添加到 trunk

+YUCHENG HU+



git-svn-id: https://svn.code.sf.net/p/hawebs/svn@127 a2543c7e-f6e9-4f8a-8bff-1ffc34733512
This commit is contained in:
YuCheng Hu
2010-06-12 00:54:13 +00:00
parent 14e316a7f8
commit 46172b5755
82 changed files with 26208 additions and 0 deletions
@@ -0,0 +1,63 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('Smarty_setup.php');
require_once('user_privileges/default_module_view.php');
require_once("modules/$currentModule/$currentModule.php");
global $mod_strings, $app_strings, $currentModule, $current_user, $theme, $singlepane_view;
$category = getParentTab();
$action = $_REQUEST['action'];
$record = $_REQUEST['record'];
$isduplicate = $_REQUEST['isDuplicate'];
$parenttab = $_REQUEST['parenttab'];
if($singlepane_view == 'true' && $action == 'CallRelatedList') {
header("Location:index.php?action=DetailView&module=$currentModule&record=$record&parenttab=$parenttab");
} else {
$tool_buttons = Button_Check($currentModule);
$focus = new $currentModule();
if($record != '') {
$focus->retrieve_entity_info($record, $currentModule);
$focus->id = $record;
}
$smarty = new vtigerCRM_Smarty;
if($isduplicate == 'true') $focus->id = '';
if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') $smarty->assign("OP_MODE",$_REQUEST['mode']);
if(!$_SESSION['rlvs'][$currentModule]) unset($_SESSION['rlvs']);
// Identify this module as custom module.
$smarty->assign('CUSTOM_MODULE', true);
$smarty->assign('APP', $app_strings);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('MODULE', $currentModule);
// TODO: Update Single Module Instance name here.
$smarty->assign('SINGLE_MOD', $currentModule);
$smarty->assign('CATEGORY', $category);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('THEME', $theme);
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CHECK', $tool_buttons);
$smarty->assign('NAME', $focus->column_fields[$focus->def_detailview_recname]);
$smarty->assign('UPDATEINFO',updateInfo($focus->id));
$related_array = getRelatedLists($currentModule, $focus);
$smarty->assign('RELATEDLISTS', $related_array);
$smarty->display('RelatedLists.tpl');
}
?>
@@ -0,0 +1,12 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include('modules/CustomView/index.php');
?>
@@ -0,0 +1,29 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $currentModule;
require_once("modules/$currentModule/$currentModule.php");
$focus = new $currentModule();
$record = $_REQUEST['record'];
$module = $_REQUEST['module'];
$return_module = $_REQUEST['return_module'];
$return_action = $_REQUEST['return_action'];
$parenttab = $_REQUEST['parenttab'];
$return_id = $_REQUEST['return_id'];
DeleteEntity($currentModule, $return_module, $focus, $record, $return_id);
if($_REQUEST['parenttab']) $parenttab = $_REQUEST['parenttab'];
header("Location: index.php?module=$return_module&action=$return_action&record=$return_id&parenttab=$parenttab&relmodule=$module");
?>
@@ -0,0 +1,83 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('Smarty_setup.php');
require_once('user_privileges/default_module_view.php');
require_once("modules/$currentModule/$currentModule.php");
global $mod_strings, $app_strings, $currentModule, $current_user, $theme, $singlepane_view;
$tool_buttons = Button_Check($currentModule);
$focus = new $currentModule();
$smarty = new vtigerCRM_Smarty();
$record = $_REQUEST['record'];
$isduplicate = $_REQUEST['isDuplicate'];
$tabid = getTabid($currentModule);
if($record != '') {
$focus->id = $record;
$focus->retrieve_entity_info($record, $currentModule);
}
if($isduplicate == 'true') $focus->id = '';
// Identify this module as custom module.
$smarty->assign('CUSTOM_MODULE', true);
$smarty->assign('APP', $app_strings);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('MODULE', $currentModule);
// TODO: Update Single Module Instance name here.
$smarty->assign('SINGLE_MOD', $currentModule);
$smarty->assign('CATEGORY', $category);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('THEME', $theme);
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$recordName = array_values(getEntityName($currentModule, $focus->id));
$recordName = $recordName[0];
$smarty->assign('NAME', $recordName);
$smarty->assign('UPDATEINFO',updateInfo($focus->id));
$smarty->assign('IS_REL_LIST',isPresentRelatedLists($currentModule));
$validationArray = split_validationdataArray(getDBValidationData($focus->tab_name, $tabid));
$smarty->assign('VALIDATION_DATA_FIELDNAME',$validationArray['fieldname']);
$smarty->assign('VALIDATION_DATA_FIELDDATATYPE',$validationArray['datatype']);
$smarty->assign('VALIDATION_DATA_FIELDLABEL',$validationArray['fieldlabel']);
$smarty->assign('EDIT_PERMISSION', isPermitted($currentModule, 'EditView', $record));
$smarty->assign('CHECK', $tool_buttons);
$smarty->assign('IS_REL_LIST', isPresentRelatedLists($currentModule));
$smarty->assign('SinglePane_View', $singlepane_view);
if($singlepane_view == 'true') {
$related_array = getRelatedLists($currentModule,$focus);
$smarty->assign("RELATEDLISTS", $related_array);
}
if(isPermitted($currentModule, 'EditView', $record) == 'yes')
$smarty->assign('EDIT_DUPLICATE', 'permitted');
if(isPermitted($currentModule, 'Delete', $record) == 'yes')
$smarty->assign('DELETE', 'permitted');
$smarty->assign('BLOCKS', getBlocks($currentModule,'detail_view','',$focus->column_fields));
// Gather the custom link information to display
include_once('vtlib/Vtiger/Link.php');
$customlink_params = Array('MODULE'=>$currentModule, 'RECORD'=>$focus->id, 'ACTION'=>$_REQUEST['action']);
$smarty->assign('CUSTOM_LINKS', Vtiger_Link::getAllByType(getTabid($currentModule), Array('DETAILVIEWBASIC','DETAILVIEW'), $customlink_params));
// END
$smarty->display('DetailView.tpl');
?>
@@ -0,0 +1,41 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $currentModule;
require_once("modules/$currentModule/$currentModule.php");
$ajaxaction = $_REQUEST['ajxaction'];
if($ajaxaction == 'DETAILVIEW')
{
$crmid = $_REQUEST['recordid'];
$tablename = $_REQUEST['tableName'];
$fieldname = $_REQUEST['fldName'];
$fieldvalue = utf8RawUrlDecode($_REQUEST['fieldValue']);
if($crmid != '')
{
$modObj = new $currentModule();
$modObj->retrieve_entity_info($crmid, $currentModule);
$modObj->column_fields[$fieldname] = $fieldvalue;
$modObj->id = $crmid;
$modObj->mode = 'edit';
$modObj->save($currentModule);
if($modObj->id != '')
{
echo ':#:SUCCESS';
}else
{
echo ':#:FAILURE';
}
}else
{
echo ':#:FAILURE';
}
}
?>
@@ -0,0 +1,88 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $app_strings, $mod_strings, $current_language, $currentModule, $theme;
require_once('Smarty_setup.php');
require_once("modules/$currentModule/$currentModule.php");
$focus = new $currentModule();
$smarty = new vtigerCRM_Smarty();
$category = getParentTab($currentModule);
$record = $_REQUEST['record'];
$isduplicate = $_REQUEST['isDuplicate'];
if($record) {
$focus->id = $record;
$focus->mode = 'edit';
$focus->retrieve_entity_info($record, $currentModule);
}
if($isduplicate == 'true') {
$focus->id = '';
$focus->mode = '';
}
$disp_view = getView($focus->mode);
if($disp_view == 'edit_view')
$smarty->assign('BLOCKS', getBlocks($currentModule, $disp_view, $focus->mode, $focus->column_fields));
else
$smarty->assign('BASBLOCKS', getBlocks($currentModule, $disp_view, $focus->mode, $focus->column_fields, 'BAS'));
$smarty->assign('OP_MODE',$disp_view);
$smarty->assign('APP', $app_strings);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('MODULE', $currentModule);
// TODO: Update Single Module Instance name here.
$smarty->assign('SINGLE_MOD', $currentModule);
$smarty->assign('CATEGORY', $category);
$smarty->assign("THEME", $theme);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CHECK', Button_Check($currentModule));
$smarty->assign('DUPLICATE', $isduplicate);
if($focus->mode == 'edit') {
$recordName = array_values(getEntityName($currentModule, $focus->id));
$recordName = $recordName[0];
$smarty->assign('NAME', $recordName);
$smarty->assign('UPDATEINFO',updateInfo($focus->id));
} else if($isduplicate) {
$recordName = array_values(getEntityName($currentModule, $record));
$recordName = $recordName[0];
$smarty->assign('NAME', $recordName);
}
if(isset($_REQUEST['return_module'])) $smarty->assign("RETURN_MODULE", $_REQUEST['return_module']);
if(isset($_REQUEST['return_action'])) $smarty->assign("RETURN_ACTION", $_REQUEST['return_action']);
if(isset($_REQUEST['return_id'])) $smarty->assign("RETURN_ID", $_REQUEST['return_id']);
if (isset($_REQUEST['return_viewname'])) $smarty->assign("RETURN_VIEWNAME", $_REQUEST['return_viewname']);
// Field Validation Information
$tabid = getTabid($currentModule);
$validationData = getDBValidationData($focus->tab_name,$tabid);
$validationArray = split_validationdataArray($validationData);
$smarty->assign("VALIDATION_DATA_FIELDNAME",$validationArray['fieldname']);
$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$validationArray['datatype']);
$smarty->assign("VALIDATION_DATA_FIELDLABEL",$validationArray['fieldlabel']);
// In case you have a date field
$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']);
// Gather the help information associated with fields
$smarty->assign('FIELDHELPINFO', vtlib_getFieldHelpInfo($currentModule));
// END
if($focus->mode == 'edit') $smarty->display('salesEditView.tpl');
else $smarty->display('CreateView.tpl');
?>
@@ -0,0 +1,12 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/utils/ExportRecords.php');
?>
@@ -0,0 +1,12 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('modules/Import/index.php');
?>
@@ -0,0 +1,154 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $app_strings, $mod_strings, $current_language, $currentModule, $theme;
global $list_max_entries_per_page;
require_once('Smarty_setup.php');
require_once('include/ListView/ListView.php');
require_once('modules/CustomView/CustomView.php');
require_once('include/DatabaseUtil.php');
require_once("modules/$currentModule/$currentModule.php");
$category = getParentTab();
$url_string = '';
$tool_buttons = Button_Check($currentModule);
$list_buttons = Array();
if(isPermitted($currentModule,'Delete','') == 'yes') $list_buttons['del'] = $app_strings[LBL_MASS_DELETE];
if(isPermitted($currentModule,'EditView','') == 'yes') {
$list_buttons['mass_edit'] = $app_strings[LBL_MASS_EDIT];
// Mass Edit could be used to change the owner as well!
//$list_buttons['c_owner'] = $app_strings[LBL_CHANGE_OWNER];
}
$focus = new $currentModule();
$sorder = $focus->getSortOrder();
$order_by = $focus->getOrderBy();
$_SESSION[$currentModule."_Order_by"] = $order_by;
$_SESSION[$currentModule."_Sort_Order"]=$sorder;
$smarty = new vtigerCRM_Smarty();
// Identify this module as custom module.
$smarty->assign('CUSTOM_MODULE', true);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('APP', $app_strings);
$smarty->assign('MODULE', $currentModule);
$smarty->assign('SINGLE_MOD', $currentModule);
$smarty->assign('CATEGORY', $category);
$smarty->assign('BUTTONS', $list_buttons);
$smarty->assign('CHECK', $tool_buttons);
$smarty->assign("THEME", $theme);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('CHANGE_OWNER', getUserslist());
$smarty->assign('CHANGE_GROUP_OWNER', getGroupslist());
// Enabling Module Search
$url_string = '';
if($_REQUEST['query'] == 'true') {
list($where, $ustring) = split('#@@#', getWhereCondition($currentModule));
$url_string .= "&query=true$ustring";
$smarty->assign('SEARCH_URL', $url_string);
}
// Custom View
$customView = new CustomView($currentModule);
$viewid = $customView->getViewId($currentModule);
$customview_html = $customView->getCustomViewCombo($viewid);
$viewinfo = $customView->getCustomViewByCvid($viewid);
$smarty->assign("VIEWID", $viewid);
if($viewinfo['viewname'] == 'All') $smarty->assign('ALL', 'All');
if($viewid != '0') {
$listquery = getListQuery($currentModule);
$list_query= $customView->getModifiedCvListQuery($viewid, $listquery, $currentModule);
} else {
$list_query= getListQuery($currentModule);
}
if($where != '') {
$list_query = "$list_query AND $where";
}
// Sorting
if($order_by) {
if($order_by == 'smownerid') $list_query .= ' ORDER BY user_name '.$sorder;
else {
$tablename = getTableNameForField($currentModule, $order_by);
$tablename = ($tablename != '')? ($tablename . '.') : '';
$list_query .= ' ORDER BY ' . $tablename . $order_by . ' ' . $sorder;
}
}
$countQuery = $adb->query( mkCountQuery($list_query) );
$recordCount= $adb->query_result($countQuery,0,'count');
// Set paging start value.
$start = 1;
if(isset($_REQUEST['start'])) { $start = $_REQUEST['start']; }
else { $start = $_SESSION['lvs'][$currentModule]['start']; }
// Total records is less than a page now.
if($recordCount <= $list_max_entries_per_page) $start = 1;
// Save in session
if(empty($start)) $start = 1; // Reset to proper state
$_SESSION['lvs'][$currentModule]['start'] = $start;
$navigation_array = getNavigationValues($start, $recordCount, $list_max_entries_per_page);
$start_rec = $navigation_array['start'];
$end_rec = $navigation_array['end_val'];
$_SESSION['nav_start']=$start_rec;
$_SESSION['nav_end']=$end_rec;
if ($start_rec ==0) $limit_start_rec = 0;
else $limit_start_rec = $start_rec -1;
$list_result = $adb->query( $list_query . " LIMIT $limit_start_rec, $list_max_entries_per_page" );
$record_string= $app_strings['LBL_SHOWING']." $start_rec - $end_rec " . $app_strings['LBL_LIST_OF'] ." ".$recordCount;
$smarty->assign('RECORD_COUNTS', $record_string);
$smarty->assign("CUSTOMVIEW_OPTION",$customview_html);
// Navigation
$start = $_SESSION['lvs'][$currentModule]['start'];
$navigation_array = getNavigationValues($start, $recordCount, $list_max_entries_per_page);
$navigationOutput = getTableHeaderNavigation($navigation_array, $url_string, $currentModule, 'index', $viewid);
$smarty->assign("NAVIGATION", $navigationOutput);
$listview_header = getListViewHeader($focus,$currentModule,$url_string,$sorder,$order_by,'',$customView);
$listview_entries = getListViewEntries($focus,$currentModule,$list_result,$navigation_array,'','','EditView','Delete',$customView);
$listview_header_search = getSearchListHeaderValues($focus,$currentModule,$url_string,$sorder,$order_by,'',$customView);
$smarty->assign('LISTHEADER', $listview_header);
$smarty->assign('LISTENTITY', $listview_entries);
$smarty->assign('SEARCHLISTHEADER',$listview_header_search);
// Module Search
$alphabetical = AlphabeticalSearch($currentModule,'index',$focus->def_basicsearch_col,'true','basic','','','','',$viewid);
$fieldnames = getAdvSearchfields($currentModule);
$criteria = getcriteria_options();
$smarty->assign("ALPHABETICAL", $alphabetical);
$smarty->assign("FIELDNAMES", $fieldnames);
$smarty->assign("CRITERIA", $criteria);
if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '')
$smarty->display("ListViewEntries.tpl");
else
$smarty->display('ListView.tpl');
?>
@@ -0,0 +1,8 @@
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
@@ -0,0 +1,366 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('data/CRMEntity.php');
require_once('data/Tracker.php');
class ModuleClass extends CRMEntity {
var $db, $log; // Used in class functions like CRMEntity
var $table_name = 'vtiger_payslip';
var $table_index= 'payslipid';
var $column_fields = Array();
// Indicator if this is a custom module or standard module
var $IsCustomModule = true;
// Mandatory for function getGroupName
// Array(groupTableName, groupColumnId)
// groupTableName should have (groupname column)
var $groupTable = Array('vtiger_payslipgrouprel', 'payslipid');
// Mandatory table for supporting custom fields
var $customFieldTable = Array('vtiger_payslipcf', 'payslipid');
// Mandatory for Saving, Include tables related to this module.
var $tab_name = Array('vtiger_crmentity', 'vtiger_payslip', 'vtiger_payslipcf');
// Mandatory for Saving, Include the table name and index column mapping here.
var $tab_name_index = Array(
'vtiger_crmentity' => 'crmid',
'vtiger_payslip' => 'payslipid',
'vtiger_payslipcf' => 'payslipid');
// Mandatory for Listing
var $list_fields = Array (
// Field Label=> Array(tablename, columnname)
'Payslip Name'=> Array('payslip', 'payslipname'),
'Assigned To' => Array('crmentity','smownerid')
);
var $list_fields_name = Array(
// Field Label=>fieldname
'Payslip Name'=> 'payslipname',
'Assigned To' => 'assigned_user_id'
);
// Make the field link detail view from list view (Fieldname)
var $list_link_field = 'payslipname';
// For Popup listview
var $search_fields = Array(
'Payslip Name'=> Array('payslip', 'payslipname')
);
var $search_fields_name = Array(
'Payslip Name'=> 'payslipname'
);
var $popup_fields = Array('payslipname');
var $sortby_fields = Array('payslipname', 'payslipmonth', 'smownerid', 'modifiedtime');
// For alphabetical search
var $def_basicsearch_col = 'payslipname';
// Column value to use on detail view record text display.
var $def_detailview_recname = 'payslipname';
// Required information for enabling Import feature
var $required_fields = Array('payslipname'=>1);
// Callback function list during Importing
var $special_functions = array("set_import_assigned_user");
var $default_order_by = 'payslipname';
var $default_sort_order='ASC';
function __construct() {
global $log, $currentModule;
$this->column_fields = getColumnFields($currentModule);
$this->db = new PearDatabase();
$this->log = $log;
}
function getSortOrder() {
global $currentModule;
$sortorder = $this->default_sort_order;
if($_REQUEST['sorder']) $sortorder = $this->db->sql_escape_string($_REQUEST['sorder']);
else if($_SESSION[$currentModule.'_Sort_Order'])
$sortorder = $_SESSION[$currentModule.'_Sort_Order'];
return $sortorder;
}
function getOrderBy() {
global $currentModule;
$orderby = $this->default_order_by;
if($_REQUEST['order_by']) $orderby = $this->db->sql_escape_string($_REQUEST['order_by']);
else if($_SESSION[$currentModule.'_Order_By'])
$orderby = $_SESSION[$currentModule.'_Order_By'];
return $orderby;
}
function save_module($module) {
}
/**
* Return query to use based on given modulename, fieldname
* Useful to handle specific case handling for Popup
*/
function getQueryByModuleField($module, $fieldname, $srcrecord) {
// $srcrecord could be empty
}
/**
* Get list view query (send more WHERE clause condition if required)
*/
function getListQuery($module, $usewhere=false) {
$query = "SELECT vtiger_crmentity.*, $this->table_name.*";
// Select Custom Field Table Columns if present
if(!empty($this->customFieldTable)) $query .= ", " . $this->customFieldTable[0] . ".* ";
$query .= " FROM $this->table_name";
$query .= " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $this->table_name.$this->table_index";
// Consider custom table join as well.
if(!empty($this->customFieldTable)) {
$query .= " INNER JOIN ".$this->customFieldTable[0]." ON ".$this->customFieldTable[0].'.'.$this->customFieldTable[1] .
" = $this->table_name.$this->table_index";
}
$query .= " LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid";
if(!empty($this->groupTable)) {
$query .= "
LEFT JOIN " . $this->groupTable[0] . " ON " . $this->groupTable[0].'.'.$this->groupTable[1] . " = $this->table_name.$this->table_index
LEFT JOIN vtiger_groups ON vtiger_groups.groupname = " . $this->groupTable[0] . '.groupname';
}
$query .= " WHERE vtiger_crmentity.deleted = 0";
$query .= $this->getListViewSecurityParameter($module);
if($usewhere) {
$query .= " $usewhere ";
}
return $query;
}
/**
* Apply security restriction (sharing privilege) query part for List view.
*/
function getListViewSecurityParameter($module) {
global $current_user;
require('user_privileges/user_privileges_'.$current_user->id.'.php');
require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
$sec_query = '';
$tabid = getTabid($module);
if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1
&& $defaultOrgSharingPermission[$tabid] == 3) {
$sec_query .= " AND (vtiger_crmentity.smownerid in($current_user->id) OR vtiger_crmentity.smownerid IN
(
SELECT vtiger_user2role.userid FROM vtiger_user2role
INNER JOIN vtiger_users ON vtiger_users.id=vtiger_user2role.userid
INNER JOIN vtiger_role ON vtiger_role.roleid=vtiger_user2role.roleid
WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%'
)
OR vtiger_crmentity.smownerid IN
(
SELECT shareduserid FROM vtiger_tmp_read_user_sharing_per
WHERE userid=".$current_user->id." AND tabid=".$tabid."
)
OR
(
vtiger_crmentity.smownerid in (0)";
if(!empty($this->groupTable)) {
$sec_query .= " AND
(";
// Build the query based on the group association of current user.
if(sizeof($current_user_groups) > 0) {
$sec_query .= " vtiger_groups.groupid IN (". implode(",", $current_user_groups) .") OR ";
}
$sec_query .= " vtiger_groups.groupid IN
(
SELECT vtiger_tmp_read_group_sharing_per.sharedgroupid
FROM vtiger_tmp_read_group_sharing_per
WHERE userid=".$current_user->id." and tabid=".$tabid."
)";
$sec_query .= ") ";
}
$sec_query .= ")
)";
}
return $sec_query;
}
/**
* Create query to export the records.
*/
function create_export_query($where)
{
global $current_user;
$thismodule = $_REQUEST['module'];
include("include/utils/ExportUtils.php");
//To get the Permitted fields query and the permitted fields list
$sql = getPermittedFieldsQuery($thismodule, "detail_view");
$fields_list = getFieldsListFromQuery($sql);
$query = "SELECT $fields_list, ". $this->groupTable[0].'.'.$this->groupTable[1] ." as 'Assigned To Group',
CASE WHEN (vtiger_users.user_name NOT LIKE '') THEN vtiger_users.user_name ELSE vtiger_groups.groupname END
AS user_name FROM vtiger_crmentity INNER JOIN $this->table_name ON vtiger_crmentity.crmid=$this->table_name.$this->table_index";
if(!empty($this->customFieldTable)) {
$query .= " INNER JOIN ".$this->customFieldTable[0]." ON ".$this->customFieldTable[0].'.'.$this->customFieldTable[1] .
" = $this->table_name.$this->table_index";
}
$query .= "
LEFT JOIN " . $this->groupTable[0] . " ON " . $this->groupTable[0].'.'.$this->groupTable[1] . " = $this->table_name.$this->table_index
LEFT JOIN vtiger_groups ON vtiger_groups.groupname = " . $this->groupTable[0] . '.groupname';
$query .= " LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id and vtiger_users.status='Active'";
$where_auto = " vtiger_crmentity.deleted=0";
if($where != '') $query .= " WHERE ($where) AND $where_auto";
else $query .= " WHERE $where_auto";
require('user_privileges/user_privileges_'.$current_user->id.'.php');
require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
// Security Check for Field Access
if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[7] == 3)
{
//Added security check to get the permitted records only
$query = $query." ".getListViewSecurityParameter($thismodule);
}
return $query;
}
/**
* Initialize this instance for importing.
*/
function initImport($module) {
$this->db = new PearDatabase();
$this->initImportableFields($module);
}
/**
* Create list query to be shown at the last step of the import.
* Called From: modules/Import/UserLastImport.php
*/
function create_import_query($module) {
global $current_user;
$query = "SELECT vtiger_crmentity.crmid, vtiger_users.user_name, $this->table_name.* FROM $this->table_name
INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $this->table_name.$this->table_index
LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_crmentity.crmid
LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
WHERE vtiger_users_last_import.assigned_user_id='$current_user->id'
AND vtiger_users_last_import.bean_type='$module'
AND vtiger_users_last_import.deleted=0
AND vtiger_users.status = 'Active'";
return $query;
}
/**
* Delete the last imported records.
*/
function undo_import($module, $user_id) {
global $adb;
$count = 0;
$query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='$module' AND deleted=0";
$result1 = $adb->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error());
while ( $row1 = $adb->fetchByAssoc($result1))
{
$query2 = "update vtiger_crmentity set deleted=1 where crmid=?";
$result2 = $adb->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error());
$count++;
}
return $count;
}
/**
* Transform the value while exporting (if required)
*/
function transform_export_value($key, $value) {
return parent::transform_export_value($key, $value);
}
/**
* Function which will set the assigned user id for import record.
*/
function set_import_assigned_user()
{
global $current_user, $adb;
$record_user = $this->column_fields["assigned_user_id"];
if($record_user != $current_user->id){
$sqlresult = $adb->pquery("select id from vtiger_users where id = ?", array($record_user));
if($this->db->num_rows($sqlresult)!= 1) {
$this->column_fields["assigned_user_id"] = $current_user->id;
} else {
$row = $adb->fetchByAssoc($sqlresult, -1, false);
if (isset($row['id']) && $row['id'] != -1) {
$this->column_fields["assigned_user_id"] = $row['id'];
} else {
$this->column_fields["assigned_user_id"] = $current_user->id;
}
}
}
}
/**
* Invoked when special actions are performed on the module.
* @param String Module name
* @param String Event Type (module.postinstall, module.disabled, module.enabled, module.preuninstall)
*/
function vtlib_handler($modulename, $event_type) {
if($event_type == 'module.postinstall') {
// TODO Handle post installation actions
} else if($event_type == 'module.disabled') {
// TODO Handle actions when this module is disabled.
} else if($event_type == 'module.enabled') {
// TODO Handle actions when this module is enabled.
} else if($event_type == 'module.preuninstall') {
// TODO Handle actions when this module is about to be deleted.
} else if($event_type == 'module.preupdate') {
// TODO Handle actions before this module is updated.
} else if($event_type == 'module.postupdate') {
// TODO Handle actions after this module is updated.
}
}
/**
* Handle saving related module information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
// function save_related_module($module, $crmid, $with_module, $with_crmid) { }
/**
* Handle deleting related module information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
//function delete_related_module($module, $crmid, $with_module, $with_crmid) { }
/**
* Handle getting related list information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
//function get_related_list($id, $cur_tab_id, $rel_tab_id, $actions=false) { }
}
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/Ajax/CommonAjax.php');
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('Popup.php');
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/quickcreate.php');
?>
@@ -0,0 +1,35 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $current_user, $currentModule;
require_once("modules/$currentModule/$currentModule.php");
$focus = new $currentModule();
setObjectValuesFromRequest($focus);
$mode = $_REQUEST['mode'];
$record=$_REQUEST['record'];
if($mode) $focus->mode = $mode;
if($record)$focus->id = $record;
$focus->save($currentModule);
$return_id = $focus->id;
if($_REQUEST['parenttab'] != '') $parenttab = $_REQUEST['parenttab'];
if($_REQUEST['return_module'] != '') $return_module = $_REQUEST['return_module'];
else $return_module = $currentModule;
if($_REQUEST['return_action'] != '') $return_action = $_REQUEST['return_action'];
else $return_action = "DetailView";
if($_REQUEST['return_id'] != '') $return_id = $_REQUEST['return_id'];
header("Location: index.php?action=$return_action&module=$return_module&record=$return_id&parenttab=$parenttab&start=".$_REQUEST['pagenumber'].$search);
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/Ajax/TagCloud.php');
?>
@@ -0,0 +1,13 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $currentModule;
include_once("modules/$currentModule/ListView.php");
?>
@@ -0,0 +1,19 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
$mod_strings = Array(
'ModuleName' => 'Module Name',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'LBL_MODULEBLOCK_INFORMATION' => 'ModuleBlock Information',
'ModuleFieldLabel' => 'ModuleFieldLabel Text',
);
?>
@@ -0,0 +1,58 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/database/PearDatabase.php');
@include_once('user_privileges/default_module_view.php');
global $adb, $singlepane_view, $currentModule;
$idlist = $_REQUEST['idlist'];
$destinationModule = $_REQUEST['destination_module'];
$parenttab = $_REQUEST['parenttab'];
$forCRMRecord = $_REQUEST['parentid'];
$mode = $_REQUEST['mode'];
// Split the string of ids
if($mode == 'delete') {
$ids = explode (";",trim($idlist,";"));
if(function_exists('checkFileAccess')) {
checkFileAccess("modules/$currentModule/$currentModule.php");
}
require_once("modules/$currentModule/$currentModule.php");
$focus = new $currentModule();
if(method_exists($focus, 'delete_related_module')) {
$focus->delete_related_module($currentModule, $forCRMRecord, $destinationModule, $ids);
}
if($singlepane_view == 'true') {
header("Location: index.php?module=$currentModule&record=$forCRMRecord&action=DetailView&parenttab=$parenttab");
} else {
header("Location: index.php?module=$currentModule&record=$forCRMRecord&action=CallRelatedList&parenttab=$parenttab");
}
exit;
}
if(!empty($_REQUEST['idlist'])) {
$ids = explode (";",trim($idlist,";"));
if(function_exists('checkFileAccess')) {
checkFileAccess("modules/$currentModule/$currentModule.php");
}
require_once("modules/$currentModule/$currentModule.php");
$focus = new $currentModule();
if(method_exists($focus, 'save_related_module')) {
$focus->save_related_module($currentModule, $forCRMRecord, $destinationModule, $ids);
}
if($singlepane_view == 'true') {
header("Location: index.php?module=$currentModule&record=$forCRMRecord&action=DetailView&parenttab=$parenttab");
} else {
header("Location: index.php?module=$currentModule&record=$forCRMRecord&action=CallRelatedList&parenttab=$parenttab");
}
} else if(!empty($_REQUEST['entityid'])){
// TODO: Handle this case
}
?>
@@ -0,0 +1,71 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('Smarty_setup.php');
require_once('user_privileges/default_module_view.php');
global $mod_strings, $app_strings, $currentModule, $current_user, $theme, $singlepane_view;
$category = getParentTab();
$action = vtlib_purify($_REQUEST['action']);
$record = vtlib_purify($_REQUEST['record']);
$isduplicate = vtlib_purify($_REQUEST['isDuplicate']);
if($singlepane_view == 'true' && $action == 'CallRelatedList') {
header("Location:index.php?action=DetailView&module=$currentModule&record=$record&parenttab=$category");
} else {
$tool_buttons = Button_Check($currentModule);
$focus = CRMEntity::getInstance($currentModule);
if($record != '') {
$focus->retrieve_entity_info($record, $currentModule);
$focus->id = $record;
}
$smarty = new vtigerCRM_Smarty;
if($isduplicate == 'true') $focus->id = '';
if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode']));
if(!$_SESSION['rlvs'][$currentModule]) unset($_SESSION['rlvs']);
// Identify this module as custom module.
$smarty->assign('CUSTOM_MODULE', true);
$smarty->assign('APP', $app_strings);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('MODULE', $currentModule);
// TODO: Update Single Module Instance name here.
$smarty->assign('SINGLE_MOD', getTranslatedString($currentModule));
$smarty->assign('CATEGORY', $category);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('THEME', $theme);
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CHECK', $tool_buttons);
$smarty->assign('NAME', $focus->column_fields[$focus->def_detailview_recname]);
$smarty->assign('UPDATEINFO',updateInfo($focus->id));
// Module Sequence Numbering
$mod_seq_field = getModuleSequenceField($currentModule);
if ($mod_seq_field != null) {
$mod_seq_id = $focus->column_fields[$mod_seq_field['name']];
} else {
$mod_seq_id = $focus->id;
}
$smarty->assign('MOD_SEQ_ID', $mod_seq_id);
// END
$related_array = getRelatedLists($currentModule, $focus);
$smarty->assign('RELATEDLISTS', $related_array);
$smarty->display('RelatedLists.tpl');
}
?>
@@ -0,0 +1,12 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include('modules/CustomView/index.php');
?>
@@ -0,0 +1,27 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $currentModule;
$focus = CRMEntity::getInstance($currentModule);
$record = vtlib_purify($_REQUEST['record']);
$module = vtlib_purify($_REQUEST['module']);
$return_module = vtlib_purify($_REQUEST['return_module']);
$return_action = vtlib_purify($_REQUEST['return_action']);
$return_id = vtlib_purify($_REQUEST['return_id']);
$parenttab = getParentTab();
//Added to fix 4600
$url = getBasic_Advance_SearchURL();
DeleteEntity($currentModule, $return_module, $focus, $record, $return_id);
header("Location: index.php?module=$return_module&action=$return_action&record=$return_id&parenttab=$parenttab&relmodule=$module".$url);
?>
@@ -0,0 +1,102 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('Smarty_setup.php');
require_once('user_privileges/default_module_view.php');
global $mod_strings, $app_strings, $currentModule, $current_user, $theme, $singlepane_view;
$focus = CRMEntity::getInstance($currentModule);
$tool_buttons = Button_Check($currentModule);
$smarty = new vtigerCRM_Smarty();
$record = $_REQUEST['record'];
$isduplicate = vtlib_purify($_REQUEST['isDuplicate']);
$tabid = getTabid($currentModule);
$category = getParentTab($currentModule);
if($record != '') {
$focus->id = $record;
$focus->retrieve_entity_info($record, $currentModule);
}
if($isduplicate == 'true') $focus->id = '';
// Identify this module as custom module.
$smarty->assign('CUSTOM_MODULE', true);
$smarty->assign('APP', $app_strings);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('MODULE', $currentModule);
// TODO: Update Single Module Instance name here.
$smarty->assign('SINGLE_MOD', 'SINGLE_'.$currentModule);
$smarty->assign('CATEGORY', $category);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('THEME', $theme);
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$recordName = array_values(getEntityName($currentModule, $focus->id));
$recordName = $recordName[0];
$smarty->assign('NAME', $recordName);
$smarty->assign('UPDATEINFO',updateInfo($focus->id));
// Module Sequence Numbering
$mod_seq_field = getModuleSequenceField($currentModule);
if ($mod_seq_field != null) {
$mod_seq_id = $focus->column_fields[$mod_seq_field['name']];
} else {
$mod_seq_id = $focus->id;
}
$smarty->assign('MOD_SEQ_ID', $mod_seq_id);
// END
$validationArray = split_validationdataArray(getDBValidationData($focus->tab_name, $tabid));
$smarty->assign('VALIDATION_DATA_FIELDNAME',$validationArray['fieldname']);
$smarty->assign('VALIDATION_DATA_FIELDDATATYPE',$validationArray['datatype']);
$smarty->assign('VALIDATION_DATA_FIELDLABEL',$validationArray['fieldlabel']);
$smarty->assign('EDIT_PERMISSION', isPermitted($currentModule, 'EditView', $record));
$smarty->assign('CHECK', $tool_buttons);
if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){
$recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id);
VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id);
}
$smarty->assign('IS_REL_LIST', isPresentRelatedLists($currentModule));
$smarty->assign('SinglePane_View', $singlepane_view);
if($singlepane_view == 'true') {
$related_array = getRelatedLists($currentModule,$focus);
$smarty->assign("RELATEDLISTS", $related_array);
}
if(isPermitted($currentModule, 'EditView', $record) == 'yes')
$smarty->assign('EDIT_DUPLICATE', 'permitted');
if(isPermitted($currentModule, 'Delete', $record) == 'yes')
$smarty->assign('DELETE', 'permitted');
$smarty->assign('BLOCKS', getBlocks($currentModule,'detail_view','',$focus->column_fields));
// Gather the custom link information to display
include_once('vtlib/Vtiger/Link.php');
$customlink_params = Array('MODULE'=>$currentModule, 'RECORD'=>$focus->id, 'ACTION'=>vtlib_purify($_REQUEST['action']));
$smarty->assign('CUSTOM_LINKS', Vtiger_Link::getAllByType(getTabid($currentModule), Array('DETAILVIEWBASIC','DETAILVIEW'), $customlink_params));
// END
// Record Change Notification
$focus->markAsViewed($current_user->id);
// END
$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true));
$smarty->display('DetailView.tpl');
?>
@@ -0,0 +1,39 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $currentModule;
$modObj = CRMEntity::getInstance($currentModule);
$ajaxaction = $_REQUEST["ajxaction"];
if($ajaxaction == 'DETAILVIEW')
{
$crmid = $_REQUEST['recordid'];
$tablename = $_REQUEST['tableName'];
$fieldname = $_REQUEST['fldName'];
$fieldvalue = utf8RawUrlDecode($_REQUEST['fieldValue']);
if($crmid != '')
{
$modObj->retrieve_entity_info($crmid, $currentModule);
$modObj->column_fields[$fieldname] = $fieldvalue;
$modObj->id = $crmid;
$modObj->mode = 'edit';
$modObj->save($currentModule);
if($modObj->id != '')
{
echo ':#:SUCCESS';
}else
{
echo ':#:FAILURE';
}
}else
{
echo ':#:FAILURE';
}
}
?>
@@ -0,0 +1,113 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $app_strings, $mod_strings, $current_language, $currentModule, $theme;
require_once('Smarty_setup.php');
$focus = CRMEntity::getInstance($currentModule);
$smarty = new vtigerCRM_Smarty();
$category = getParentTab($currentModule);
$record = $_REQUEST['record'];
$isduplicate = vtlib_purify($_REQUEST['isDuplicate']);
//added to fix the issue4600
$searchurl = getBasic_Advance_SearchURL();
$smarty->assign("SEARCH", $searchurl);
//4600 ends
if($record) {
$focus->id = $record;
$focus->mode = 'edit';
$focus->retrieve_entity_info($record, $currentModule);
}
if($isduplicate == 'true') {
$focus->id = '';
$focus->mode = '';
}
if(empty($_REQUEST['record']) && $focus->mode != 'edit'){
setObjectValuesFromRequest($focus);
}
$disp_view = getView($focus->mode);
if($disp_view == 'edit_view')
$smarty->assign('BLOCKS', getBlocks($currentModule, $disp_view, $focus->mode, $focus->column_fields));
else
$smarty->assign('BASBLOCKS', getBlocks($currentModule, $disp_view, $focus->mode, $focus->column_fields, 'BAS'));
$smarty->assign('OP_MODE',$disp_view);
$smarty->assign('APP', $app_strings);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('MODULE', $currentModule);
// TODO: Update Single Module Instance name here.
$smarty->assign('SINGLE_MOD', getTranslatedString('SINGLE_'.$currentModule));
$smarty->assign('CATEGORY', $category);
$smarty->assign("THEME", $theme);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CHECK', Button_Check($currentModule));
$smarty->assign('DUPLICATE', $isduplicate);
if($focus->mode == 'edit' || $isduplicate) {
$recordName = array_values(getEntityName($currentModule, $record));
$recordName = $recordName[0];
$smarty->assign('NAME', $recordName);
$smarty->assign('UPDATEINFO',updateInfo($record));
}
if(isset($_REQUEST['return_module'])) $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module']));
if(isset($_REQUEST['return_action'])) $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action']));
if(isset($_REQUEST['return_id'])) $smarty->assign("RETURN_ID", vtlib_purify($_REQUEST['return_id']));
if (isset($_REQUEST['return_viewname'])) $smarty->assign("RETURN_VIEWNAME", vtlib_purify($_REQUEST['return_viewname']));
// Field Validation Information
$tabid = getTabid($currentModule);
$validationData = getDBValidationData($focus->tab_name,$tabid);
$validationArray = split_validationdataArray($validationData);
$smarty->assign("VALIDATION_DATA_FIELDNAME",$validationArray['fieldname']);
$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$validationArray['datatype']);
$smarty->assign("VALIDATION_DATA_FIELDLABEL",$validationArray['fieldlabel']);
// In case you have a date field
$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']);
global $adb;
// Module Sequence Numbering
$mod_seq_field = getModuleSequenceField($currentModule);
if($focus->mode != 'edit' && $mod_seq_field != null) {
$autostr = getTranslatedString('MSG_AUTO_GEN_ON_SAVE');
$mod_seq_string = $adb->pquery("SELECT prefix, cur_id from vtiger_modentity_num where semodule = ? and active=1",array($currentModule));
$mod_seq_prefix = $adb->query_result($mod_seq_string,0,'prefix');
$mod_seq_no = $adb->query_result($mod_seq_string,0,'cur_id');
if($adb->num_rows($mod_seq_string) == 0 || $focus->checkModuleSeqNumber($focus->table_name, $mod_seq_field['column'], $mod_seq_prefix.$mod_seq_no))
echo '<br><font color="#FF0000"><b>'. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label'])
.' - '. getTranslatedString('LBL_CLICK') .' <a href="index.php?module=Settings&action=CustomModEntityNo&parenttab=Settings&selmodule='.$currentModule.'">'.getTranslatedString('LBL_HERE').'</a> '
. getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .'</b></font>';
else
$smarty->assign("MOD_SEQ_ID",$autostr);
} else {
$smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]);
}
// END
// Gather the help information associated with fields
$smarty->assign('FIELDHELPINFO', vtlib_getFieldHelpInfo($currentModule));
// END
if($focus->mode == 'edit') {
$smarty->display('salesEditView.tpl');
} else {
$smarty->display('CreateView.tpl');
}
?>
@@ -0,0 +1,12 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/utils/ExportRecords.php');
?>
@@ -0,0 +1,106 @@
<?php
/*+********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
********************************************************************************/
require_once('Smarty_setup.php');
require_once('include/utils/utils.php');
require_once('database/DatabaseConnection.php');
global $mod_strings, $app_strings, $app_list_strings;
global $current_language, $currentModule, $current_userid, $theme;
require_once('themes/'.$theme.'/layout_utils.php');
$req_module = vtlib_purify($_REQUEST['module']);
$focus = CRMEntity::getInstance($req_module);
$return_module=vtlib_purify($_REQUEST['module']);
$delete_idstring=vtlib_purify($_REQUEST['idlist']);
$parenttab = getParenttab();
$smarty = new vtigerCRM_Smarty;
$ids_list = array();
$errormsg = '';
if(isset($_REQUEST['del_rec']))
{
$url = getBasic_Advance_SearchURL();
$delete_id_array=explode(",",$delete_idstring,-1);
foreach ($delete_id_array as $id)
{
if(isPermitted($req_module,'Delete',$id) == 'yes') {
$sql="update vtiger_crmentity set deleted=1 where crmid=?";
$result = $adb->pquery($sql, array($id));
DeleteEntity($req_module,$return_module,$focus,$id,"");
}
else {
$ids_list[] = $id;
}
}
if(count($ids_list) > 0) {
$ret = getEntityName($req_module,$ids_list);
if(count($ret) > 0)
{
$errormsg = implode(',',$ret);
}
echo "<table border='0' cellpadding='5' cellspacing='0' width='100%' height='450px'><tr><td align='center'>";
echo "<div style='border: 3px solid rgb(153, 153, 153); background-color: rgb(255, 255, 255); width: 55%; position: relative; z-index: 10000000;'>
<table border='0' cellpadding='5' cellspacing='0' width='98%'>
<tbody><tr>
<td rowspan='2' width='11%'><img src='themes/$theme/images/denied.gif' ></td>
<td style='border-bottom: 1px solid rgb(204, 204, 204);' nowrap='nowrap' width='70%'>
<span class='genHeaderSmall'>$app_strings[LBL_DUP_PERMISSION] $req_module $errormsg</span></td>
</tr>
<tr>
<td class='small' align='right' nowrap='nowrap'>
<a href='javascript:window.location.reload();'>$app_strings[LBL_GO_BACK]</a><br>
</td>
</tr>
</tbody></table>
</div>";
echo "</td></tr></table>";
exit;
}
}
include("include/saveMergeCriteria.php");
$ret_arr=getDuplicateRecordsArr($req_module);
$fld_values=$ret_arr[0];
$total_num_group=count($fld_values);
$fld_name=$ret_arr[1];
$ui_type=$ret_arr[2];
$smarty->assign("NAVIGATION",$ret_arr["navigation"]);//Added for page navigation
$smarty->assign("MODULE",$req_module);
$smarty->assign("NUM_GROUP",$total_num_group);
$smarty->assign("FIELD_NAMES",$fld_name);
$smarty->assign("CATEGORY",$parenttab);
$smarty->assign("ALL_VALUES",$fld_values);
if(isPermitted($req_module,'Delete','') == 'yes')
$button_del = $app_strings['LBL_MASS_DELETE'];
$smarty->assign("DELETE",$button_del);
$smarty->assign("MOD", return_module_language($current_language,$req_module));
$smarty->assign("THEME", $theme);
$smarty->assign("IMAGE_PATH",$image_path);
$smarty->assign("APP", $app_strings);
$smarty->assign("CMOD", $mod_strings);
$smarty->assign("MODE",'view');
if(isset($_REQUEST['button_view']))
{
$smarty->assign("VIEW",'true');
}
if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '')
$smarty->display("FindDuplicateAjax.tpl");
else
$smarty->display('FindDuplicateDisplay.tpl');
?>
@@ -0,0 +1,12 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('modules/Import/index.php');
?>
@@ -0,0 +1,190 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $app_strings, $mod_strings, $current_language, $currentModule, $theme;
global $list_max_entries_per_page;
require_once('Smarty_setup.php');
require_once('include/ListView/ListView.php');
require_once('modules/CustomView/CustomView.php');
require_once('include/DatabaseUtil.php');
checkFileAccess("modules/$currentModule/$currentModule.php");
require_once("modules/$currentModule/$currentModule.php");
$category = getParentTab();
$url_string = '';
$tool_buttons = Button_Check($currentModule);
$list_buttons = Array();
if(isPermitted($currentModule,'Delete','') == 'yes') $list_buttons['del'] = $app_strings[LBL_MASS_DELETE];
if(isPermitted($currentModule,'EditView','') == 'yes') {
$list_buttons['mass_edit'] = $app_strings[LBL_MASS_EDIT];
// Mass Edit could be used to change the owner as well!
//$list_buttons['c_owner'] = $app_strings[LBL_CHANGE_OWNER];
}
$focus = new $currentModule();
$focus->initSortbyField($currentModule);
$sorder = $focus->getSortOrder();
$order_by = $focus->getOrderBy();
$_SESSION[$currentModule."_Order_by"] = $order_by;
$_SESSION[$currentModule."_Sort_Order"]=$sorder;
$smarty = new vtigerCRM_Smarty();
// Identify this module as custom module.
$smarty->assign('CUSTOM_MODULE', true);
$smarty->assign('MOD', $mod_strings);
$smarty->assign('APP', $app_strings);
$smarty->assign('MODULE', $currentModule);
$smarty->assign('SINGLE_MOD', getTranslatedString('SINGLE_'.$currentModule));
$smarty->assign('CATEGORY', $category);
$smarty->assign('BUTTONS', $list_buttons);
$smarty->assign('CHECK', $tool_buttons);
$smarty->assign('THEME', $theme);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('CHANGE_OWNER', getUserslist());
$smarty->assign('CHANGE_GROUP_OWNER', getGroupslist());
// Enabling Module Search
$url_string = '';
if($_REQUEST['query'] == 'true') {
list($where, $ustring) = split('#@@#', getWhereCondition($currentModule));
$url_string .= "&query=true$ustring";
$smarty->assign('SEARCH_URL', $url_string);
}
// Custom View
$customView = new CustomView($currentModule);
$viewid = $customView->getViewId($currentModule);
$customview_html = $customView->getCustomViewCombo($viewid);
$viewinfo = $customView->getCustomViewByCvid($viewid);
// Feature available from 5.1
if(method_exists($customView, 'isPermittedChangeStatus')) {
// Approving or Denying status-public by the admin in CustomView
$statusdetails = $customView->isPermittedChangeStatus($viewinfo['status']);
// To check if a user is able to edit/delete a CustomView
$edit_permit = $customView->isPermittedCustomView($viewid,'EditView',$currentModule);
$delete_permit = $customView->isPermittedCustomView($viewid,'Delete',$currentModule);
$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails);
$smarty->assign("CV_EDIT_PERMIT",$edit_permit);
$smarty->assign("CV_DELETE_PERMIT",$delete_permit);
}
// END
$smarty->assign("VIEWID", $viewid);
if($viewinfo['viewname'] == 'All') $smarty->assign('ALL', 'All');
if($viewid ==0)
{
echo "<table border='0' cellpadding='5' cellspacing='0' width='100%' height='450px'><tr><td align='center'>";
echo "<div style='border: 3px solid rgb(153, 153, 153); background-color: rgb(255, 255, 255); width: 55%; position: relative; z-index: 10000000;'>
<table border='0' cellpadding='5' cellspacing='0' width='98%'>
<tbody><tr>
<td rowspan='2' width='11%'><img src='". vtiger_imageurl('denied.gif', $theme) ."' ></td>
<td style='border-bottom: 1px solid rgb(204, 204, 204);' nowrap='nowrap' width='70%'><span clas
s='genHeaderSmall'>$app_strings[LBL_PERMISSION]</span></td>
</tr>
<tr>
<td class='small' align='right' nowrap='nowrap'>
<a href='javascript:window.history.back();'>$app_strings[LBL_GO_BACK]</a><br>
</td>
</tr>
</tbody></table>
</div>";
echo "</td></tr></table>";
exit;
}
$listquery = getListQuery($currentModule);
$list_query= $customView->getModifiedCvListQuery($viewid, $listquery, $currentModule);
if($where != '') {
$list_query = "$list_query AND $where";
}
// Sorting
if(!empty($order_by)) {
if($order_by == 'smownerid') $list_query .= ' ORDER BY user_name '.$sorder;
else {
$tablename = getTableNameForField($currentModule, $order_by);
$tablename = ($tablename != '')? ($tablename . '.') : '';
$list_query .= ' ORDER BY ' . $tablename . $order_by . ' ' . $sorder;
}
}
//Postgres 8 fixes
if( $adb->dbType == "pgsql")
$list_query = fixPostgresQuery( $list_query, $log, 0);
if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true){
$count_result = $adb->query( mkCountQuery( $list_query));
$noofrows = $adb->query_result($count_result,0,"count");
}else{
$noofrows = null;
}
$queryMode = (isset($_REQUEST['query']) && $_REQUEST['query'] == 'true');
$start = ListViewSession::getRequestCurrentPage($currentModule, $list_query, $viewid, $queryMode);
$navigation_array = VT_getSimpleNavigationValues($start,$list_max_entries_per_page,$noofrows);
$limit_start_rec = ($start-1) * $list_max_entries_per_page;
if( $adb->dbType == "pgsql")
$list_result = $adb->pquery($list_query. " OFFSET $limit_start_rec LIMIT $list_max_entries_per_page", array());
else
$list_result = $adb->pquery($list_query. " LIMIT $limit_start_rec, $list_max_entries_per_page", array());
$recordListRangeMsg = getRecordRangeMessage($list_result, $limit_start_rec);
$smarty->assign('recordListRange',$recordListRangeMsg);
$smarty->assign("CUSTOMVIEW_OPTION",$customview_html);
// Navigation
$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string, $currentModule, 'index', $viewid);
$smarty->assign("NAVIGATION", $navigationOutput);
$listview_header = getListViewHeader($focus,$currentModule,$url_string,$sorder,$order_by,'',$customView);
$listview_entries = getListViewEntries($focus,$currentModule,$list_result,$navigation_array,'','','EditView','Delete',$customView);
$listview_header_search = getSearchListHeaderValues($focus,$currentModule,$url_string,$sorder,$order_by,'',$customView);
$smarty->assign('LISTHEADER', $listview_header);
$smarty->assign('LISTENTITY', $listview_entries);
$smarty->assign('SEARCHLISTHEADER',$listview_header_search);
// Module Search
$alphabetical = AlphabeticalSearch($currentModule,'index',$focus->def_basicsearch_col,'true','basic','','','','',$viewid);
$fieldnames = getAdvSearchfields($currentModule);
$criteria = getcriteria_options();
$smarty->assign("ALPHABETICAL", $alphabetical);
$smarty->assign("FIELDNAMES", $fieldnames);
$smarty->assign("CRITERIA", $criteria);
$smarty->assign("AVALABLE_FIELDS", getMergeFields($currentModule,"available_fields"));
$smarty->assign("FIELDS_TO_MERGE", getMergeFields($currentModule,"fileds_to_merge"));
$_SESSION[$currentModule.'_listquery'] = $list_query;
if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '')
$smarty->display("ListViewEntries.tpl");
else
$smarty->display('ListView.tpl');
?>
@@ -0,0 +1,11 @@
<?php
/*+*******************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*********************************************************************************/
require_once 'include/ListView/ListViewPagging.php';
?>
@@ -0,0 +1,44 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $mod_strings,$app_strings,$theme,$currentModule,$current_user;
require_once('Smarty_setup.php');
require_once('include/utils/utils.php');
$focus = CRMEntity::getInstance($currentModule);
$focus->mode = '';
$mode = 'mass_edit';
$disp_view = getView($focus->mode);
$idstring = $_REQUEST['idstring'];
$smarty = new vtigerCRM_Smarty;
$smarty->assign('MODULE',$currentModule);
$smarty->assign('APP',$app_strings);
$smarty->assign('THEME', $theme);
$smarty->assign('IMAGE_PATH', "themes/$theme/images/");
$smarty->assign('IDS',$idstring);
$smarty->assign('MASS_EDIT','1');
$smarty->assign('BLOCKS',getBlocks($currentModule,$disp_view,$mode,$focus->column_fields));
$smarty->assign("CATEGORY",getParentTab());
// Field Validation Information
$tabid = getTabid($currentModule);
$validationData = getDBValidationData($focus->tab_name,$tabid);
$validationArray = split_validationdataArray($validationData);
$smarty->assign("VALIDATION_DATA_FIELDNAME",$validationArray['fieldname']);
$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$validationArray['datatype']);
$smarty->assign("VALIDATION_DATA_FIELDLABEL",$validationArray['fieldlabel']);
$smarty->display('MassEditForm.tpl');
?>
@@ -0,0 +1,65 @@
<?php
/*+********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
********************************************************************************/
global $currentModule, $rstart;
$focus = CRMEntity::getInstance($currentModule);
$idlist= vtlib_purify($_REQUEST['massedit_recordids']);
$viewid = vtlib_purify($_REQUEST['viewname']);
$return_module = vtlib_purify($_REQUEST['massedit_module']);
$return_action = 'index';
//Added to fix 4600
$url = getBasic_Advance_SearchURL();
if(isset($_REQUEST['start']) && $_REQUEST['start']!=''){
$rstart = "&start=".vtlib_purify($_REQUEST['start']);
}
if(isset($idlist)) {
$recordids = explode(';', $idlist);
for($index = 0; $index < count($recordids); ++$index) {
$recordid = $recordids[$index];
if($recordid == '') continue;
if(isPermitted($currentModule,'EditView',$recordid) == 'yes') {
// Save each module record with update value.
$focus->retrieve_entity_info($recordid, $currentModule);
$focus->mode = 'edit';
$focus->id = $recordid;
foreach($focus->column_fields as $fieldname => $val)
{
if(isset($_REQUEST[$fieldname."_mass_edit_check"])) {
if($fieldname == 'assigned_user_id'){
if($_REQUEST['assigntype'] == 'U') {
$value = $_REQUEST['assigned_user_id'];
} elseif($_REQUEST['assigntype'] == 'T') {
$value = $_REQUEST['assigned_group_id'];
}
} else {
if(is_array($_REQUEST[$fieldname]))
$value = $_REQUEST[$fieldname];
else
$value = trim($_REQUEST[$fieldname]);
}
$focus->column_fields[$fieldname] = $value;
}
else {
$focus->column_fields[$fieldname] = decode_html($focus->column_fields[$fieldname]);
}
}
$focus->save($currentModule);
}
}
}
$parenttab = getParentTab();
header("Location: index.php?module=$return_module&action=$return_action&parenttab=$parenttab$rstart");
?>
@@ -0,0 +1,8 @@
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
@@ -0,0 +1,451 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('data/CRMEntity.php');
require_once('data/Tracker.php');
class ModuleClass extends CRMEntity {
var $db, $log; // Used in class functions of CRMEntity
var $table_name = 'vtiger_payslip';
var $table_index= 'payslipid';
var $column_fields = Array();
/** Indicator if this is a custom module or standard module */
var $IsCustomModule = true;
/**
* Mandatory table for supporting custom fields.
*/
var $customFieldTable = Array('vtiger_payslipcf', 'payslipid');
/**
* Mandatory for Saving, Include tables related to this module.
*/
var $tab_name = Array('vtiger_crmentity', 'vtiger_payslip', 'vtiger_payslipcf');
/**
* Mandatory for Saving, Include tablename and tablekey columnname here.
*/
var $tab_name_index = Array(
'vtiger_crmentity' => 'crmid',
'vtiger_payslip' => 'payslipid',
'vtiger_payslipcf' => 'payslipid');
/**
* Mandatory for Listing (Related listview)
*/
var $list_fields = Array (
/* Format: Field Label => Array(tablename, columnname) */
// tablename should not have prefix 'vtiger_'
'Payslip Name'=> Array('payslip', 'payslipname'),
'Assigned To' => Array('crmentity','smownerid')
);
var $list_fields_name = Array(
/* Format: Field Label => fieldname */
'Payslip Name'=> 'payslipname',
'Assigned To' => 'assigned_user_id'
);
// Make the field link to detail view from list view (Fieldname)
var $list_link_field = 'payslipname';
// For Popup listview and UI type support
var $search_fields = Array(
/* Format: Field Label => Array(tablename, columnname) */
// tablename should not have prefix 'vtiger_'
'Payslip Name'=> Array('payslip', 'payslipname')
);
var $search_fields_name = Array(
/* Format: Field Label => fieldname */
'Payslip Name'=> 'payslipname'
);
// For Popup window record selection
var $popup_fields = Array('payslipname');
// Placeholder for sort fields - All the fields will be initialized for Sorting through initSortFields
var $sortby_fields = Array();
// For Alphabetical search
var $def_basicsearch_col = 'payslipname';
// Column value to use on detail view record text display
var $def_detailview_recname = 'payslipname';
// Required Information for enabling Import feature
var $required_fields = Array('payslipname'=>1);
// Callback function list during Importing
var $special_functions = Array('set_import_assigned_user');
var $default_order_by = 'payslipname';
var $default_sort_order='ASC';
// Used when enabling/disabling the mandatory fields for the module.
// Refers to vtiger_field.fieldname values.
var $mandatory_fields = Array('createdtime', 'modifiedtime', 'payslipname');
function __construct() {
global $log, $currentModule;
$this->column_fields = getColumnFields($currentModule);
$this->db = PearDatabase::getInstance();
$this->log = $log;
}
function getSortOrder() {
global $currentModule;
$sortorder = $this->default_sort_order;
if($_REQUEST['sorder']) $sortorder = $this->db->sql_escape_string($_REQUEST['sorder']);
else if($_SESSION[$currentModule.'_Sort_Order'])
$sortorder = $_SESSION[$currentModule.'_Sort_Order'];
return $sortorder;
}
function getOrderBy() {
global $currentModule;
$use_default_order_by = '';
if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) {
$use_default_order_by = $this->default_order_by;
}
$orderby = $use_default_order_by;
if($_REQUEST['order_by']) $orderby = $this->db->sql_escape_string($_REQUEST['order_by']);
else if($_SESSION[$currentModule.'_Order_By'])
$orderby = $_SESSION[$currentModule.'_Order_By'];
return $orderby;
}
function save_module($module) {
}
/**
* Return query to use based on given modulename, fieldname
* Useful to handle specific case handling for Popup
*/
function getQueryByModuleField($module, $fieldname, $srcrecord) {
// $srcrecord could be empty
}
/**
* Get list view query (send more WHERE clause condition if required)
*/
function getListQuery($module, $where='') {
$query = "SELECT vtiger_crmentity.*, $this->table_name.*";
// Select Custom Field Table Columns if present
if(!empty($this->customFieldTable)) $query .= ", " . $this->customFieldTable[0] . ".* ";
$query .= " FROM $this->table_name";
$query .= " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $this->table_name.$this->table_index";
// Consider custom table join as well.
if(!empty($this->customFieldTable)) {
$query .= " INNER JOIN ".$this->customFieldTable[0]." ON ".$this->customFieldTable[0].'.'.$this->customFieldTable[1] .
" = $this->table_name.$this->table_index";
}
$query .= " LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid";
$query .= " LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid";
$linkedModulesQuery = $this->db->pquery("SELECT distinct fieldname, columnname, relmodule FROM vtiger_field" .
" INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid" .
" WHERE uitype='10' AND vtiger_fieldmodulerel.module=?", array($module));
$linkedFieldsCount = $this->db->num_rows($linkedModulesQuery);
for($i=0; $i<$linkedFieldsCount; $i++) {
$related_module = $this->db->query_result($linkedModulesQuery, $i, 'relmodule');
$fieldname = $this->db->query_result($linkedModulesQuery, $i, 'fieldname');
$columnname = $this->db->query_result($linkedModulesQuery, $i, 'columnname');
$other = CRMEntity::getInstance($related_module);
vtlib_setup_modulevars($related_module, $other);
$query .= " LEFT JOIN $other->table_name ON $other->table_name.$other->table_index = $this->table_name.$columnname";
}
$query .= " WHERE vtiger_crmentity.deleted = 0 ".$where;
$query .= $this->getListViewSecurityParameter($module);
return $query;
}
/**
* Apply security restriction (sharing privilege) query part for List view.
*/
function getListViewSecurityParameter($module) {
global $current_user;
require('user_privileges/user_privileges_'.$current_user->id.'.php');
require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
$sec_query = '';
$tabid = getTabid($module);
if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1
&& $defaultOrgSharingPermission[$tabid] == 3) {
$sec_query .= " AND (vtiger_crmentity.smownerid in($current_user->id) OR vtiger_crmentity.smownerid IN
(
SELECT vtiger_user2role.userid FROM vtiger_user2role
INNER JOIN vtiger_users ON vtiger_users.id=vtiger_user2role.userid
INNER JOIN vtiger_role ON vtiger_role.roleid=vtiger_user2role.roleid
WHERE vtiger_role.parentrole LIKE '".$current_user_parent_role_seq."::%'
)
OR vtiger_crmentity.smownerid IN
(
SELECT shareduserid FROM vtiger_tmp_read_user_sharing_per
WHERE userid=".$current_user->id." AND tabid=".$tabid."
)
OR
(";
// Build the query based on the group association of current user.
if(sizeof($current_user_groups) > 0) {
$sec_query .= " vtiger_groups.groupid IN (". implode(",", $current_user_groups) .") OR ";
}
$sec_query .= " vtiger_groups.groupid IN
(
SELECT vtiger_tmp_read_group_sharing_per.sharedgroupid
FROM vtiger_tmp_read_group_sharing_per
WHERE userid=".$current_user->id." and tabid=".$tabid."
)";
$sec_query .= ")
)";
}
return $sec_query;
}
/**
* Create query to export the records.
*/
function create_export_query($where)
{
global $current_user;
$thismodule = $_REQUEST['module'];
include("include/utils/ExportUtils.php");
//To get the Permitted fields query and the permitted fields list
$sql = getPermittedFieldsQuery($thismodule, "detail_view");
$fields_list = getFieldsListFromQuery($sql);
$query = "SELECT $fields_list, vtiger_users.user_name AS user_name
FROM vtiger_crmentity INNER JOIN $this->table_name ON vtiger_crmentity.crmid=$this->table_name.$this->table_index";
if(!empty($this->customFieldTable)) {
$query .= " INNER JOIN ".$this->customFieldTable[0]." ON ".$this->customFieldTable[0].'.'.$this->customFieldTable[1] .
" = $this->table_name.$this->table_index";
}
$query .= " LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid";
$query .= " LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id and vtiger_users.status='Active'";
$linkedModulesQuery = $this->db->pquery("SELECT distinct fieldname, columnname, relmodule FROM vtiger_field" .
" INNER JOIN vtiger_fieldmodulerel ON vtiger_fieldmodulerel.fieldid = vtiger_field.fieldid" .
" WHERE uitype='10' AND vtiger_fieldmodulerel.module=?", array($thismodule));
$linkedFieldsCount = $this->db->num_rows($linkedModulesQuery);
for($i=0; $i<$linkedFieldsCount; $i++) {
$related_module = $this->db->query_result($linkedModulesQuery, $i, 'relmodule');
$fieldname = $this->db->query_result($linkedModulesQuery, $i, 'fieldname');
$columnname = $this->db->query_result($linkedModulesQuery, $i, 'columnname');
$other = CRMEntity::getInstance($related_module);
vtlib_setup_modulevars($related_module, $other);
$query .= " LEFT JOIN $other->table_name ON $other->table_name.$other->table_index = $this->table_name.$columnname";
}
$where_auto = " vtiger_crmentity.deleted=0";
if($where != '') $query .= " WHERE ($where) AND $where_auto";
else $query .= " WHERE $where_auto";
require('user_privileges/user_privileges_'.$current_user->id.'.php');
require('user_privileges/sharing_privileges_'.$current_user->id.'.php');
// Security Check for Field Access
if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[7] == 3)
{
//Added security check to get the permitted records only
$query = $query." ".getListViewSecurityParameter($thismodule);
}
return $query;
}
/**
* Initialize this instance for importing.
*/
function initImport($module) {
$this->db = PearDatabase::getInstance();
$this->initImportableFields($module);
}
/**
* Create list query to be shown at the last step of the import.
* Called From: modules/Import/UserLastImport.php
*/
function create_import_query($module) {
global $current_user;
$query = "SELECT vtiger_crmentity.crmid, case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, $this->table_name.* FROM $this->table_name
INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $this->table_name.$this->table_index
LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=vtiger_crmentity.crmid
LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
WHERE vtiger_users_last_import.assigned_user_id='$current_user->id'
AND vtiger_users_last_import.bean_type='$module'
AND vtiger_users_last_import.deleted=0";
return $query;
}
/**
* Delete the last imported records.
*/
function undo_import($module, $user_id) {
global $adb;
$count = 0;
$query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='$module' AND deleted=0";
$result1 = $adb->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error());
while ( $row1 = $adb->fetchByAssoc($result1))
{
$query2 = "update vtiger_crmentity set deleted=1 where crmid=?";
$result2 = $adb->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error());
$count++;
}
return $count;
}
/**
* Transform the value while exporting
*/
function transform_export_value($key, $value) {
return parent::transform_export_value($key, $value);
}
/**
* Function which will set the assigned user id for import record.
*/
function set_import_assigned_user()
{
global $current_user, $adb;
$record_user = $this->column_fields["assigned_user_id"];
if($record_user != $current_user->id){
$sqlresult = $adb->pquery("select id from vtiger_users where id = ? union select groupid as id from vtiger_groups where groupid = ?", array($record_user, $record_user));
if($this->db->num_rows($sqlresult)!= 1) {
$this->column_fields["assigned_user_id"] = $current_user->id;
} else {
$row = $adb->fetchByAssoc($sqlresult, -1, false);
if (isset($row['id']) && $row['id'] != -1) {
$this->column_fields["assigned_user_id"] = $row['id'];
} else {
$this->column_fields["assigned_user_id"] = $current_user->id;
}
}
}
}
/**
* Function which will give the basic query to find duplicates
*/
function getDuplicatesQuery($module,$table_cols,$field_values,$ui_type_arr,$select_cols='') {
$select_clause = "SELECT ". $this->table_name .".".$this->table_index ." AS recordid, vtiger_users_last_import.deleted,".$table_cols;
// Select Custom Field Table Columns if present
if(isset($this->customFieldTable)) $query .= ", " . $this->customFieldTable[0] . ".* ";
$from_clause = " FROM $this->table_name";
$from_clause .= " INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $this->table_name.$this->table_index";
// Consider custom table join as well.
if(isset($this->customFieldTable)) {
$from_clause .= " INNER JOIN ".$this->customFieldTable[0]." ON ".$this->customFieldTable[0].'.'.$this->customFieldTable[1] .
" = $this->table_name.$this->table_index";
}
$from_clause .= " LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid
LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid";
$where_clause = " WHERE vtiger_crmentity.deleted = 0";
$where_clause .= $this->getListViewSecurityParameter($module);
if (isset($select_cols) && trim($select_cols) != '') {
$sub_query = "SELECT $select_cols FROM $this->table_name AS t " .
" INNER JOIN vtiger_crmentity AS crm ON crm.crmid = t.".$this->table_index;
// Consider custom table join as well.
if(isset($this->customFieldTable)) {
$sub_query .= " LEFT JOIN ".$this->customFieldTable[0]." tcf ON tcf.".$this->customFieldTable[1]." = t.$this->table_index";
}
$sub_query .= " WHERE crm.deleted=0 GROUP BY $select_cols HAVING COUNT(*)>1";
} else {
$sub_query = "SELECT $table_cols $from_clause $where_clause GROUP BY $table_cols HAVING COUNT(*)>1";
}
$query = $select_clause . $from_clause .
" LEFT JOIN vtiger_users_last_import ON vtiger_users_last_import.bean_id=" . $this->table_name .".".$this->table_index .
" INNER JOIN (" . $sub_query . ") AS temp ON ".get_on_clause($field_values,$ui_type_arr,$module) .
$where_clause .
" ORDER BY $table_cols,". $this->table_name .".".$this->table_index ." ASC";
return $query;
}
/**
* Invoked when special actions are performed on the module.
* @param String Module name
* @param String Event Type (module.postinstall, module.disabled, module.enabled, module.preuninstall)
*/
function vtlib_handler($modulename, $event_type) {
if($event_type == 'module.postinstall') {
// TODO Handle post installation actions
} else if($event_type == 'module.disabled') {
// TODO Handle actions when this module is disabled.
} else if($event_type == 'module.enabled') {
// TODO Handle actions when this module is enabled.
} else if($event_type == 'module.preuninstall') {
// TODO Handle actions when this module is about to be deleted.
} else if($event_type == 'module.preupdate') {
// TODO Handle actions before this module is updated.
} else if($event_type == 'module.postupdate') {
// TODO Handle actions after this module is updated.
}
}
/**
* Handle saving related module information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
// function save_related_module($module, $crmid, $with_module, $with_crmid) { }
/**
* Handle deleting related module information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
//function delete_related_module($module, $crmid, $with_module, $with_crmid) { }
/**
* Handle getting related list information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
//function get_related_list($id, $cur_tab_id, $rel_tab_id, $actions=false) { }
/**
* Handle getting dependents list information.
* NOTE: This function has been added to CRMEntity (base class).
* You can override the behavior by re-defining it here.
*/
//function get_dependents_list($id, $cur_tab_id, $rel_tab_id, $actions=false) { }
}
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/Ajax/CommonAjax.php');
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('Popup.php');
?>
@@ -0,0 +1,134 @@
<?php
/*********************************************************************************
** The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*
********************************************************************************/
require_once('Smarty_setup.php');
require_once('database/DatabaseConnection.php');
require_once('modules/Users/Users.php');
require_once('include/utils/utils.php');
$module = vtlib_purify($_REQUEST['module']);
$focus = CRMEntity::getInstance($module);
global $mod_strings, $app_strings, $app_list_strings;
global $current_language, $currentModule, $theme;
global $adb;
$theme_path="themes/".$theme."/";
$image_path=$theme_path."images/";
$mode = $_REQUEST['mergemode'];
if($mode == 'mergesave') {
$return_module=vtlib_purify($_REQUEST['return_module']);
$action=vtlib_purify($_REQUEST['action']);
$return_action=vtlib_purify($_REQUEST['return_action']);
$parenttab=vtlib_purify($_REQUEST['parent']);
$merge_id=vtlib_purify($_REQUEST['record']);
$recordids=vtlib_purify($_REQUEST['pass_rec']);
$result = $adb->pquery("SELECT count(*) AS count FROM vtiger_crmentity WHERE crmid=? and deleted=0", array($merge_id));
$count = $adb->query_result($result,0,'count');
if($count > 0)
{
// First, save the primary record
$focus->mode="edit";
setObjectValuesFromRequest($focus);
$focus->save($module);
$rec_values=$focus->column_fields;
// Remove the id of primary record from the list of records to be deleted.
$del_value=explode(",",$recordids,-1);
$offset = array_search($merge_id,$del_value);
unset($del_value[$offset]);
// Transfer the related lists of the records to be deleted, to the primary record's related list
if(method_exists($focus, 'transferRelatedRecords')){
$focus->transferRelatedRecords($module,$del_value,$merge_id);
} else {
transferRelatedRecords($module,$del_value,$merge_id);
}
// Delete the records by id specified in the list
foreach($del_value as $value)
{
DeleteEntity($_REQUEST['module'],$_REQUEST['return_module'],$focus,$value,"");
}
}
?>
<script>
window.self.close();window.opener.location.href=window.opener.location.href;
</script>
<?php
} elseif ($mode == 'mergefields') {
$idstring=vtlib_purify($_REQUEST['passurl']);
$parent_tab=getParentTab();
$exploded_id=explode(",",$idstring,-1);
$record_count = count($exploded_id);
$smarty = new vtigerCRM_Smarty;
$smarty->assign("EDIT_DUPLICATE","");
if($record_count == 2) {
if(isPermitted($currentModule,"EditView",$exploded_id[0]) == 'yes' && isPermitted($currentModule,"EditView",$exploded_id[1]) == 'yes'
&& isPermitted($currentModule,"Delete",$exploded_id[0]) == 'yes' && isPermitted($currentModule,"Delete",$exploded_id[1]) == 'yes')
$smarty->assign("EDIT_DUPLICATE","permitted");
}
else {
if(isPermitted($currentModule,"EditView",$exploded_id[0]) == 'yes' && isPermitted($currentModule,"EditView",$exploded_id[1]) == 'yes' && isPermitted($currentModule,"EditView",$exploded_id[2]) == 'yes'
&& isPermitted($currentModule,"Delete",$exploded_id[0]) == 'yes' && isPermitted($currentModule,"Delete",$exploded_id[1]) == 'yes' && isPermitted($currentModule,"Delete",$exploded_id[2]) == 'yes')
$smarty->assign("EDIT_DUPLICATE","permitted");
}
$all_values_array=getRecordValues($exploded_id,$module);
$all_values=$all_values_array[0];
$js_arr_val=$all_values_array[1];
$fld_array=$all_values_array[2];
$js_arr=implode(",",$js_arr_val);
$imported_records = Array();
$sql="select bean_id from vtiger_users_last_import where bean_type=? and deleted=0";
$result = $adb->pquery($sql, array($module));
$num_rows=$adb->num_rows($result);
$count=0;
for($i=0; $i<$num_rows;$i++)
{
foreach($exploded_id as $value)
if($value == $adb->query_result($result,$i,"bean_id"))
$count++;
array_push($imported_records,$adb->query_result($result,$i,"bean_id"));
}
if ($record_count == $count)
$no_existing=1;
else
$no_existing=0;
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP", $app_strings);
$smarty->assign("RECORD_COUNT",$record_count);
$smarty->assign("THEME", $theme);
$smarty->assign("IMAGE_PATH", $image_path);
$smarty->assign("MODULENAME", $module);
$smarty->assign("PARENT_TAB", $parent_tab);
$smarty->assign("JS_ARRAY", $js_arr);
$smarty->assign("ID_ARRAY", $exploded_id);
$smarty->assign("IDSTRING",$idstring);
$smarty->assign("ALLVALUES", $all_values);
$smarty->assign("FIELD_ARRAY", $fld_array);
$smarty->assign("IMPORTED_RECORDS", $imported_records);
$smarty->assign("NO_EXISTING", $no_existing);
$smarty->display("MergeFields.tpl");
}
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/quickcreate.php');
?>
@@ -0,0 +1,53 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $current_user, $currentModule;
checkFileAccess("modules/$currentModule/$currentModule.php");
require_once("modules/$currentModule/$currentModule.php");
$focus = new $currentModule();
setObjectValuesFromRequest($focus);
$mode = $_REQUEST['mode'];
$record=$_REQUEST['record'];
if($mode) $focus->mode = $mode;
if($record)$focus->id = $record;
if($_REQUEST['assigntype'] == 'U') {
$focus->column_fields['assigned_user_id'] = $_REQUEST['assigned_user_id'];
} elseif($_REQUEST['assigntype'] == 'T') {
$focus->column_fields['assigned_user_id'] = $_REQUEST['assigned_group_id'];
}
$focus->save($currentModule);
$return_id = $focus->id;
$search = vtlib_purify($_REQUEST['search_url']);
$parenttab = getParentTab();
if($_REQUEST['return_module'] != '') {
$return_module = vtlib_purify($_REQUEST['return_module']);
} else {
$return_module = $currentModule;
}
if($_REQUEST['return_action'] != '') {
$return_action = vtlib_purify($_REQUEST['return_action']);
} else {
$return_action = "DetailView";
}
if($_REQUEST['return_id'] != '') {
$return_id = vtlib_purify($_REQUEST['return_id']);
}
header("Location: index.php?action=$return_action&module=$return_module&record=$return_id&parenttab=$parenttab&start=".vtlib_purify($_REQUEST['pagenumber']).$search);
?>
@@ -0,0 +1,13 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include('modules/Vtiger/Settings.php');
?>
@@ -0,0 +1,11 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/Ajax/TagCloud.php');
?>
@@ -0,0 +1,11 @@
<?php
/*+*******************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*********************************************************************************/
require_once 'modules/Home/UnifiedSearch.php';
?>
@@ -0,0 +1,15 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
global $currentModule;
checkFileAccess("modules/$currentModule/ListView.php");
include_once("modules/$currentModule/ListView.php");
?>
@@ -0,0 +1,20 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
$mod_strings = Array(
'ModuleName' => 'Module Name',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'LBL_MODULEBLOCK_INFORMATION' => 'ModuleBlock Information',
'ModuleFieldLabel' => 'ModuleFieldLabel Text',
);
?>
@@ -0,0 +1,46 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('include/database/PearDatabase.php');
@include_once('user_privileges/default_module_view.php');
global $adb, $singlepane_view, $currentModule;
$idlist = vtlib_purify($_REQUEST['idlist']);
$destinationModule = vtlib_purify($_REQUEST['destination_module']);
$parenttab = getParentTab();
$forCRMRecord = vtlib_purify($_REQUEST['parentid']);
$mode = $_REQUEST['mode'];
if($singlepane_view == 'true')
$action = "DetailView";
else
$action = "CallRelatedList";
$focus = CRMEntity::getInstance($currentModule);
if($mode == 'delete') {
// Split the string of ids
$ids = explode (";",$idlist);
if(!empty($ids)) {
$focus->delete_related_module($currentModule, $forCRMRecord, $destinationModule, $ids);
}
} else {
if(!empty($_REQUEST['idlist'])) {
// Split the string of ids
$ids = explode (";",trim($idlist,";"));
} else if(!empty($_REQUEST['entityid'])){
$ids = $_REQUEST['entityid'];
}
if(!empty($ids)) {
$focus->save_related_module($currentModule, $forCRMRecord, $destinationModule, $ids);
}
}
header("Location: index.php?module=$currentModule&record=$forCRMRecord&action=$action&parenttab=$parenttab");
?>
@@ -0,0 +1,27 @@
Using skeleton module
=====================
1. Copy ModuleDir/<target_vtiger_version> to modules/<NewModuleName>
2. Rename modules/<NewModuleName>/ModuleFile.php to <NewModuleName>.php
3. Rename modules/<NewModuleName>/ModuleFileAjax.php to <NewModuleName>Ajax.php
4. Rename modules/<NewModuleName>/ModuleFile.js to <NewModuleName>.js
5. Edit <NewModuleName>.php
a. Update $table_name and $table_index (Module table name and table index column)
b. Update $groupTable
c. Update $tab_name, $tab_name_index
d. Update $list_fields, $list_fields_name, $sortby_fields
e. Update $detailview_links
f. Update $default_order_by, $default_sort_order
g. Update $customFieldTable
h. Rename class ModuleClass to class <NewModuleName>
Refer documentation for more details.
+181
View File
@@ -0,0 +1,181 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
include_once('include/utils/UserInfoUtil.php');
include_once('vtlib/Vtiger/Utils.php');
include_once('vtlib/Vtiger/Profile.php');
/**
* Provides API to control Access like Sharing, Tools etc. for vtiger CRM Module
* @package vtlib
*/
class Vtiger_Access {
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Get unique id for sharing access record.
* @access private
*/
static function __getDefaultSharingAccessId() {
global $adb;
return $adb->getUniqueID('vtiger_def_org_share');
}
/**
* Recalculate sharing access rules.
* @internal This function could take up lot of resource while execution
* @access private
*/
static function syncSharingAccess() {
self::log("Recalculating sharing rules ... ", false);
RecalculateSharingRules();
self::log("DONE");
}
/**
* Enable or Disable sharing access control to module
* @param Vtiger_Module Instance of the module to use
* @param Boolean true to enable sharing access, false disable sharing access
* @access private
*/
static function allowSharing($moduleInstance, $enable=true) {
global $adb;
$ownedby = $enable? 0 : 1;
$adb->pquery("UPDATE vtiger_tab set ownedby=? WHERE tabid=?", Array($ownedby, $moduleInstance->id));
self::log(($enable? "Enabled" : "Disabled") . " sharing access control ... DONE");
}
/**
* Initialize sharing access.
* @param Vtiger_Module Instance of the module to use
* @access private
* @internal This method is called from Vtiger_Module during creation.
*/
static function initSharing($moduleInstance) {
global $adb;
$result = $adb->query("SELECT share_action_id from vtiger_org_share_action_mapping WHERE share_action_name in
('Public: Read Only', 'Public: Read, Create/Edit', 'Public: Read, Create/Edit, Delete', 'Private')");
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$actionid = $adb->query_result($result, $index, 'share_action_id');
$adb->pquery("INSERT INTO vtiger_org_share_action2tab(share_action_id,tabid) VALUES(?,?)", Array($actionid, $moduleInstance->id));
}
self::log("Setting up sharing access options ... DONE");
}
/**
* Delete sharing access setup for module
* @param Vtiger_Module Instance of module to use
* @access private
* @internal This method is called from Vtiger_Module during deletion.
*/
static function deleteSharing($moduleInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_org_share_action2tab WHERE tabid=?", Array($moduleInstance->id));
self::log("Deleting sharing access ... DONE");
}
/**
* Set default sharing for a module
* @param Vtiger_Module Instance of the module
* @param String Permission text should be one of ['Public_ReadWriteDelete', 'Public_ReadOnly', 'Public_ReadWrite', 'Private']
* @access private
*/
static function setDefaultSharing($moduleInstance, $permission_text='Public_ReadWriteDelete') {
global $adb;
$permission_text = strtolower($permission_text);
if($permission_text == 'public_readonly') $permission = 0;
else if($permission_text == 'public_readwrite') $permission = 1;
else if($permission_text == 'public_readwritedelete') $permission = 2;
else if($permission_text == 'private') $permission = 3;
else $permission = 2; // public_readwritedelete is default
$editstatus = 0; // 0 or 1
$result = $adb->pquery("SELECT * FROM vtiger_def_org_share WHERE tabid=?", Array($moduleInstance->id));
if($adb->num_rows($result)) {
$ruleid = $adb->query_result($result, 0, 'ruleid');
$adb->pquery("UPDATE vtiger_def_org_share SET permission=? WHERE ruleid=?", Array($permission, $ruleid));
} else {
$ruleid = self::__getDefaultSharingAccessId();
$adb->pquery("INSERT INTO vtiger_def_org_share (ruleid,tabid,permission,editstatus) VALUES(?,?,?,?)",
Array($ruleid,$moduleInstance->id,$permission,$editstatus));
}
self::syncSharingAccess();
}
/**
* Enable tool for module.
* @param Vtiger_Module Instance of module to use
* @param String Tool (action name) like Import, Export, Merge
* @param Boolean true to enable tool, false to disable
* @param Integer (optional) profile id to use, false applies to all profile.
* @access private
*/
static function updateTool($moduleInstance, $toolAction, $flag, $profileid=false) {
global $adb;
$result = $adb->pquery("SELECT actionid FROM vtiger_actionmapping WHERE actionname=?", Array($toolAction));
if($adb->num_rows($result)) {
$actionid = $adb->query_result($result, 0, 'actionid');
$permission = ($flag == true)? '0' : '1';
$profileids = Array();
if($profileid) {
$profileids[] = $profileid;
} else {
$profileids = Vtiger_Profile::getAllIds();
}
self::log( ($flag? 'Enabling':'Disabling') . " $toolAction for Profile [", false);
foreach($profileids as $useprofileid) {
$result = $adb->pquery("SELECT permission FROM vtiger_profile2utility WHERE profileid=? AND tabid=? AND activityid=?",
Array($useprofileid, $moduleInstance->id, $actionid));
if($adb->num_rows($result)) {
$curpermission = $adb->query_result($result, 0, 'permission');
if($curpermission != $permission) {
$adb->pquery("UPDATE vtiger_profile2utility set permission=? WHERE profileid=? AND tabid=? AND activityid=?",
Array($permission, $useprofileid, $moduleInstance->id, $actionid));
}
} else {
$adb->pquery("INSERT INTO vtiger_profile2utility (profileid, tabid, activityid, permission) VALUES(?,?,?,?)",
Array($useprofileid, $moduleInstance->id, $actionid, $permission));
}
self::log("$useprofileid,", false);
}
self::log("] ... DONE");
}
}
/**
* Delete tool (actions) of the module
* @param Vtiger_Module Instance of module to use
*/
static function deleteTools($moduleInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_profile2utility WHERE tabid=?", Array($moduleInstance->id));
self::log("Deleting tools ... DONE");
}
}
?>
+215
View File
@@ -0,0 +1,215 @@
<?php
/*+*******************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
******************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
/**
* Provides API to work with vtiger CRM Module Blocks
* @package vtlib
*/
class Vtiger_Block {
/** ID of this block instance */
var $id;
/** Label for this block instance */
var $label;
var $sequence;
var $showtitle = 0;
var $visible = 0;
var $increateview = 0;
var $ineditview = 0;
var $indetailview = 0;
var $module;
/**
* Constructor
*/
function __construct() {
}
/**
* Get unquie id for this instance
* @access private
*/
function __getUniqueId() {
global $adb;
/** Sequence table was added from 5.1.0 */
$maxblockid = $adb->getUniqueID('vtiger_blocks');
return $maxblockid;
}
/**
* Get next sequence value to use for this block instance
* @access private
*/
function __getNextSequence() {
global $adb;
$result = $adb->pquery("SELECT MAX(sequence) as max_sequence from vtiger_blocks where tabid = ?", Array($this->module->id));
$maxseq = 0;
if($adb->num_rows($result)) {
$maxseq = $adb->query_result($result, 0, 'max_sequence');
}
return ++$maxseq;
}
/**
* Initialize this block instance
* @param Array Map of column name and value
* @param Vtiger_Module Instance of module to which this block is associated
* @access private
*/
function initialize($valuemap, $moduleInstance=false) {
$this->id = $valuemap[blockid];
$this->label= $valuemap[blocklabel];
$this->module=$moduleInstance? $moduleInstance: Vtiger_Module::getInstance($valuemap[tabid]);
}
/**
* Create vtiger CRM block
* @access private
*/
function __create($moduleInstance) {
global $adb;
$this->module = $moduleInstance;
$this->id = $this->__getUniqueId();
if(!$this->sequence) $this->sequence = $this->__getNextSequence();
$adb->pquery("INSERT INTO vtiger_blocks(blockid,tabid,blocklabel,sequence,show_title,visible,create_view,edit_view,detail_view)
VALUES(?,?,?,?,?,?,?,?,?)", Array($this->id, $this->module->id, $this->label,$this->sequence,
$this->showtitle, $this->visible,$this->increateview, $this->ineditview, $this->indetailview));
self::log("Creating Block $this->label ... DONE");
self::log("Module language entry for $this->label ... CHECK");
}
/**
* Update vtiger CRM block
* @access private
* @internal TODO
*/
function __update() {
self::log("Updating Block $this->label ... DONE");
}
/**
* Delete this instance
* @access private
*/
function __delete() {
global $adb;
self::log("Deleting Block $this->label ... ", false);
$adb->pquery("DELETE FROM vtiger_blocks WHERE blockid=?", Array($this->id));
self::log("DONE");
}
/**
* Save this block instance
* @param Vtiger_Module Instance of the module to which this block is associated
*/
function save($moduleInstance=false) {
if($this->id) $this->__update();
else $this->__create($moduleInstance);
return $this->id;
}
/**
* Delete block instance
* @param Boolean True to delete associated fields, False to avoid it
*/
function delete($recursive=true) {
if($recursive) {
$fields = Vtiger_Field::getAllForBlock($this);
foreach($fields as $fieldInstance) $fieldInstance->delete($recursive);
}
$this->__delete();
}
/**
* Add field to this block
* @param Vtiger_Field Instance of field to add to this block.
* @return Reference to this block instance
*/
function addField($fieldInstance) {
$fieldInstance->save($this);
return $this;
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Get instance of block
* @param mixed block id or block label
* @param Vtiger_Module Instance of the module if block label is passed
*/
static function getInstance($value, $moduleInstance=false) {
global $adb;
$instance = false;
$query = false;
$queryParams = false;
if(Vtiger_Utils::isNumber($value)) {
$query = "SELECT * FROM vtiger_blocks WHERE blockid=?";
$queryParams = Array($value);
} else {
$query = "SELECT * FROM vtiger_blocks WHERE blocklabel=? AND tabid=?";
$queryParams = Array($value, $moduleInstance->id);
}
$result = $adb->pquery($query, $queryParams);
if($adb->num_rows($result)) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance);
}
return $instance;
}
/**
* Get all block instances associated with the module
* @param Vtiger_Module Instance of the module
*/
static function getAllForModule($moduleInstance) {
global $adb;
$instances = false;
$query = "SELECT * FROM vtiger_blocks WHERE tabid=?";
$queryParams = Array($moduleInstance->id);
$result = $adb->pquery($query, $queryParams);
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance);
$instances[] = $instance;
}
return $instances;
}
/**
* Delete all blocks associated with module
* @param Vtiger_Module Instnace of module to use
* @param Boolean true to delete associated fields, false otherwise
* @access private
*/
static function deleteForModule($moduleInstance, $recursive=true) {
global $adb;
if($recursive) Vtiger_Field::deleteForModule($moduleInstance);
$adb->pquery("DELETE FROM vtiger_blocks WHERE tabid=?", Array($moduleInstance->id));
self::log("Deleting blocks for module ... DONE");
}
}
?>
+127
View File
@@ -0,0 +1,127 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
include_once('modules/Users/Users.php');
@include_once('include/events/include.inc');
/**
* Provides API to work with vtiger CRM Eventing (available from vtiger 5.1)
* @package vtlib
*/
class Vtiger_Event {
/** Event name like: vtiger.entity.aftersave, vtiger.entity.beforesave */
var $eventname;
/** Event handler class to use */
var $classname;
/** Filename where class is defined */
var $filename;
/** Condition for the event */
var $condition;
/** Internal caching */
static $is_supported = '';
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Check if vtiger CRM support Events
*/
static function hasSupport() {
if(self::$is_supported === '') {
self::$is_supported = Vtiger_Utils::checkTable('vtiger_eventhandlers');
}
return self::$is_supported;
}
/**
* Handle event registration for module
* @param Vtiger_Module Instance of the module to use
* @param String Name of the Event like vtiger.entity.aftersave, vtiger.entity.beforesave
* @param String Name of the Handler class (should extend VTEventHandler)
* @param String File path which has Handler class definition
* @param String Condition for the event to trigger (default blank)
*/
static function register($moduleInstance, $eventname, $classname, $filename, $condition='') {
// Security check on fileaccess, don't die if it fails
if(Vtiger_Utils::checkFileAccess($filename, false)) {
global $adb;
$eventsManager = new VTEventsManager($adb);
$eventsManager->registerHandler($eventname, $filename, $classname, $condition);
$eventsManager->setModuleForHandler($moduleInstance->name, $classname);
self::log("Registering Event $eventname with [$filename] $classname ... DONE");
}
}
/**
* Trigger event based on CRM Record
* @param String Name of the Event to trigger
* @param Integer CRM record id on which event needs to be triggered.
*/
static function trigger($eventname, $crmid) {
if(!self::hasSupport()) return;
global $adb;
$checkres = $adb->pquery("SELECT setype, crmid, deleted FROM vtiger_crmentity WHERE crmid=?", Array($crmid));
if($adb->num_rows($checkres)) {
$result = $adb->fetch_array($checkres, 0);
if($result['deleted'] == '0') {
$module = $result['setype'];
$moduleInstance = CRMEntity::getInstance($module);
$moduleInstance->retrieve_entity_info($result['crmid'], $module);
$moduleInstance->id = $result['crmid'];
global $current_user;
if(!$current_user) {
$current_user = new Users();
$current_user->id = $moduleInstance->column_fields['assigned_user_id'];
}
// Trigger the event
$em = new VTEventsManager($adb);
$em->triggerEvent($eventname, VTEntityData::fromCRMEntity($moduleInstance));
}
}
}
/**
* Get all the registered module events
* @param Vtiger_Module Instance of the module to use
*/
static function getAll($moduleInstance) {
global $adb;
$events = false;
if(self::hasSupport()) {
// Get all events related to module
$records = $adb->pquery("SELECT * FROM vtiger_eventhandlers WHERE handler_class IN
(SELECT handler_class FROM vtiger_eventhandler_module WHERE module_name=?)", Array($moduleInstance->name));
if($records) {
while($record = $adb->fetch_array($records)) {
$event = new Vtiger_Event();
$event->eventname = $record['event_name'];
$event->classname = $record['handler_class'];
$event->filename = $record['handler_path'];
$event->condition = $record['condition'];
$events[] = $event;
}
}
}
return $events;
}
}
?>
@@ -0,0 +1,44 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
require_once('vtlib/thirdparty/parser/feed/simplepie.inc');
/**
* Extends SimplePie (feed parser library for Rss, Atom, etc)
* @package vtlib
*/
class Vtiger_Feed_Parser extends SimplePie {
var $vt_cachelocation = 'test/vtlib/feedcache';
var $vt_fetchdone = false;
/**
* Parse the feed url.
* @param String Feed url (RSS, ATOM etc)
* @param Integer Timeout value (to try connecting to url)
*/
function vt_dofetch($url, $timeout=10) {
$this->set_timeout($timeout);
$this->set_feed_url($url);
$this->enable_order_by_date(false);
$this->enable_cache(false);
$this->init();
$this->vt_fetchdone = true;
}
/**
* Parse the content as feed.
* @param String Feed content
*/
function vt_doparse($content) {
$this->set_raw_data($content);
$this->init();
$this->vt_fetchdone = true;
}
}
?>
+245
View File
@@ -0,0 +1,245 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
include_once('vtlib/Vtiger/FieldBasic.php');
/**
* Provides APIs to control vtiger CRM Field
* @package vtlib
*/
class Vtiger_Field extends Vtiger_FieldBasic {
/**
* Get unique picklist id to use
* @access private
*/
function __getPicklistUniqueId() {
global $adb;
return $adb->getUniqueID('vtiger_picklist');
}
/**
* Set values for picklist field (for all the roles)
* @param Array List of values to add.
*
* @internal Creates picklist base if it does not exists
*/
function setPicklistValues($values) {
global $adb;
// Non-Role based picklist values
if($this->uitype == '16') {
$this->setNoRolePicklistValues($values);
return;
}
$picklist_table = 'vtiger_'.$this->name;
$picklist_idcol = $this->name.'id';
if(!Vtiger_Utils::CheckTable($picklist_table)) {
Vtiger_Utils::CreateTable(
$picklist_table,
"($picklist_idcol INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
$this->name VARCHAR(200) NOT NULL,
presence INT (1) NOT NULL DEFAULT 1,
picklist_valueid INT NOT NULL DEFAULT 0)",
true);
$new_picklistid = $this->__getPicklistUniqueId();
$adb->pquery("INSERT INTO vtiger_picklist (picklistid,name) VALUES(?,?)",Array($new_picklistid, $this->name));
self::log("Creating table $picklist_table ... DONE");
} else {
$new_picklistid = $adb->query_result(
$adb->pquery("SELECT picklistid FROM vtiger_picklist WHERE name=?", Array($this->name)), 0, 'picklistid');
}
// Add value to picklist now
$sortid = 0; // TODO To be set per role
foreach($values as $value) {
$new_picklistvalueid = getUniquePicklistID();
$presence = 1; // 0 - readonly, Refer function in include/ComboUtil.php
$new_id = $adb->getUniqueID($picklist_table);
$adb->pquery("INSERT INTO $picklist_table($picklist_idcol, $this->name, presence, picklist_valueid) VALUES(?,?,?,?)",
Array($new_id, $value, $presence, $new_picklistvalueid));
++$sortid;
// Associate picklist values to all the role
$adb->query("INSERT INTO vtiger_role2picklist(roleid, picklistvalueid, picklistid, sortid) SELECT roleid,
$new_picklistvalueid, $new_picklistid, $sortid FROM vtiger_role");
}
}
/**
* Set values for picklist field (non-role based)
* @param Array List of values to add
*
* @internal Creates picklist base if it does not exists
* @access private
*/
function setNoRolePicklistValues($values) {
global $adb;
$picklist_table = 'vtiger_'.$this->name;
$picklist_idcol = $this->name.'id';
if(!Vtiger_Utils::CheckTable($picklist_table)) {
Vtiger_Utils::CreateTable(
$picklist_table,
"($picklist_idcol INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
$this->name VARCHAR(200) NOT NULL,
sortorderid INT(11),
presence INT (11) NOT NULL DEFAULT 1)",
true);
self::log("Creating table $picklist_table ... DONE");
}
// Add value to picklist now
$sortid = 1;
foreach($values as $value) {
$presence = 1; // 0 - readonly, Refer function in include/ComboUtil.php
$new_id = $adb->getUniqueId($picklist_table);
$adb->pquery("INSERT INTO $picklist_table($picklist_idcol, $this->name, sortorderid, presence) VALUES(?,?,?,?)",
Array($new_id, $value, $sortid, $presence));
$sortid = $sortid+1;
}
}
/**
* Set relation between field and modules (UIType 10)
* @param Array List of module names
*
* @internal Creates table vtiger_fieldmodulerel if it does not exists
*/
function setRelatedModules($moduleNames) {
// We need to create core table to capture the relation between the field and modules.
Vtiger_Utils::CreateTable(
'vtiger_fieldmodulerel',
'(fieldid INT NOT NULL, module VARCHAR(100) NOT NULL, relmodule VARCHAR(100) NOT NULL, status VARCHAR(10), sequence INT)',
true
);
// END
global $adb;
foreach($moduleNames as $relmodule) {
$checkres = $adb->pquery('SELECT * FROM vtiger_fieldmodulerel WHERE fieldid=? AND module=? AND relmodule=?',
Array($this->id, $this->getModuleName(), $relmodule));
// If relation already exist continue
if($adb->num_rows($checkres)) continue;
$adb->pquery('INSERT INTO vtiger_fieldmodulerel(fieldid, module, relmodule) VALUES(?,?,?)',
Array($this->id, $this->getModuleName(), $relmodule));
self::log("Setting $this->name relation with $relmodule ... DONE");
}
return true;
}
/**
* Remove relation between the field and modules (UIType 10)
* @param Array List of module names
*/
function unsetRelatedModules($moduleNames) {
global $adb;
foreach($moduleNames as $relmodule) {
$adb->pquery('DELETE FROM vtiger_fieldmodulerel WHERE fieldid=? AND module=? AND relmodule = ?',
Array($this->id, $this->getModuleName(), $relmodule));
Vtiger_Utils::Log("Unsetting $this->name relation with $relmodule ... DONE");
}
return true;
}
/**
* Get Vtiger_Field instance by fieldid or fieldname
* @param mixed fieldid or fieldname
* @param Vtiger_Module Instance of the module if fieldname is used
*/
static function getInstance($value, $moduleInstance=false) {
global $adb;
$instance = false;
$query = false;
$queryParams = false;
if(Vtiger_Utils::isNumber($value)) {
$query = "SELECT * FROM vtiger_field WHERE fieldid=?";
$queryParams = Array($value);
} else {
$query = "SELECT * FROM vtiger_field WHERE fieldname=? AND tabid=?";
$queryParams = Array($value, $moduleInstance->id);
}
$result = $adb->pquery($query, $queryParams);
if($adb->num_rows($result)) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance);
}
return $instance;
}
/**
* Get Vtiger_Field instances related to block
* @param Vtiger_Block Instnace of block to use
* @param Vtiger_Module Instance of module to which block is associated
*/
static function getAllForBlock($blockInstance, $moduleInstance=false) {
global $adb;
$instances = false;
$query = false;
$queryParams = false;
if($moduleInstance) {
$query = "SELECT * FROM vtiger_field WHERE block=? AND tabid=?";
$queryParams = Array($blockInstance->id, $moduleInstance->id);
} else {
$query = "SELECT * FROM vtiger_field WHERE block=?";
$queryParams = Array($blockInstance->id);
}
$result = $adb->pquery($query, $queryParams);
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance, $blockInstance);
$instances[] = $instance;
}
return $instances;
}
/**
* Get Vtiger_Field instances related to module
* @param Vtiger_Module Instance of module to use
*/
static function getAllForModule($moduleInstance) {
global $adb;
$instances = false;
$query = "SELECT * FROM vtiger_field WHERE tabid=?";
$queryParams = Array($moduleInstance->id);
$result = $adb->pquery($query, $queryParams);
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance);
$instances[] = $instance;
}
return $instances;
}
/**
* Delete fields associated with the module
* @param Vtiger_Module Instance of module
* @access private
*/
static function deleteForModule($moduleInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_field WHERE tabid=?", Array($moduleInstance->id));
self::log("Deleting fields of the module ... DONE");
}
}
?>
@@ -0,0 +1,283 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
/**
* Provides basic API to work with vtiger CRM Fields
* @package vtlib
*/
class Vtiger_FieldBasic {
/** ID of this field instance */
var $id;
var $name;
var $label = false;
var $table = false;
var $column = false;
var $columntype = false;
var $helpinfo = '';
var $masseditable = 1; // Default: Enable massedit for field
var $uitype = 1;
var $typeofdata = 'V~O';
var $displaytype = 1;
var $generatedtype = 1;
var $readonly = 1;
var $presence = 2;
var $selected = 0;
var $maximumlength = 100;
var $sequence = false;
var $quickcreate = 1;
var $quicksequence = false;
var $info_type = 'BAS';
var $block;
/**
* Constructor
*/
function __construct() {
}
/**
* Initialize this instance
* @param Array
* @param Vtiger_Module Instance of module to which this field belongs
* @param Vtiger_Block Instance of block to which this field belongs
* @access private
*/
function initialize($valuemap, $moduleInstance=false, $blockInstance=false) {
$this->id = $valuemap['fieldid'];
$this->name = $valuemap['fieldname'];
$this->label= $valuemap['fieldlabel'];
$this->column = $valuemap['columnname'];
$this->table = $valuemap['tablename'];
$this->uitype = $valuemap['uitype'];
$this->typeofdata = $valuemap['typeofdata'];
$this->helpinfo = $valuemap['helpinfo'];
$this->masseditable = $valuemap['masseditable'];
$this->block= $blockInstance? $blockInstance : Vtiger_Block::getInstance($valuemap['block'], $moduleInstance);
}
/** Cache (Record) the schema changes to improve performance */
static $__cacheSchemaChanges = Array();
/**
* Initialize vtiger schema changes.
* @access private
*/
function __handleVtigerCoreSchemaChanges() {
// Add helpinfo column to the vtiger_field table
if(empty(self::$__cacheSchemaChanges['vtiger_field.helpinfo'])) {
Vtiger_Utils::AddColumn('vtiger_field', 'helpinfo', ' TEXT');
self::$__cacheSchemaChanges['vtiger_field.helpinfo'] = true;
}
}
/**
* Get unique id for this instance
* @access private
*/
function __getUniqueId() {
global $adb;
return $adb->getUniqueID('vtiger_field');
}
/**
* Get next sequence id to use within a block for this instance
* @access private
*/
function __getNextSequence() {
global $adb;
$result = $adb->pquery("SELECT MAX(sequence) AS max_seq FROM vtiger_field WHERE tabid=? AND block=?",
Array($this->getModuleId(), $this->getBlockId()));
$maxseq = 0;
if($result && $adb->num_rows($result)) {
$maxseq = $adb->query_result($result, 0, 'max_seq');
$maxseq += 1;
}
return $maxseq;
}
/**
* Get next quick create sequence id for this instance
* @access private
*/
function __getNextQuickCreateSequence() {
global $adb;
$result = $adb->pquery("SELECT MAX(quickcreatesequence) AS max_quickcreateseq FROM vtiger_field WHERE tabid=?",
Array($this->getModuleId()));
$max_quickcreateseq = 0;
if($result && $adb->num_rows($result)) {
$max_quickcreateseq = $adb->query_result($result, 0, 'max_quickcreateseq');
$max_quickcreateseq += 1;
}
return $max_quickcreateseq;
}
/**
* Create this field instance
* @param Vtiger_Block Instance of the block to use
* @access private
*/
function __create($blockInstance) {
$this->__handleVtigerCoreSchemaChanges();
global $adb;
$this->block = $blockInstance;
$moduleInstance = $this->getModuleInstance();
$this->id = $this->__getUniqueId();
if(!$this->sequence) {
$this->sequence = $this->__getNextSequence();
}
if($this->quickcreate != 1) { // If enabled for display
if(!$this->quicksequence) {
$this->quicksequence = $this->__getNextQuickCreateSequence();
}
} else {
$this->quicksequence = null;
}
// Initialize other variables which are not done
if(!$this->table) $this->table = $moduleInstance->basetable;
if(!$this->column) {
$this->column = strtolower($this->name);
if(!$this->columntype) $this->columntype = 'VARCHAR(100)';
}
if(!$this->label) $this->label = $this->name;
$adb->pquery("INSERT INTO vtiger_field (tabid, fieldid, columnname, tablename, generatedtype,
uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence,
block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, helpinfo)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
Array($this->getModuleId(), $this->id, $this->column, $this->table, $this->generatedtype,
$this->uitype, $this->name, $this->label, $this->readonly, $this->presence, $this->selected,
$this->maximumlength, $this->sequence, $this->getBlockId(), $this->displaytype, $this->typeofdata,
$this->quickcreate, $this->quicksequence, $this->info_type, $this->helpinfo));
// Set the field status for mass-edit (if set)
$adb->pquery('UPDATE vtiger_field SET masseditable=? WHERE fieldid=?', Array($this->masseditable, $this->id));
Vtiger_Profile::initForField($this);
if(!empty($this->columntype)) {
Vtiger_Utils::AddColumn($this->table, $this->column, $this->columntype);
}
self::log("Creating Field $this->name ... DONE");
self::log("Module language mapping for $this->label ... CHECK");
}
/**
* Update this field instance
* @access private
* @internal TODO
*/
function __update() {
self::log("Updating Field $this->name ... DONE");
}
/**
* Delete this field instance
* @access private
*/
function __delete() {
global $adb;
Vtiger_Profile::deleteForField($this);
$adb->pquery("DELETE FROM vtiger_field WHERE fieldid=?", Array($this->id));
self::log("Deleteing Field $this->name ... DONE");
}
/**
* Get block id to which this field instance is associated
*/
function getBlockId() {
return $this->block->id;
}
/**
* Get module id to which this field instance is associated
*/
function getModuleId() {
return $this->block->module->id;
}
/**
* Get module name to which this field instance is associated
*/
function getModuleName() {
return $this->block->module->name;
}
/**
* Get module instance to which this field instance is associated
*/
function getModuleInstance(){
return $this->block->module;
}
/**
* Save this field instance
* @param Vtiger_Block Instance of block to which this field should be added.
*/
function save($blockInstance=false) {
if($this->id) $this->__update();
else $this->__create($blockInstance);
return $this->id;
}
/**
* Delete this field instance
*/
function delete() {
$this->__delete();
}
/**
* Set Help Information for this instance.
* @param String Help text (content)
*/
function setHelpInfo($helptext) {
// Make sure to initialize the core tables first
$this->__handleVtigerCoreSchemaChanges();
global $adb;
$adb->pquery('UPDATE vtiger_field SET helpinfo=? WHERE fieldid=?', Array($helptext, $this->id));
self::log("Updated help information of $this->name ... DONE");
}
/**
* Set Masseditable information for this instance.
* @param Integer Masseditable value
*/
function setMassEditable($value) {
global $adb;
$adb->pquery('UPDATE vtiger_field SET masseditable=? WHERE fieldid=?', Array($value, $this->id));
self::log("Updated masseditable information of $this->name ... DONE");
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
}
?>
+291
View File
@@ -0,0 +1,291 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
include_once('vtlib/Vtiger/Version.php');
/**
* Provides API to work with vtiger CRM Custom View (Filter)
* @package vtlib
*/
class Vtiger_Filter {
/** ID of this filter instance */
var $id;
var $name;
var $isdefault;
var $status = false; // 5.1.0 onwards
var $inmetrics = false;
var $entitytype= false;
var $module;
/**
* Constructor
*/
function __construct() {
}
/**
* Get unique id for this instance
* @access private
*/
function __getUniqueId() {
global $adb;
return $adb->getUniqueID('vtiger_customview');
}
/**
* Initialize this filter instance
* @param Vtiger_Module Instance of the module to which this filter is associated.
* @access private
*/
function initialize($valuemap, $moduleInstance=false) {
$this->id = $valuemap[cvid];
$this->name= $valuemap[viewname];
$this->module=$moduleInstance? $moduleInstance: Vtiger_Module::getInstance($valuemap[tabid]);
}
/**
* Create this instance
* @param Vtiger_Module Instance of the module to which this filter should be associated with
* @access private
*/
function __create($moduleInstance) {
global $adb;
$this->module = $moduleInstance;
$this->id = $this->__getUniqueId();
$this->isdefault = ($this->isdefault===true||$this->isdefault=='true')?1:0;
$this->inmetrics = ($this->inmetrics===true||$this->inmetrics=='true')?1:0;
$adb->pquery("INSERT INTO vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) VALUES(?,?,?,?,?)",
Array($this->id, $this->name, $this->isdefault, $this->inmetrics, $this->module->name));
self::log("Creating Filter $this->name ... DONE");
// Filters are role based from 5.1.0 onwards
if(!$this->status) {
if(strtoupper(trim($this->name)) == 'ALL') $this->status = '0'; // Default
else $this->status = '3'; // Public
$adb->pquery("UPDATE vtiger_customview SET status=? WHERE cvid=?", Array($this->status, $this->id));
self::log("Setting Filter $this->name to status [$this->status] ... DONE");
}
// END
}
/**
* Update this instance
* @access private
* @internal TODO
*/
function __update() {
self::log("Updating Filter $this->name ... DONE");
}
/**
* Delete this instance
* @access private
*/
function __delete() {
global $adb;
$adb->pquery("DELETE FROM vtiger_cvadvfilter WHERE cvid=?", Array($this->id));
$adb->pquery("DELETE FROM vtiger_cvcolumnlist WHERE cvid=?", Array($this->id));
$adb->pquery("DELETE FROM vtiger_customview WHERE cvid=?", Array($this->id));
}
/**
* Save this instance
* @param Vtiger_Module Instance of the module to use
*/
function save($moduleInstance=false) {
if($this->id) $this->__update();
else $this->__create($moduleInstance);
return $this->id;
}
/**
* Delete this instance
* @access private
*/
function delete() {
$this->__delete();
}
/**
* Get the column value to use in custom view tables.
* @param Vtiger_Field Instance of the field
* @access private
*/
function __getColumnValue($fieldInstance) {
$tod = split('~', $fieldInstance->typeofdata);
$displayinfo = $fieldInstance->getModuleName().'_'.str_replace(' ','_',$fieldInstance->label).':'.$tod[0];
$cvcolvalue = "$fieldInstance->table:$fieldInstance->column:$fieldInstance->name:$displayinfo";
return $cvcolvalue;
}
/**
* Add the field to this filer instance
* @param Vtiger_Field Instance of the field
* @param Integer Index count to use
*/
function addField($fieldInstance, $index=0) {
global $adb;
$cvcolvalue = $this->__getColumnValue($fieldInstance);
$adb->pquery("UPDATE vtiger_cvcolumnlist SET columnindex=columnindex+1 WHERE cvid=? AND columnindex>=? ORDER BY columnindex DESC",
Array($this->id, $index));
$adb->pquery("INSERT INTO vtiger_cvcolumnlist(cvid,columnindex,columnname) VALUES(?,?,?)", Array($this->id, $index, $cvcolvalue));
$this->log("Adding $fieldInstance->name to $this->name filter ... DONE");
return $this;
}
/**
* Add rule to this filter instance
* @param Vtiger_Field Instance of the field
* @param String One of [EQUALS, NOT_EQUALS, STARTS_WITH, ENDS_WITH, CONTAINS, DOES_NOT_CONTAINS, LESS_THAN,
* GREATER_THAN, LESS_OR_EQUAL, GREATER_OR_EQUAL]
* @param String Value to use for comparision
* @param Integer Index count to use
*/
function addRule($fieldInstance, $comparator, $comparevalue, $index=0) {
global $adb;
if(empty($comparator)) return $this;
$comparator = self::translateComparator($comparator);
$cvcolvalue = $this->__getColumnValue($fieldInstance);
$adb->pquery("UPDATE vtiger_cvadvfilter set columnindex=columnindex+1 WHERE cvid=? AND columnindex>=? ORDER BY columnindex DESC",
Array($this->id, $index));
$adb->pquery("INSERT INTO vtiger_cvadvfilter(cvid, columnindex, columnname, comparator, value) VALUES(?,?,?,?,?)",
Array($this->id, $index, $cvcolvalue, $comparator, $comparevalue));
Vtiger_Utils::Log("Adding Condition " . self::translateComparator($comparator,true) ." on $fieldInstance->name of $this->name filter ... DONE");
return $this;
}
/**
* Translate comparator (condition) to long or short form.
* @access private
* @internal Used from Vtiger_PackageExport also
*/
static function translateComparator($value, $tolongform=false) {
$comparator = false;
if($tolongform) {
$comparator = strtolower($value);
if($comparator == 'e') $comparator = 'EQUALS';
else if($comparator == 'n') $comparator = 'NOT_EQUALS';
else if($comparator == 's') $comparator = 'STARTS_WITH';
else if($comparator == 'ew') $comparator = 'ENDS_WITH';
else if($comparator == 'c') $comparator = 'CONTAINS';
else if($comparator == 'k') $comparator = 'DOES_NOT_CONTAINS';
else if($comparator == 'l') $comparator = 'LESS_THAN';
else if($comparator == 'g') $comparator = 'GREATER_THAN';
else if($comparator == 'm') $comparator = 'LESS_OR_EQUAL';
else if($comparator == 'h') $comparator = 'GREATER_OR_EQUAL';
} else {
$comparator = strtoupper($value);
if($comparator == 'EQUALS') $comparator = 'e';
else if($comparator == 'NOT_EQUALS') $comparator = 'n';
else if($comparator == 'STARTS_WITH') $comparator = 's';
else if($comparator == 'ENDS_WITH') $comparator = 'ew';
else if($comparator == 'CONTAINS') $comparator = 'c';
else if($comparator == 'DOES_NOT_CONTAINS') $comparator = 'k';
else if($comparator == 'LESS_THAN') $comparator = 'l';
else if($comparator == 'GREATER_THAN') $comparator = 'g';
else if($comparator == 'LESS_OR_EQUAL') $comparator = 'm';
else if($comparator == 'GREATER_OR_EQUAL') $comparator = 'h';
}
return $comparator;
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Get instance by filterid or filtername
* @param mixed filterid or filtername
* @param Vtiger_Module Instance of the module to use when filtername is used
*/
static function getInstance($value, $moduleInstance=false) {
global $adb;
$instance = false;
$query = false;
$queryParams = false;
if(Vtiger_Utils::isNumber($value)) {
$query = "SELECT * FROM vtiger_customview WHERE cvid=?";
$queryParams = Array($value);
} else {
$query = "SELECT * FROM vtiger_customview WHERE viewname=? AND entitytype=?";
$queryParams = Array($value, $moduleInstance->name);
}
$result = $adb->pquery($query, $queryParams);
if($adb->num_rows($result)) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance);
}
return $instance;
}
/**
* Get all instances of filter for the module
* @param Vtiger_Module Instance of module
*/
static function getAllForModule($moduleInstance) {
global $adb;
$instances = false;
$query = "SELECT * FROM vtiger_customview WHERE entitytype=?";
$queryParams = Array($moduleInstance->name);
$result = $adb->pquery($query, $queryParams);
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$instance = new self();
$instance->initialize($adb->fetch_array($result), $moduleInstance);
$instances[] = $instance;
}
return $instances;
}
/**
* Delete filter associated for module
* @param Vtiger_Module Instance of module
*/
static function deleteForModule($moduleInstance) {
global $adb;
$cvidres = $adb->pquery("SELECT cvid FROM vtiger_customview WHERE entitytype=?", Array($moduleInstance->name));
if($adb->num_rows($cvidres)) {
$cvids = Array();
for($index = 0; $index < $adb->num_rows($cvidres); ++$index) {
$cvids[] = $adb->query_result($cvidres, $index, 'cvid');
}
if(!empty($cvids)) {
$adb->query("DELETE FROM vtiger_cvadvfilter WHERE cvid IN (" . implode(',', $cvids) . ")");
$adb->query("DELETE FROM vtiger_cvcolumnlist WHERE cvid IN (" . implode(',', $cvids) . ")");
$adb->query("DELETE FROM vtiger_customview WHERE cvid IN (" . implode(',', $cvids) . ")");
}
}
}
}
?>
@@ -0,0 +1,25 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('vtlib/Vtiger/LanguageImport.php');
/**
* Language Manager class for vtiger Modules.
* @package vtlib
*/
class Vtiger_Language extends Vtiger_LanguageImport {
/**
* Constructor
*/
function __construct() {
parent::__construct();
}
}
?>
@@ -0,0 +1,131 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Package.php');
/**
* Provides API to package vtiger CRM language files.
* @package vtlib
*/
class Vtiger_LanguageExport extends Vtiger_Package {
const TABLENAME = 'vtiger_language';
/**
* Constructor
*/
function __construct() {
parent::__construct();
}
/**
* Generate unique id for insertion
* @access private
*/
function __getUniqueId() {
global $adb;
return $adb->getUniqueID(self::TABLENAME);
}
/**
* Initialize Language Schema
* @access private
*/
static function __initSchema() {
$hastable = Vtiger_Utils::CheckTable(self::TABLENAME);
if(!$hastable) {
Vtiger_Utils::CreateTable(
self::TABLENAME,
'(id INT NOT NULL PRIMARY KEY,
name VARCHAR(50), prefix VARCHAR(10), label VARCHAR(30), lastupdated DATETIME, sequence INT, isdefault INT(1), active INT(1))',
true
);
global $languages, $adb;
foreach($languages as $langkey=>$langlabel) {
$uniqueid = self::__getUniqueId();
$adb->pquery('INSERT INTO '.self::TABLENAME.'(id,name,prefix,label,lastupdated,active) VALUES(?,?,?,?,?,?)',
Array($uniqueid, $langlabel,$langkey,$langlabel,date('Y-m-d H:i:s',time()), 1));
}
}
}
/**
* Register language pack information.
*/
static function register($prefix, $label, $name='', $isdefault=false, $isactive=true, $overrideCore=false) {
self::__initSchema();
$prefix = trim($prefix);
// We will not allow registering core language unless forced
if(strtolower($prefix) == 'en_us' && $overrideCore == false) return;
$useisdefault = ($isdefault)? 1 : 0;
$useisactive = ($isactive)? 1 : 0;
global $adb;
$checkres = $adb->pquery('SELECT * FROM '.self::TABLENAME.' WHERE prefix=?', Array($prefix));
$datetime = date('Y-m-d H:i:s');
if($adb->num_rows($checkres)) {
$id = $adb->query_result($checkres, 0, 'id');
$adb->pquery('UPDATE '.self::TABLENAME.' set label=?, name=?, lastupdated=?, isdefault=?, active=? WHERE id=?',
Array($label, $name, $datetime, $useisdefault, $useisactive, $id));
} else {
$uniqueid = self::__getUniqueId();
$adb->pquery('INSERT INTO '.self::TABLENAME.' (id,name,prefix,label,lastupdated,isdefault,active) VALUES(?,?,?,?,?,?,?)',
Array($uniqueid, $name, $prefix, $label, $datetime, $useisdefault, $useisactive));
}
self::log("Registering Language $label [$prefix] ... DONE");
}
/**
* De-Register language pack information
* @param String Language prefix like (de_de) etc
*/
static function deregister($prefix) {
$prefix = trim($prefix);
// We will not allow deregistering core language
if(strtolower($prefix) == 'en_us') return;
self::__initSchema();
global $adb;
$checkres = $adb->pquery('DELETE FROM '.self::TABLENAME.' WHERE prefix=?', Array($prefix));
self::log("Deregistering Language $prefix ... DONE");
}
/**
* Get all the language information
* @param Boolean true to include in-active languages also, false (default)
*/
static function getAll($includeInActive=false) {
global $adb;
$hastable = Vtiger_Utils::CheckTable(self::TABLENAME);
$languageinfo = Array();
if($hastable) {
if($includeInActive) $result = $adb->query('SELECT * FROM '.self::TABLENAME);
else $result = $adb->query('SELECT * FROM '.self::TABLENAME . ' WHERE active=1');
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$resultrow = $adb->fetch_array($result);
$prefix = $resultrow['prefix'];
$label = $resultrow['label'];
$languageinfo[$prefix] = $label;
}
} else {
global $languages;
foreach($languages as $prefix=>$label) {
$languageinfo[$prefix] = $label;
}
}
return $languageinfo;
}
}
?>
@@ -0,0 +1,138 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/LanguageExport.php');
/**
* Provides API to import language into vtiger CRM
* @package vtlib
*/
class Vtiger_LanguageImport extends Vtiger_LanguageExport {
/**
* Constructor
*/
function __construct() {
parent::__construct();
}
function getPrefix() {
return $this->_modulexml->name;
}
/**
* Initialize Import
* @access private
*/
function initImport($zipfile, $overwrite) {
$this->__initSchema();
$name = $this->getModuleNameFromZip($zipfile);
}
/**
* Import Module from zip file
* @param String Zip file name
* @param Boolean True for overwriting existing module
*/
function import($zipfile, $overwrite=false) {
$this->initImport($zipfile, $overwrite);
// Call module import function
$this->import_Language($zipfile);
}
/**
* Update Module from zip file
* @param Object Instance of Language (to keep Module update API consistent)
* @param String Zip file name
* @param Boolean True for overwriting existing module
*/
function update($instance, $zipfile, $overwrite=true) {
$this->import($zipfile, $overwrite);
}
/**
* Import Module
* @access private
*/
function import_Language($zipfile) {
$name = $this->_modulexml->name;
$prefix = $this->_modulexml->prefix;
$label = $this->_modulexml->label;
self::log("Importing $label [$prefix] ... STARTED");
$unzip = new Vtiger_Unzip($zipfile);
$filelist = $unzip->getList();
foreach($filelist as $filename=>$fileinfo) {
if(!$unzip->isdir($filename)) {
if(strpos($filename, '/') === false) continue;
$targetdir = substr($filename, 0, strripos($filename,'/'));
$targetfile = basename($filename);
$prefixparts = split('_', $prefix);
$dounzip = false;
if(is_dir($targetdir)) {
// Case handling for jscalendar
if(stripos($targetdir, 'jscalendar/lang') === 0
&& stripos($targetfile, "calendar-".$prefixparts[0].".js")===0) {
if(file_exists("$targetdir/calendar-en.js")) {
$dounzip = true;
}
}
// Case handling for phpmailer
else if(stripos($targetdir, 'modules/Emails/language') === 0
&& stripos($targetfile, "phpmailer.lang-$prefix.php")===0) {
if(file_exists("$targetdir/phpmailer.lang-en_us.php")) {
$dounzip = true;
}
}
// Handle javascript language file
else if(preg_match("/$prefix.lang.js/", $targetfile)) {
$corelangfile = "$targetdir/en_us.lang.js";
if(file_exists($corelangfile)) {
$dounzip = true;
}
}
// Handle php language file
else if(preg_match("/$prefix.lang.php/", $targetfile)) {
$corelangfile = "$targetdir/en_us.lang.php";
if(file_exists($corelangfile)) {
$dounzip = true;
}
}
}
if($dounzip) {
if($unzip->unzip($filename, $filename) !== false) {
self::log("Copying file $filename ... DONE");
} else {
self::log("Copying file $filename ... FAILED");
}
} else {
self::log("Copying file $filename ... SKIPPED");
}
}
}
if($unzip) $unzip->close();
self::register($prefix, $label, $name);
self::log("Importing $label [$prefix] ... DONE");
return;
}
}
?>
+224
View File
@@ -0,0 +1,224 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
include_once('vtlib/Vtiger/Utils/StringTemplate.php');
/**
* Provides API to handle custom links
* @package vtlib
*/
class Vtiger_Link {
var $tabid;
var $linkid;
var $linktype;
var $linklabel;
var $linkurl;
var $linkicon;
var $sequence;
var $status = false;
// Ignore module while selection
const IGNORE_MODULE = -1;
/**
* Constructor
*/
function __construct() {
}
/**
* Initialize this instance.
*/
function initialize($valuemap) {
$this->tabid = $valuemap['tabid'];
$this->linkid = $valuemap['linkid'];
$this->linktype=$valuemap['linktype'];
$this->linklabel=$valuemap['linklabel'];
$this->linkurl =decode_html($valuemap['linkurl']);
$this->linkicon =decode_html($valuemap['linkicon']);
$this->sequence =$valuemap['sequence'];
$this->status =$valuemap['status'];
}
/**
* Get module name.
*/
function module() {
if(!empty($this->tabid)) {
return getTabModuleName($this->tabid);
}
return false;
}
/**
* Get unique id for the insertion
*/
static function __getUniqueId() {
global $adb;
return $adb->getUniqueID('vtiger_links');
}
/** Cache (Record) the schema changes to improve performance */
static $__cacheSchemaChanges = Array();
/**
* Initialize the schema (tables)
*/
static function __initSchema() {
if(empty(self::$__cacheSchemaChanges['vtiger_links'])) {
if(!Vtiger_Utils::CheckTable('vtiger_links')) {
Vtiger_Utils::CreateTable(
'vtiger_links',
'(linkid INT NOT NULL PRIMARY KEY,
tabid INT, linktype VARCHAR(20), linklabel VARCHAR(30), linkurl VARCHAR(255), linkicon VARCHAR(100), sequence INT, status INT(1) NOT NULL DEFAULT 1)',
true);
Vtiger_Utils::ExecuteQuery(
'CREATE INDEX link_tabidtype_idx on vtiger_links(tabid,linktype)');
}
self::$__cacheSchemaChanges['vtiger_links'] = true;
}
}
/**
* Add link given module
* @param Integer Module ID
* @param String Link Type (like DETAILVIEW). Useful for grouping based on pages.
* @param String Label to display
* @param String HREF value or URL to use for the link
* @param String ICON to use on the display
* @param Integer Order or sequence of displaying the link
*/
static function addLink($tabid, $type, $label, $url, $iconpath='',$sequence=0) {
global $adb;
self::__initSchema();
$checkres = $adb->pquery('SELECT linkid FROM vtiger_links WHERE tabid=? AND linktype=? AND linkurl=? AND linkicon=? AND linklabel=?',
Array($tabid, $type, $url, $iconpath, $label));
if(!$adb->num_rows($checkres)) {
$uniqueid = self::__getUniqueId();
$adb->pquery('INSERT INTO vtiger_links (linkid,tabid,linktype,linklabel,linkurl,linkicon,sequence) VALUES(?,?,?,?,?,?,?)',
Array($uniqueid, $tabid, $type, $label, $url, $iconpath, $sequence));
self::log("Adding Link ($type - $label) ... DONE");
}
}
/**
* Delete link of the module
* @param Integer Module ID
* @param String Link Type (like DETAILVIEW). Useful for grouping based on pages.
* @param String Display label
* @param String URL of link to lookup while deleting
*/
static function deleteLink($tabid, $type, $label, $url=false) {
global $adb;
self::__initSchema();
if($url) {
$adb->pquery('DELETE FROM vtiger_links WHERE tabid=? AND linktype=? AND linklabel=? AND linkurl=?',
Array($tabid, $type, $label, $url));
self::log("Deleting Link ($type - $label - $url) ... DONE");
} else {
$adb->pquery('DELETE FROM vtiger_links WHERE tabid=? AND linktype=? AND linklabel=?',
Array($tabid, $type, $label));
self::log("Deleting Link ($type - $label) ... DONE");
}
}
/**
* Delete all links related to module
* @param Integer Module ID.
*/
static function deleteAll($tabid) {
global $adb;
self::__initSchema();
$adb->pquery('DELETE FROM vtiger_links WHERE tabid=?', Array($tabid));
self::log("Deleting Links ... DONE");
}
/**
* Get all the links related to module
* @param Integer Module ID.
*/
static function getAll($tabid) {
return self::getAllByType($tabid);
}
/**
* Get all the link related to module based on type
* @param Integer Module ID
* @param mixed String or List of types to select
* @param Map Key-Value pair to use for formating the link url
*/
static function getAllByType($tabid, $type=false, $parameters=false) {
global $adb;
self::__initSchema();
$multitype = false;
if($type) {
// Multiple link type selection?
if(is_array($type)) {
$multitype = true;
if($tabid === self::IGNORE_MODULE) {
$result = $adb->pquery('SELECT * FROM vtiger_links WHERE linktype IN ('.
Vtiger_Utils::implodestr('?', count($type), ',') .')',
Array($adb->flatten_array($type)));
} else {
$result = $adb->pquery('SELECT * FROM vtiger_links WHERE tabid=? AND linktype IN ('.
Vtiger_Utils::implodestr('?', count($type), ',') .')',
Array($tabid, $adb->flatten_array($type)));
}
} else {
// Single link type selection
if($tabid === self::IGNORE_MODULE) {
$result = $adb->pquery('SELECT * FROM vtiger_links WHERE linktype=?', Array($type));
} else {
$result = $adb->pquery('SELECT * FROM vtiger_links WHERE tabid=? AND linktype=?', Array($tabid, $type));
}
}
} else {
$result = $adb->pquery('SELECT * FROM vtiger_links WHERE tabid=?', Array($tabid));
}
$strtemplate = new Vtiger_StringTemplate();
if($parameters) {
foreach($parameters as $key=>$value) $strtemplate->assign($key, $value);
}
$instances = Array();
if($multitype) {
foreach($type as $t) $instances[$t] = Array();
}
while($row = $adb->fetch_array($result)){
$instance = new self();
$instance->initialize($row);
if($parameters) {
$instance->linkurl = $strtemplate->merge($instance->linkurl);
$instance->linkicon= $strtemplate->merge($instance->linkicon);
}
if($multitype) {
$instances[$instance->linktype][] = $instance;
} else {
$instances[] = $instance;
}
}
return $instances;
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delimit=true) {
Vtiger_Utils::Log($message, $delimit);
}
}
?>
+233
View File
@@ -0,0 +1,233 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('modules/Emails/class.phpmailer.php');
include_once('config.inc.php');
include_once('include/database/PearDatabase.php');
include_once('vtlib/Vtiger/Utils.php');
include_once('vtlib/Vtiger/Event.php');
/**
* Provides API to work with PHPMailer & Email Templates
* @package vtlib
*/
class Vtiger_Mailer extends PHPMailer {
var $_serverConfigured = false;
/**
* Constructor
*/
function __construct() {
$this->initialize();
}
/**
* Get the unique id for insertion
* @access private
*/
function __getUniqueId() {
global $adb;
return $adb->getUniqueID('vtiger_mailer_queue');
}
/**
* Initialize this instance
* @access private
*/
function initialize() {
$this->IsSMTP();
global $adb;
$result = $adb->pquery("SELECT * FROM vtiger_systems WHERE server_type=?", Array('email'));
if($adb->num_rows($result)) {
$this->Host = $adb->query_result($result, 0, 'server');
$this->Username = $adb->query_result($result, 0, 'server_username');
$this->Password = $adb->query_result($result, 0, 'server_password');
$this->SMTPAuth = $adb->query_result($result, 0, 'smtp_auth');
if(empty($this->SMTPAuth)) $this->SMTPAuth = false;
$this->_serverConfigured = true;
}
}
/**
* Reinitialize this instance for use
* @access private
*/
function reinitialize() {
$this->From = '';
$this->FromName = '';
$this->to = Array();
$this->cc = Array();
$this->bcc = Array();
$this->ReplyTo = Array();
$this->Body = '';
$this->Subject ='';
$this->attachment = Array();
}
/**
* Initialize this instance using mail template
* @access private
*/
function initFromTemplate($emailtemplate) {
global $adb;
$result = $adb->pquery("SELECT * from vtiger_emailtemplates WHERE templatename=? AND foldername=?",
Array($emailtemplate, 'Public'));
if($adb->num_rows($result)) {
$this->IsHTML(true);
$usesubject = $adb->query_result($result, 0, 'subject');
$usebody = decode_html($adb->query_result($result, 0, 'body'));
$this->Subject = $usesubject;
$this->Body = $usebody;
return true;
}
return false;
}
/**
* Configure sender information
*/
function ConfigSenderInfo($fromemail, $fromname='', $replyto='') {
if(empty($fromname)) $fromname = $fromemail;
$this->From = $fromemail;
$this->FromName = $fromname;
$this->AddReplyTo($replyto);
}
/**
* Overriding default send
*/
function Send($sync=false, $linktoid=false) {
if(!$this->_serverConfigured) return;
if($sync) return parent::Send();
$this->__AddToQueue($linktoid);
return true;
}
/**
* Send mail using the email template
* @param String Recipient email
* @param String Recipient name
* @param String vtiger CRM Email template name to use
*/
function SendTo($toemail, $toname='', $emailtemplate=false, $linktoid=false, $sync=false) {
if(empty($toname)) $toname = $toemail;
$this->AddAddress($toemail, $toname);
if($emailtemplate) $this->initFromTemplate($emailtemplate);
return $this->Send($sync, $linktoid);
}
/** Mail Queue **/
// Check if this instance is initialized.
var $_queueinitialized = false;
function __initializeQueue() {
if(!$this->_queueinitialized) {
if(!Vtiger_Utils::CheckTable('vtiger_mailer_queue')) {
Vtiger_Utils::CreateTable('vtiger_mailer_queue',
'(id INT NOT NULL PRIMARY KEY,
fromname VARCHAR(100), fromemail VARCHAR(100),
mailer VARCHAR(10), content_type VARCHAR(15), subject VARCHAR(999), body TEXT, relcrmid INT,
failed INT(1) NOT NULL DEFAULT 0, failreason VARCHAR(255))',
true);
}
if(!Vtiger_Utils::CheckTable('vtiger_mailer_queueinfo')) {
Vtiger_Utils::CreateTable('vtiger_mailer_queueinfo',
'(id INTEGER, name VARCHAR(100), email VARCHAR(100), type VARCHAR(7))',
true);
}
$this->_queueinitialized = true;
}
return true;
}
/**
* Add this mail to queue
*/
function __AddToQueue($linktoid) {
if($this->__initializeQueue()) {
global $adb;
$uniqueid = self::__getUniqueId();
$adb->pquery('INSERT INTO vtiger_mailer_queue(id,fromname,fromemail,content_type,subject,body,mailer,relcrmid) VALUES(?,?,?,?,?,?,?,?)',
Array($uniqueid, $this->FromName, $this->From, $this->ContentType, $this->Subject, $this->Body, $this->Mailer, $linktoid));
$queueid = $adb->database->Insert_ID();
foreach($this->to as $toinfo) {
if(empty($toinfo[0])) continue;
$adb->pquery('INSERT INTO vtiger_mailer_queueinfo(id, name, email, type) VALUES(?,?,?,?)',
Array($queueid, $toinfo[1], $toinfo[0], 'TO'));
}
foreach($this->cc as $ccinfo) {
if(empty($ccinfo[0])) continue;
$adb->pquery('INSERT INTO vtiger_mailer_queueinfo(id, name, email, type) VALUES(?,?,?,?)',
Array($queueid, $ccinfo[1], $ccinfo[0], 'CC'));
}
foreach($this->bcc as $bccinfo) {
if(empty($bccinfo[0])) continue;
$adb->pquery('INSERT INTO vtiger_mailer_queueinfo(id, name, email, type) VALUES(?,?,?,?)',
Array($queueid, $bccinfo[1], $bccinfo[0], 'BCC'));
}
foreach($this->ReplyTo as $rtoinfo) {
if(empty($rtoinfo[0])) continue;
$adb->pquery('INSERT INTO vtiger_mailer_queueinfo(id, name, email, type) VALUES(?,?,?,?)',
Array($queueid, $rtoinfo[1], $rtoinfo[0], 'RPLYTO'));
}
}
}
/**
* Dispatch (send) email that was queued.
*/
static function dispatchQueue() {
global $adb;
if(!Vtiger_Utils::CheckTable('vtiger_mailer_queue')) return;
$mailer = new self();
$queue = $adb->query('SELECT * FROM vtiger_mailer_queue WHERE failed != 1');
if($adb->num_rows($queue)) {
for($index = 0; $index < $adb->num_rows($queue); ++$index) {
$mailer->reinitialize();
$queue_record = $adb->fetch_array($queue, $index);
$queueid = $queue_record['id'];
$relcrmid= $queue_record['relcrmid'];
$mailer->From = $queue_record['fromemail'];
$mailer->From = $queue_record['fromname'];
$mailer->Subject=$queue_record['subject'];
$mailer->Body = decode_html($queue_record['body']);
$mailer->Mailer=$queue_record['mailer'];
$mailer->ContentType = $queue_record['content_type'];
$emails = $adb->pquery('SELECT * FROM vtiger_mailer_queueinfo WHERE id=?', Array($queueid));
for($eidx = 0; $eidx < $adb->num_rows($emails); ++$eidx) {
$email_record = $adb->fetch_array($emails, $eidx);
if($email_record[type] == 'TO') $mailer->AddAddress($email_record[email], $email_record[name]);
else if($email_record[type] == 'CC')$mailer->AddCC($email_record[email], $email_record[name]);
else if($email_record[type] == 'BCC')$mailer->AddBCC($email_record[email], $email_record[name]);
else if($email_record[type] == 'RPLYTO')$mailer->AddReplyTo($email_record[email], $email_record[name]);
}
$sent = $mailer->Send(true);
if($sent) {
Vtiger_Event::trigger('vtiger.mailer.mailsent', $relcrmid);
$adb->pquery('DELETE FROM vtiger_mailer_queue WHERE id=?', Array($queueid));
$adb->pquery('DELETE FROM vtiger_mailer_queueinfo WHERE id=?', Array($queueid));
} else {
$adb->pquery('UPDATE vtiger_mailer_queueinfo SET failed=?, failreason=? WHERE id=?', Array(1, $mailer->ErrorInfo, $queueid));
}
}
}
}
}
?>
+142
View File
@@ -0,0 +1,142 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
/**
* Provides API to work with vtiger CRM Menu
* @package vtlib
*/
class Vtiger_Menu {
/** ID of this menu instance */
var $id = false;
var $label = false;
var $sequence = false;
var $visible = 0;
/**
* Constructor
*/
function __construct() {
}
/**
* Initialize this instance
* @param Array Map
* @access private
*/
function initialize($valuemap) {
$this->id = $valuemap[parenttabid];
$this->label = $valuemap[parenttab_label];
$this->sequence = $valuemap[sequence];
$this->visible = $valuemap[visible];
}
/**
* Get relation sequence to use
* @access private
*/
function __getNextRelSequence() {
global $adb;
$result = $adb->pquery("SELECT MAX(sequence) AS max_seq FROM vtiger_parenttabrel WHERE parenttabid=?",
Array($this->id));
$maxseq = $adb->query_result($result, 0, 'max_seq');
return ++$maxseq;
}
/**
* Add module to this menu instance
* @param Vtiger_Module Instance of the module
*/
function addModule($moduleInstance) {
if($this->id) {
global $adb;
$relsequence = $this->__getNextRelSequence();
$adb->pquery("INSERT INTO vtiger_parenttabrel (parenttabid,tabid,sequence) VALUES(?,?,?)",
Array($this->id, $moduleInstance->id, $relsequence));
self::log("Added to menu $this->label ... DONE");
} else {
self::log("Menu could not be found!");
}
self::syncfile();
}
/**
* Remove module from this menu instance.
* @param Vtiger_Module Instance of the module
*/
function removeModule($moduleInstance) {
if(empty($moduleInstance) || empty($moduleInstance)) {
self::log("Module instance is not set!");
return;
}
if($this->id) {
global $adb;
$adb->pquery("DELETE FROM vtiger_parenttabrel WHERE parenttabid = ? AND tabid = ?",
Array($this->id, $moduleInstance->id));
self::log("Removed $moduleInstance->name from menu $this->label ... DONE");
} else {
self::log("Menu could not be found!");
}
self::syncfile();
}
/**
* Detach module from menu
* @param Vtiger_Module Instance of the module
*/
static function detachModule($moduleInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_parenttabrel WHERE tabid=?", Array($moduleInstance->id));
self::log("Detaching from menu ... DONE");
self::syncfile();
}
/**
* Get instance of menu by label
* @param String Menu label
*/
static function getInstance($value) {
global $adb;
$query = false;
$instance = false;
if(Vtiger_Utils::isNumber($value)) {
$query = "SELECT * FROM vtiger_parenttab WHERE parenttabid=?";
} else {
$query = "SELECT * FROM vtiger_parenttab WHERE parenttab_label=?";
}
$result = $adb->pquery($query, Array($value));
if($adb->num_rows($result)) {
$instance = new self();
$instance->initialize($adb->fetch_array($result));
}
return $instance;
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Synchronize the menu information to flat file
* @access private
*/
static function syncfile() {
self::log("Updating parent_tabdata file ... STARTED");
create_parenttab_data_file();
self::log("Updating parent_tabdata file ... DONE");
}
}
?>
+193
View File
@@ -0,0 +1,193 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/ModuleBasic.php');
/**
* Provides API to work with vtiger CRM Modules
* @package vtlib
*/
class Vtiger_Module extends Vtiger_ModuleBasic {
/**
* Get unique id for related list
* @access private
*/
function __getRelatedListUniqueId() {
global $adb;
return $adb->getUniqueID('vtiger_relatedlists');
}
/**
* Get related list sequence to use
* @access private
*/
function __getNextRelatedListSequence() {
global $adb;
$max_sequence = 0;
$result = $adb->pquery("SELECT max(sequence) as maxsequence FROM vtiger_relatedlists WHERE tabid=?", Array($this->id));
if($adb->num_rows($result)) $max_sequence = $adb->query_result($result, 0, 'maxsequence');
return ++$max_sequence;
}
/**
* Set related list information between other module
* @param Vtiger_Module Instance of target module with which relation should be setup
* @param String Label to display in related list (default is target module name)
* @param Array List of action button to show ('ADD', 'SELECT')
* @param String Callback function name of this module to use as handler
*
* @internal Creates table vtiger_crmentityrel if it does not exists
*/
function setRelatedList($moduleInstance, $label='', $actions=false, $function_name='get_related_list') {
global $adb;
if(empty($moduleInstance)) return;
Vtiger_Utils::CreateTable(
'vtiger_crmentityrel',
'(crmid INT NOT NULL, module VARCHAR(100) NOT NULL, relcrmid INT NOT NULL, relmodule VARCHAR(100) NOT NULL)',
true
);
$relation_id = $this->__getRelatedListUniqueId();
$sequence = $this->__getNextRelatedListSequence();
$presence = 0; // 0 - Enabled, 1 - Disabled
if(empty($label)) $label = $moduleInstance->name;
// Allow ADD action of other module records (default)
if($actions === false) $actions = Array('ADD');
$useactions_text = $actions;
if(is_array($actions)) $useactions_text = implode(',', $actions);
$useactions_text = strtoupper($useactions_text);
// Add column to vtiger_relatedlists to save extended actions
Vtiger_Utils::AddColumn('vtiger_relatedlists', 'actions', 'VARCHAR(50)');
$adb->pquery("INSERT INTO vtiger_relatedlists(relation_id,tabid,related_tabid,name,sequence,label,presence,actions) VALUES(?,?,?,?,?,?,?,?)",
Array($relation_id,$this->id,$moduleInstance->id,$function_name,$sequence,$label,$presence,$useactions_text));
self::log("Setting relation with $moduleInstance->name [$useactions_text] ... DONE");
}
/**
* Unset related list information that exists with other module
* @param Vtiger_Module Instance of target module with which relation should be setup
* @param String Label to display in related list (default is target module name)
* @param String Callback function name of this module to use as handler
*/
function unsetRelatedList($moduleInstance, $label='', $function_name='get_related_list') {
global $adb;
if(empty($moduleInstance)) return;
if(empty($label)) $label = $moduleInstance->name;
$adb->pquery("DELETE FROM vtiger_relatedlists WHERE tabid=? AND related_tabid=? AND name=? AND label=?",
Array($this->id, $moduleInstance->id, $function_name, $label));
self::log("Unsetting relation with $moduleInstance->name ... DONE");
}
/**
* Add custom link for a module page
* @param String Type can be like 'DETAILVIEW', 'LISTVIEW' etc..
* @param String Label to use for display
* @param String HREF value to use for generated link
* @param String Path to the image file (relative or absolute)
* @param Integer Sequence of appearance
*
* NOTE: $url can have variables like $MODULE (module for which link is associated),
* $RECORD (record on which link is dispalyed)
*/
function addLink($type, $label, $url, $iconpath='', $sequence=0) {
Vtiger_Link::addLink($this->id, $type, $label, $url, $iconpath, $sequence);
}
/**
* Delete custom link of a module
* @param String Type can be like 'DETAILVIEW', 'LISTVIEW' etc..
* @param String Display label to lookup
* @param String URL value to lookup
*/
function deleteLink($type, $label, $url=false) {
Vtiger_Link::deleteLink($this->id, $type, $label, $url);
}
/**
* Get all the custom links related to this module.
*/
function getLinks() {
return Vtiger_Link::getAll($this->id);
}
/**
* Initialize webservice setup for this module instance.
*/
function initWebservice() {
Vtiger_Webservice::initialize($this);
}
/**
* Get instance by id or name
* @param mixed id or name of the module
*/
static function getInstance($value) {
global $adb;
$instance = false;
$query = false;
if(Vtiger_Utils::isNumber($value)) {
$query = "SELECT * FROM vtiger_tab WHERE tabid=?";
} else {
$query = "SELECT * FROM vtiger_tab WHERE name=?";
}
$result = $adb->pquery($query, Array($value));
if($adb->num_rows($result)) {
$instance = new self();
$instance->initialize($adb->fetch_array($result));
}
return $instance;
}
/**
* Get instance of the module class.
* @param String Module name
*/
static function getClassInstance($modulename) {
if($modulename == 'Calendar') $modulename = 'Activity';
$instance = false;
$filepath = "modules/$modulename/$modulename.php";
if(Vtiger_Utils::checkFileAccess($filepath, false)) {
include_once($filepath);
if(class_exists($modulename)) {
$instance = new $modulename();
}
}
return $instance;
}
/**
* Fire the event for the module (if vtlib_handler is defined)
*/
static function fireEvent($modulename, $event_type) {
$instance = self::getClassInstance((string)$modulename);
if($instance) {
if(method_exists($instance, 'vtlib_handler')) {
self::log("Invoking vtlib_handler for $event_type ...START");
$instance->vtlib_handler((string)$modulename, (string)$event_type);
self::log("Invoking vtlib_handler for $event_type ...DONE");
}
}
}
}
?>
@@ -0,0 +1,389 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Access.php');
include_once('vtlib/Vtiger/Block.php');
include_once('vtlib/Vtiger/Field.php');
include_once('vtlib/Vtiger/Filter.php');
include_once('vtlib/Vtiger/Profile.php');
include_once('vtlib/Vtiger/Menu.php');
include_once('vtlib/Vtiger/Link.php');
include_once('vtlib/Vtiger/Event.php');
include_once('vtlib/Vtiger/Webservice.php');
include_once('vtlib/Vtiger/Version.php');
/**
* Provides API to work with vtiger CRM Module
* @package vtlib
*/
class Vtiger_ModuleBasic {
/** ID of this instance */
var $id = false;
var $name = false;
var $label = false;
var $version= 0;
var $presence = 0;
var $ownedby = 0; // 0 - Sharing Access Enabled, 1 - Sharing Access Disabled
var $tabsequence = false;
var $isentitytype = true; // Real module or an extension?
var $entityidcolumn = false;
var $entityidfield = false;
var $basetable = false;
var $basetableid=false;
var $customtable=false;
var $grouptable = false;
const EVENT_MODULE_ENABLED = 'module.enabled';
const EVENT_MODULE_DISABLED = 'module.disabled';
const EVENT_MODULE_POSTINSTALL = 'module.postinstall';
const EVENT_MODULE_PREUNINSTALL= 'module.preuninstall';
const EVENT_MODULE_PREUPDATE = 'module.preupdate';
const EVENT_MODULE_POSTUPDATE = 'module.postupdate';
/**
* Constructor
*/
function __construct() {
}
/**
* Initialize this instance
* @access private
*/
function initialize($valuemap) {
$this->id = $valuemap['tabid'];
$this->name=$valuemap['name'];
$this->label=$valuemap['tablabel'];
$this->version=$valuemap['version'];
$this->presence = $valuemap['presence'];
$this->ownedby = $valuemap['ownedby'];
$this->tabsequence = $valuemap['tabsequence'];
$this->isentitytype = $valuemap['isentitytype'];
if($this->isentitytype || $this->name == 'Users') {
// Initialize other details too
$this->initialize2();
}
}
/**
* Initialize more information of this instance
* @access private
*/
function initialize2() {
global $adb;
$result = $adb->pquery("SELECT tablename,entityidfield FROM vtiger_entityname WHERE tabid=?",
Array($this->id));
if($adb->num_rows($result)) {
$this->basetable = $adb->query_result($result, 0, 'tablename');
$this->basetableid=$adb->query_result($result, 0, 'entityidfield');
}
}
/**
* Get unique id for this instance
* @access private
*/
function __getUniqueId() {
global $adb;
$result = $adb->query("SELECT MAX(tabid) AS max_seq FROM vtiger_tab");
$maxseq = $adb->query_result($result, 0, 'max_seq');
return ++$maxseq;
}
/**
* Get next sequence to use for this instance
* @access private
*/
function __getNextSequence() {
global $adb;
$result = $adb->query("SELECT MAX(tabsequence) AS max_tabseq FROM vtiger_tab");
$maxtabseq = $adb->query_result($result, 0, 'max_tabseq');
return ++$maxtabseq;
}
/**
* Initialize vtiger schema changes.
* @access private
*/
function __handleVtigerCoreSchemaChanges() {
// Add version column to the table first
Vtiger_Utils::AddColumn('vtiger_tab', 'version', ' VARCHAR(10)');
}
/**
* Create this module instance
* @access private
*/
function __create() {
global $adb;
self::log("Creating Module $this->name ... STARTED");
$this->id = $this->__getUniqueId();
if(!$this->tabsequence) $this->tabsequence = $this->__getNextSequence();
if(!$this->label) $this->label = $this->name;
$customized = 1; // To indicate this is a Custom Module
$this->__handleVtigerCoreSchemaChanges();
$adb->pquery("INSERT INTO vtiger_tab (tabid,name,presence,tabsequence,tablabel,modifiedby,
modifiedtime,customized,ownedby,version) VALUES (?,?,?,?,?,?,?,?,?,?)",
Array($this->id, $this->name, $this->presence, $this->tabsequence, $this->label, NULL, NULL, $customized, $this->ownedby, $this->version));
$useisentitytype = $this->isentitytype? 1 : 0;
$adb->pquery('UPDATE vtiger_tab set isentitytype=? WHERE tabid=?',Array($useisentitytype, $this->id));
Vtiger_Profile::initForModule($this);
self::syncfile();
if($this->isentitytype) {
Vtiger_Access::initSharing($this);
}
self::log("Creating Module $this->name ... DONE");
}
/**
* Update this instance
* @access private
*/
function __update() {
self::log("Updating Module $this->name ... DONE");
}
/**
* Delete this instance
* @access private
*/
function __delete() {
Vtiger_Module::fireEvent($this->name,
Vtiger_Module::EVENT_MODULE_PREUNINSTALL);
global $adb;
if($this->isentitytype) {
$this->unsetEntityIdentifier();
$this->deleteRelatedLists();
}
$adb->pquery("DELETE FROM vtiger_tab WHERE tabid=?", Array($this->id));
self::log("Deleting Module $this->name ... DONE");
}
/**
* Update module version information
* @access private
*/
function __updateVersion($newversion) {
$this->__handleVtigerCoreSchemaChanges();
global $adb;
$adb->pquery("UPDATE vtiger_tab SET version=? WHERE tabid=?", Array($newversion, $this->id));
$this->version = $newversion;
self::log("Updating version to $newversion ... DONE");
}
/**
* Save this instance
*/
function save() {
if($this->id) $this->__update();
else $this->__create();
return $this->id;
}
/**
* Delete this instance
*/
function delete() {
if($this->isentitytype) {
Vtiger_Access::deleteSharing($this);
Vtiger_Access::deleteTools($this);
Vtiger_Filter::deleteForModule($this);
Vtiger_Block::deleteForModule($this);
}
$this->__delete();
Vtiger_Profile::deleteForModule($this);
Vtiger_Link::deleteAll($this->id);
Vtiger_Menu::detachModule($this);
self::syncfile();
}
/**
* Initialize table required for the module
* @param String Base table name (default modulename in lowercase)
* @param String Base table column (default modulenameid in lowercase)
*
* Creates basetable, customtable, grouptable <br>
* customtable name is basetable + 'cf'<br>
* grouptable name is basetable + 'grouprel'<br>
*/
function initTables($basetable=false, $basetableid=false) {
$this->basetable = $basetable;
$this->basetableid=$basetableid;
// Initialize tablename and index column names
$lcasemodname = strtolower($this->name);
if(!$this->basetable) $this->basetable = "vtiger_$lcasemodname";
if(!$this->basetableid)$this->basetableid=$lcasemodname . "id";
if(!$this->customtable)$this->customtable = $this->basetable . "cf";
if(!$this->grouptable)$this->grouptable = $this->basetable."grouprel";
Vtiger_Utils::CreateTable($this->basetable,"($this->basetableid INT)",true);
Vtiger_Utils::CreateTable($this->customtable,
"($this->basetableid INT PRIMARY KEY)", true);
if(Vtiger_Version::check('5.0.4', '<=')) {
Vtiger_Utils::CreateTable($this->grouptable,
"($this->basetableid INT PRIMARY KEY, groupname varchar(100))",true);
}
}
/**
* Set entity identifier field for this module
* @param Vtiger_Field Instance of field to use
*/
function setEntityIdentifier($fieldInstance) {
global $adb;
if($this->basetableid) {
if(!$this->entityidfield) $this->entityidfield = $this->basetableid;
if(!$this->entityidcolumn)$this->entityidcolumn= $this->basetableid;
}
if($this->entityidfield && $this->entityidcolumn) {
$adb->pquery("INSERT INTO vtiger_entityname(tabid, modulename, tablename, fieldname, entityidfield, entityidcolumn) VALUES(?,?,?,?,?,?)",
Array($this->id, $this->name, $fieldInstance->table, $fieldInstance->name, $this->entityidfield, $this->entityidcolumn));
self::log("Setting entity identifier ... DONE");
}
}
/**
* Unset entity identifier information
*/
function unsetEntityIdentifier() {
global $adb;
$adb->pquery("DELETE FROM vtiger_entityname WHERE tabid=?", Array($this->id));
self::log("Unsetting entity identifier ... DONE");
}
/**
* Delete related lists information
*/
function deleteRelatedLists() {
global $adb;
$adb->pquery("DELETE FROM vtiger_relatedlists WHERE tabid=?", Array($this->id));
self::log("Deleting related lists ... DONE");
}
/**
* Configure default sharing access for the module
* @param String Permission text should be one of ['Public_ReadWriteDelete', 'Public_ReadOnly', 'Public_ReadWrite', 'Private']
*/
function setDefaultSharing($permission_text='Public_ReadWriteDelete') {
Vtiger_Access::setDefaultSharing($this, $permission_text);
}
/**
* Allow module sharing control
*/
function allowSharing() {
Vtiger_Access::allowSharing($this, true);
}
/**
* Disallow module sharing control
*/
function disallowSharing() {
Vtiger_Access::allowSharing($this, false);
}
/**
* Enable tools for this module
* @param mixed String or Array with value ['Import', 'Export', 'Merge']
*/
function enableTools($tools) {
if(is_string($tools)) {
$tools = Array(0 => $tools);
}
foreach($tools as $tool) {
Vtiger_Access::updateTool($this, $tool, true);
}
}
/**
* Disable tools for this module
* @param mixed String or Array with value ['Import', 'Export', 'Merge']
*/
function disableTools($tools) {
if(is_string($tools)) {
$tools = Array(0 => $tools);
}
foreach($tools as $tool) {
Vtiger_Access::updateTool($this, $tool, false);
}
}
/**
* Add block to this module
* @param Vtiger_Block Instance of block to add
*/
function addBlock($blockInstance) {
$blockInstance->save($this);
return $this;
}
/**
* Add filter to this module
* @param Vtiger_Filter Instance of filter to add
*/
function addFilter($filterInstance) {
$filterInstance->save($this);
return $this;
}
/**
* Get all the fields of the module or block
* @param Vtiger_Block Instance of block to use to get fields, false to get all the block fields
*/
function getFields($blockInstance=false) {
$fields = false;
if($blockInstance) $fields = Vtiger_Field::getAllForBlock($blockInstance, $this);
else $fields = Vtiger_Field::getAllForModule($this);
return $fields;
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delimit=true) {
Vtiger_Utils::Log($message, $delimit);
}
/**
* Synchronize the menu information to flat file
* @access private
*/
static function syncfile() {
self::log("Updating tabdata file ... ", false);
create_tab_data_file();
self::log("DONE");
}
}
?>
@@ -0,0 +1,117 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
include 'vtlib/thirdparty/network/Request.php';
/**
* Provides API to work with HTTP Connection.
* @package vtlib
*/
class Vtiger_Net_Client {
var $client;
var $url;
var $response;
/**
* Constructor
* @param String URL of the site
* Example:
* $client = new Vtiger_New_Client('http://www.vtiger.com');
*/
function __construct($url) {
$this->setURL($url);
}
/**
* Set another url for this instance
* @param String URL to use go forward
*/
function setURL($url) {
$this->url = $url;
$this->client = new HTTP_Request();
$this->response = false;
}
/**
* Set custom HTTP Headers
* @param Map HTTP Header and Value Pairs
*/
function setHeaders($values) {
foreach($values as $key=>$value) {
$this->client->addHeader($key, $value);
}
}
/**
* Perform a GET request
* @param Map key-value pair or false
* @param Integer timeout value
*/
function doGet($params=false, $timeout=null) {
if($timeout) $this->client->_timeout = $timeout;
$this->client->setURL($this->url);
$this->client->setMethod(HTTP_REQUEST_METHOD_GET);
if($params) {
foreach($params as $key=>$value)
$this->client->addQueryString($key, $value);
}
$this->response = $this->client->sendRequest();
$content = false;
if(!$this->wasError()) {
$content = $this->client->getResponseBody();
}
$this->disconnect();
return $content;
}
/**
* Perform a POST request
* @param Map key-value pair or false
* @param Integer timeout value
*/
function doPost($params=false, $timeout=null) {
if($timeout) $this->client->_timeout = $timeout;
$this->client->setURL($this->url);
$this->client->setMethod(HTTP_REQUEST_METHOD_POST);
if($params) {
if(is_string($params)) $this->client->addRawPostData($params);
else {
foreach($params as $key=>$value)
$this->client->addPostData($key, $value);
}
}
$this->response = $this->client->sendRequest();
$content = false;
if(!$this->wasError()) {
$content = $this->client->getResponseBody();
}
$this->disconnect();
return $content;
}
/**
* Did last request resulted in error?
*/
function wasError() {
return PEAR::isError($this->response);
}
/**
* Disconnect this instance
*/
function disconnect() {
$this->client->disconnect();
}
}
?>
+25
View File
@@ -0,0 +1,25 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('vtlib/Vtiger/PackageUpdate.php');
/**
* Package Manager class for vtiger Modules.
* @package vtlib
*/
class Vtiger_Package extends Vtiger_PackageUpdate {
/**
* Constructor
*/
function Vtiger_Package() {
parent::__construct();
}
}
?>
@@ -0,0 +1,606 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Module.php');
include_once('vtlib/Vtiger/Menu.php');
include_once('vtlib/Vtiger/Event.php');
include_once('vtlib/Vtiger/Zip.php');
/**
* Provides API to package vtiger CRM module and associated files.
* @package vtlib
*/
class Vtiger_PackageExport {
var $_export_tmpdir = 'test/vtlib';
var $_export_modulexml_filename = null;
var $_export_modulexml_file = null;
/**
* Constructor
*/
function Vtiger_PackageExport() {
if(is_dir($this->_export_tmpdir) === FALSE) {
mkdir($this->_export_tmpdir);
}
}
/** Output Handlers */
/** @access private */
function openNode($node,$delimiter="\n") {
$this->__write("<$node>$delimiter");
}
/** @access private */
function closeNode($node,$delimiter="\n") {
$this->__write("</$node>$delimiter");
}
/** @access private */
function outputNode($value, $node='') {
if($node != '') $this->openNode($node,'');
$this->__write($value);
if($node != '') $this->closeNode($node);
}
/** @access private */
function __write($value) {
fwrite($this->_export_modulexml_file, $value);
}
/**
* Set the module.xml file path for this export and
* return its temporary path.
* @access private
*/
function __getManifestFilePath() {
if(empty($this->_export_modulexml_filename)) {
// Set the module xml filename to be written for exporting.
$this->_export_modulexml_filename = "manifest-".time().".xml";
}
return "$this->_export_tmpdir/$this->_export_modulexml_filename";
}
/**
* Initialize Export
* @access private
*/
function __initExport($module, $moduleInstance) {
if($moduleInstance->isentitytype) {
// We will be including the file, so do a security check.
Vtiger_Utils::checkFileAccess("modules/$module/$module.php");
}
$this->_export_modulexml_file = fopen($this->__getManifestFilePath(), 'w');
$this->__write("<?xml version='1.0'?>\n");
}
/**
* Post export work.
* @access private
*/
function __finishExport() {
if(!empty($this->_export_modulexml_file)) {
fclose($this->_export_modulexml_file);
$this->_export_modulexml_file = null;
}
}
/**
* Clean up the temporary files created.
* @access private
*/
function __cleanupExport() {
if(!empty($this->_export_modulexml_filename)) {
unlink($this->__getManifestFilePath());
}
}
/**
* Export Module as a zip file.
* @param Vtiger_Module Instance of module
* @param Path Output directory path
* @param String Zipfilename to use
* @param Boolean True for sending the output as download
*/
function export($moduleInstance, $todir='', $zipfilename='', $directDownload=false) {
$module = $moduleInstance->name;
$this->__initExport($module, $moduleInstance);
// Call module export function
$this->export_Module($moduleInstance);
$this->__finishExport();
// Export as Zip
if($zipfilename == '') $zipfilename = "$module-" . date('YmdHis') . ".zip";
$zipfilename = "$this->_export_tmpdir/$zipfilename";
$zip = new Vtiger_Zip($zipfilename);
// Add manifest file
$zip->addFile($this->__getManifestFilePath(), "manifest.xml");
// Copy module directory
$zip->copyDirectoryFromDisk("modules/$module");
// Copy templates directory of the module (if any)
if(is_dir("Smarty/templates/modules/$module"))
$zip->copyDirectoryFromDisk("Smarty/templates/modules/$module", "templates");
// Copy cron files of the module (if any)
if(is_dir("cron/modules/$module"))
$zip->copyDirectoryFromDisk("cron/modules/$module", "cron");
$zip->save();
if($directDownload) {
$zip->forceDownload($zipfilename);
unlink($zipfilename);
}
$this->__cleanupExport();
}
/**
* Export vtiger dependencies
* @access private
*/
function export_Dependencies() {
global $vtiger_current_version;
$this->openNode('dependencies');
$this->outputNode($vtiger_current_version, 'vtiger_version');
$this->closeNode('dependencies');
}
/**
* Export Module Handler
* @access private
*/
function export_Module($moduleInstance) {
global $adb;
$moduleid = $moduleInstance->id;
$sqlresult = $adb->query("SELECT * FROM vtiger_parenttabrel WHERE tabid = $moduleid");
$parenttabid = $adb->query_result($sqlresult, 0, 'parenttabid');
$menu = Vtiger_Menu::getInstance($parenttabid);
$parent_name = $menu->label;
$sqlresult = $adb->query("SELECT * FROM vtiger_tab WHERE tabid = $moduleid");
$tabresultrow = $adb->fetch_array($sqlresult);
$tabname = $tabresultrow['name'];
$tablabel= $tabresultrow['tablabel'];
$tabversion = isset($tabresultrow['version'])? $tabresultrow['version'] : false;
$this->openNode('module');
$this->outputNode(date('Y-m-d H:i:s'),'exporttime');
$this->outputNode($tabname, 'name');
$this->outputNode($tablabel, 'label');
$this->outputNode($parent_name, 'parent');
if(!$moduleInstance->isentitytype) {
$this->outputNode('extension', 'type');
}
if($tabversion) {
$this->outputNode($tabversion, 'version');
}
// Export dependency information
$this->export_Dependencies();
// Export module tables
$this->export_Tables($moduleInstance);
// Export module blocks
$this->export_Blocks($moduleInstance);
// Export module filters
$this->export_CustomViews($moduleInstance);
// Export Sharing Access
$this->export_SharingAccess($moduleInstance);
// Export Events
$this->export_Events($moduleInstance);
// Export Actions
$this->export_Actions($moduleInstance);
// Export Related Lists
$this->export_RelatedLists($moduleInstance);
// Export Custom Links
$this->export_CustomLinks($moduleInstance);
$this->closeNode('module');
}
/**
* Export module base and related tables
* @access private
*/
function export_Tables($moduleInstance) {
$_exportedTables = Array();
$modulename = $moduleInstance->name;
$this->openNode('tables');
if($moduleInstance->isentitytype) {
$focus = CRMEntity::getInstance($modulename);
// Setup required module variables which is need for vtlib API's
vtlib_setup_modulevars($modulename, $focus);
$tables = Array ($focus->table_name);
if(!empty($focus->groupTable)) $tables[] = $focus->groupTable[0];
if(!empty($focus->customFieldTable)) $tables[] = $focus->customFieldTable[0];
foreach($tables as $table) {
$this->openNode('table');
$this->outputNode($table, 'name');
$this->outputNode('<![CDATA['.Vtiger_Utils::CreateTableSql($table).']]>', 'sql');
$this->closeNode('table');
$_exportedTables[] = $table;
}
}
// Now export table information recorded in schema file
if(file_exists("modules/$modulename/schema.xml")) {
$schema = simplexml_load_file("modules/$modulename/schema.xml");
if(!empty($schema->tables) && !empty($schema->tables->table)) {
foreach($schema->tables->table as $tablenode) {
$table = trim($tablenode->name);
if(!in_array($table,$_exportedTables)) {
$this->openNode('table');
$this->outputNode($table, 'name');
$this->outputNode('<![CDATA['.Vtiger_Utils::CreateTableSql($table).']]>', 'sql');
$this->closeNode('table');
$_exportedTables[] = $table;
}
}
}
}
$this->closeNode('tables');
}
/**
* Export module blocks with its related fields
* @access private
*/
function export_Blocks($moduleInstance) {
global $adb;
$sqlresult = $adb->pquery("SELECT * FROM vtiger_blocks WHERE tabid = ?", Array($moduleInstance->id));
$resultrows= $adb->num_rows($sqlresult);
if(empty($resultrows)) return;
$this->openNode('blocks');
for($index = 0; $index < $resultrows; ++$index) {
$blockid = $adb->query_result($sqlresult, $index, 'blockid');
$blocklabel = $adb->query_result($sqlresult, $index, 'blocklabel');
$this->openNode('block');
$this->outputNode($blocklabel, 'label');
// Export fields associated with the block
$this->export_Fields($moduleInstance, $blockid);
$this->closeNode('block');
}
$this->closeNode('blocks');
}
/**
* Export fields related to a module block
* @access private
*/
function export_Fields($moduleInstance, $blockid) {
global $adb;
$fieldresult = $adb->pquery("SELECT * FROM vtiger_field WHERE tabid=? AND block=?", Array($moduleInstance->id, $blockid));
$fieldcount = $adb->num_rows($fieldresult);
if(empty($fieldcount)) return;
$entityresult = $adb->pquery("SELECT * FROM vtiger_entityname WHERE tabid=?", Array($moduleInstance->id));
$entity_fieldname = $adb->query_result($entityresult, 0, 'fieldname');
$this->openNode('fields');
for($index = 0; $index < $fieldcount; ++$index) {
$this->openNode('field');
$fieldresultrow = $adb->fetch_row($fieldresult);
$fieldname = $fieldresultrow['fieldname'];
$uitype = $fieldresultrow['uitype'];
$fieldid = $fieldresultrow['fieldid'];
$this->outputNode($fieldname, 'fieldname');
$this->outputNode($uitype, 'uitype');
$this->outputNode($fieldresultrow['columnname'],'columnname');
$this->outputNode($fieldresultrow['tablename'], 'tablename');
$this->outputNode($fieldresultrow['generatedtype'], 'generatedtype');
$this->outputNode($fieldresultrow['fieldlabel'], 'fieldlabel');
$this->outputNode($fieldresultrow['readonly'], 'readonly');
$this->outputNode($fieldresultrow['presence'], 'presence');
$this->outputNode($fieldresultrow['selected'], 'selected');
$this->outputNode($fieldresultrow['sequence'], 'sequence');
$this->outputNode($fieldresultrow['maximumlength'], 'maximumlength');
$this->outputNode($fieldresultrow['typeofdata'], 'typeofdata');
$this->outputNode($fieldresultrow['quickcreate'], 'quickcreate');
$this->outputNode($fieldresultrow['quickcreatesequence'], 'quickcreatesequence');
$this->outputNode($fieldresultrow['displaytype'], 'displaytype');
$this->outputNode($fieldresultrow['info_type'], 'info_type');
$this->outputNode('<![CDATA['.$fieldresultrow['helpinfo'].']]>', 'helpinfo');
if(isset($fieldresultrow['masseditable'])) {
$this->outputNode($fieldresultrow['masseditable'], 'masseditable');
}
// Export Entity Identifier Information
if($fieldname == $entity_fieldname) {
$this->openNode('entityidentifier');
$this->outputNode($adb->query_result($entityresult, 0, 'entityidfield'), 'entityidfield');
$this->outputNode($adb->query_result($entityresult, 0, 'entityidcolumn'), 'entityidcolumn');
$this->closeNode('entityidentifier');
}
// Export picklist values for picklist fields
if($uitype == '15' || $uitype == '16' || $uitype == '111' || $uitype == '33' || $uitype == '55') {
if($uitype == '16') {
$picklistvalues = vtlib_getPicklistValues($fieldname);
} else {
$picklistvalues = vtlib_getPicklistValues_AccessibleToAll($fieldname);
}
$this->openNode('picklistvalues');
foreach($picklistvalues as $picklistvalue) {
$this->outputNode($picklistvalue, 'picklistvalue');
}
$this->closeNode('picklistvalues');
}
// Export field to module relations
if($uitype == '10') {
$relatedmodres = $adb->pquery("SELECT * FROM vtiger_fieldmodulerel WHERE fieldid=?", Array($fieldid));
$relatedmodcount = $adb->num_rows($relatedmodres);
if($relatedmodcount) {
$this->openNode('relatedmodules');
for($relmodidx = 0; $relmodidx < $relatedmodcount; ++$relmodidx) {
$this->outputNode($adb->query_result($relatedmodres, $relmodidx, 'relmodule'), 'relatedmodule');
}
$this->closeNode('relatedmodules');
}
}
$this->closeNode('field');
}
$this->closeNode('fields');
}
/**
* Export Custom views of the module
* @access private
*/
function export_CustomViews($moduleInstance) {
global $adb;
$customviewres = $adb->pquery("SELECT * FROM vtiger_customview WHERE entitytype = ?", Array($moduleInstance->name));
$customviewcount=$adb->num_rows($customviewres);
if(empty($customviewcount)) return;
$this->openNode('customviews');
for($cvindex = 0; $cvindex < $customviewcount; ++$cvindex) {
$cvid = $adb->query_result($customviewres, $cvindex, 'cvid');
$cvcolumnres = $adb->query("SELECT * FROM vtiger_cvcolumnlist WHERE cvid=$cvid");
$cvcolumncount=$adb->num_rows($cvcolumnres);
$this->openNode('customview');
$setdefault = $adb->query_result($customviewres, $cvindex, 'setdefault');
$setdefault = ($setdefault == 1)? 'true' : 'false';
$setmetrics = $adb->query_result($customviewres, $cvindex, 'setmetrics');
$setmetrics = ($setmetrics == 1)? 'true' : 'false';
$this->outputNode($adb->query_result($customviewres, $cvindex, 'viewname'), 'viewname');
$this->outputNode($setdefault, 'setdefault');
$this->outputNode($setmetrics, 'setmetrics');
$this->openNode('fields');
for($index = 0; $index < $cvcolumncount; ++$index) {
$cvcolumnindex = $adb->query_result($cvcolumnres, $index, 'columnindex');
$cvcolumnname = $adb->query_result($cvcolumnres, $index, 'columnname');
$cvcolumnnames= explode(':', $cvcolumnname);
$cvfieldname = $cvcolumnnames[2];
$this->openNode('field');
$this->outputNode($cvfieldname, 'fieldname');
$this->outputNode($cvcolumnindex,'columnindex');
$cvcolumnruleres = $adb->pquery("SELECT * FROM vtiger_cvadvfilter WHERE cvid=? AND columnname=?",
Array($cvid, $cvcolumnname));
$cvcolumnrulecount = $adb->num_rows($cvcolumnruleres);
if($cvcolumnrulecount) {
$this->openNode('rules');
for($rindex = 0; $rindex < $cvcolumnrulecount; ++$rindex) {
$cvcolumnruleindex = $adb->query_result($cvcolumnruleres, $rindex, 'columnindex');
$cvcolumnrulecomp = $adb->query_result($cvcolumnruleres, $rindex, 'comparator');
$cvcolumnrulevalue = $adb->query_result($cvcolumnruleres, $rindex, 'value');
$cvcolumnrulecomp = Vtiger_Filter::translateComparator($cvcolumnrulecomp, true);
$this->openNode('rule');
$this->outputNode($cvcolumnruleindex, 'columnindex');
$this->outputNode($cvcolumnrulecomp, 'comparator');
$this->outputNode($cvcolumnrulevalue, 'value');
$this->closeNode('rule');
}
$this->closeNode('rules');
}
$this->closeNode('field');
}
$this->closeNode('fields');
$this->closeNode('customview');
}
$this->closeNode('customviews');
}
/**
* Export Sharing Access of the module
* @access private
*/
function export_SharingAccess($moduleInstance) {
global $adb;
$deforgshare = $adb->pquery("SELECT * FROM vtiger_def_org_share WHERE tabid=?", Array($moduleInstance->id));
$deforgshareCount = $adb->num_rows($deforgshare);
if(empty($deforgshareCount)) return;
$this->openNode('sharingaccess');
if($deforgshareCount) {
for($index = 0; $index < $deforgshareCount; ++$index) {
$permission = $adb->query_result($deforgshare, $index, 'permission');
$permissiontext = '';
if($permission == '0') $permissiontext = 'public_readonly';
if($permission == '1') $permissiontext = 'public_readwrite';
if($permission == '2') $permissiontext = 'public_readwritedelete';
if($permission == '3') $permissiontext = 'private';
$this->outputNode($permissiontext, 'default');
}
}
$this->closeNode('sharingaccess');
}
/**
* Export Events of the module
* @access private
*/
function export_Events($moduleInstance) {
$events = Vtiger_Event::getAll($moduleInstance);
if(!$events) return;
$this->openNode('events');
foreach($events as $event) {
$this->openNode('event');
$this->outputNode($event->eventname, 'eventname');
$this->outputNode('<![CDATA['.$event->classname.']]>', 'classname');
$this->outputNode('<![CDATA['.$event->filename.']]>', 'filename');
$this->outputNode('<![CDATA['.$event->condition.']]>', 'condition');
$this->closeNode('event');
}
$this->closeNode('events');
}
/**
* Export actions (tools) associated with module.
* TODO: Need to pickup values based on status for all user (profile)
* @access private
*/
function export_Actions($moduleInstance) {
if(!$moduleInstance->isentitytype) return;
global $adb;
$result = $adb->pquery('SELECT distinct(actionname) FROM vtiger_profile2utility, vtiger_actionmapping
WHERE vtiger_profile2utility.activityid=vtiger_actionmapping.actionid and tabid=?', Array($moduleInstance->id));
if($adb->num_rows($result)) {
$this->openNode('actions');
while($resultrow = $adb->fetch_array($result)) {
$this->openNode('action');
$this->outputNode('<![CDATA['. $resultrow['actionname'] .']]>', 'name');
$this->outputNode('enabled', 'status');
$this->closeNode('action');
}
$this->closeNode('actions');
}
}
/**
* Export related lists associated with module.
* @access private
*/
function export_RelatedLists($moduleInstance) {
if(!$moduleInstance->isentitytype) return;
global $adb;
$result = $adb->pquery("SELECT * FROM vtiger_relatedlists WHERE tabid = ?", Array($moduleInstance->id));
if($adb->num_rows($result)) {
$this->openNode('relatedlists');
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$row = $adb->fetch_array($result);
$this->openNode('relatedlist');
$this->outputNode($row['name'], 'function');
$this->outputNode($row['label'], 'label');
$this->outputNode($row['sequence'], 'sequence');
$this->outputNode($row['presence'], 'presence');
$action_text = $row['actions'];
if(!empty($action_text)) {
$this->openNode('actions');
$actions = explode(',', $action_text);
foreach($actions as $action) {
$this->outputNode($action, 'action');
}
$this->closeNode('actions');
}
$relModuleInstance = Vtiger_Module::getInstance($row['related_tabid']);
$this->outputNode($relModuleInstance->name, 'relatedmodule');
$this->closeNode('relatedlist');
}
$this->closeNode('relatedlists');
}
}
/**
* Export custom links of the module.
* @access private
*/
function export_CustomLinks($moduleInstance) {
$customlinks = $moduleInstance->getLinks();
if(!empty($customlinks)) {
$this->openNode('customlinks');
foreach($customlinks as $customlink) {
$this->openNode('customlink');
$this->outputNode($customlink->linktype, 'linktype');
$this->outputNode($customlink->linklabel, 'linklabel');
$this->outputNode("<![CDATA[$customlink->linkurl]]>", 'linkurl');
$this->outputNode("<![CDATA[$customlink->linkicon]]>", 'linkicon');
$this->outputNode($customlink->sequence, 'sequence');
$this->closeNode('customlink');
}
$this->closeNode('customlinks');
}
}
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
}
?>
@@ -0,0 +1,622 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/PackageExport.php');
include_once('vtlib/Vtiger/Unzip.php');
include_once('vtlib/Vtiger/Module.php');
include_once('vtlib/Vtiger/Event.php');
/**
* Provides API to import module into vtiger CRM
* @package vtlib
*/
class Vtiger_PackageImport extends Vtiger_PackageExport {
/**
* Module Meta XML File (Parsed)
* @access private
*/
var $_modulexml;
/**
* Module Fields mapped by [modulename][fieldname] which
* will be used to create customviews.
* @access private
*/
var $_modulefields_cache = Array();
/**
* License of the package.
* @access private
*/
var $_licensetext = false;
/**
* Constructor
*/
function Vtiger_PackageImport() {
parent::__construct();
}
/**
* Parse the manifest file
* @access private
*/
function __parseManifestFile($unzip) {
$manifestfile = $this->__getManifestFilePath();
$unzip->unzip('manifest.xml', $manifestfile);
$this->_modulexml = simplexml_load_file($manifestfile);
unlink($manifestfile);
}
/**
* Get type of package (as specified in manifest)
*/
function type() {
if(!empty($this->_modulexml) && !empty($this->_modulexml->type)) {
return $this->_modulexml->type;
}
return false;
}
/**
* XPath evaluation on the root module node.
* @param String Path expression
*/
function xpath($path) {
return $this->_modulexml->xpath($path);
}
/**
* Get the value of matching path (instead of complete xpath result)
* @param String Path expression for which value is required
*/
function xpath_value($path) {
$xpathres = $this->xpath($path);
foreach($xpathres as $pathkey=>$pathvalue) {
if($pathkey == $path) return $pathvalue;
}
return false;
}
/**
* Are we trying to import language package?
*/
function isLanguageType() {
$packagetype = $this->type();
if($packagetype) {
$lcasetype = strtolower($packagetype);
if($lcasetype == 'language') return true;
}
return false;
}
/**
* Get the license of this package
* NOTE: checkzip should have been called earlier.
*/
function getLicense() {
return $this->_licensetext;
}
/**
* Check if zipfile is a valid package
* @access private
*/
function checkZip($zipfile) {
$unzip = new Vtiger_Unzip($zipfile);
$filelist = $unzip->getList();
$manifestxml_found = false;
$languagefile_found = false;
$vtigerversion_found = false;
$modulename = null;
$language_modulename = null;
foreach($filelist as $filename=>$fileinfo) {
$matches = Array();
preg_match('/manifest.xml/', $filename, $matches);
if(count($matches)) {
$manifestxml_found = true;
$this->__parseManifestFile($unzip);
$modulename = $this->_modulexml->name;
// Do we need to check the zip further?
if($this->isLanguageType()) {
$languagefile_found = true; // No need to search for module language file.
break;
} else {
continue;
}
}
// Check for language file.
preg_match("/modules\/([^\/]+)\/language\/en_us.lang.php/", $filename, $matches);
if(count($matches)) { $language_modulename = $matches[1]; continue; }
}
// Verify module language file.
if(!empty($language_modulename) && $language_modulename == $modulename) {
$languagefile_found = true;
}
if(!empty($this->_modulexml) &&
!empty($this->_modulexml->dependencies) &&
!empty($this->_modulexml->dependencies->vtiger_version)) {
$vtigerversion_found = true;
}
$validzip = false;
if($manifestxml_found && $languagefile_found && $vtigerversion_found)
$validzip = true;
if($validzip) {
if(!empty($this->_modulexml->license)) {
if(!empty($this->_modulexml->license->inline)) {
$this->_licensetext = $this->_modulexml->license->inline;
} else if(!empty($this->_modulexml->license->file)) {
$licensefile = $this->_modulexml->license->file;
$licensefile = "$licensefile";
if(!empty($filelist[$licensefile])) {
$this->_licensetext = $unzip->unzip($licensefile);
} else {
$this->_licensetext = "Missing $licensefile!";
}
}
}
}
if($unzip) $unzip->close();
return $validzip;
}
/**
* Get module name packaged in the zip file
* @access private
*/
function getModuleNameFromZip($zipfile) {
if(!$this->checkZip($zipfile)) return null;
return $this->_modulexml->name;
}
/**
* Cache the field instance for re-use
* @access private
*/
function __AddModuleFieldToCache($moduleInstance, $fieldname, $fieldInstance) {
$this->_modulefields_cache["$moduleInstance->name"]["$fieldname"] = $fieldInstance;
}
/**
* Get field instance from cache
* @access private
*/
function __GetModuleFieldFromCache($moduleInstance, $fieldname) {
return $this->_modulefields_cache["$moduleInstance->name"]["$fieldname"];
}
/**
* Initialize Import
* @access private
*/
function initImport($zipfile, $overwrite) {
$module = $this->getModuleNameFromZip($zipfile);
if($module != null) {
$unzip = new Vtiger_Unzip($zipfile, $overwrite);
// Unzip selectively
$unzip->unzipAllEx( ".",
Array(
// Include only file/folders that need to be extracted
'include' => Array('templates', "modules/$module", 'cron'),
//'exclude' => Array('manifest.xml')
// NOTE: If excludes is not given then by those not mentioned in include are ignored.
),
// What files needs to be renamed?
Array(
// Templates folder
'templates' => "Smarty/templates/modules/$module",
// Cron folder
'cron' => "cron/modules/$module"
)
);
// If data is not yet available
if(empty($this->_modulexml)) {
$this->__parseManifestFile($unzip);
}
if($unzip) $unzip->close();
}
return $module;
}
/**
* Get dependent version
* @access private
*/
function getDependentVtigerVersion() {
return $this->_modulexml->dependencies->vtiger_version;
}
/**
* Get package version
* @access private
*/
function getVersion() {
return $this->_modulexml->version;
}
/**
* Import Module from zip file
* @param String Zip file name
* @param Boolean True for overwriting existing module
*
* @todo overwrite feature is not functionally currently.
*/
function import($zipfile, $overwrite=false) {
$module = $this->initImport($zipfile, $overwrite);
// Call module import function
$this->import_Module();
}
/**
* Import Module
* @access private
*/
function import_Module() {
$tabname = $this->_modulexml->name;
$tablabel= $this->_modulexml->label;
$parenttab=(string)$this->_modulexml->parent;
$tabversion=$this->_modulexml->version;
$isextension= false;
if(!empty($this->_modulexml->type)) {
$type = strtolower($this->_modulexml->type);
if($type == 'extension' || $type == 'language')
$isextension = true;
}
$moduleInstance = new Vtiger_Module();
$moduleInstance->name = $tabname;
$moduleInstance->label= $tablabel;
$moduleInstance->isentitytype = ($isextension != true);
$moduleInstance->version = (!$tabversion)? 0 : $tabversion;
$moduleInstance->save();
if(!empty($parenttab)) {
$menuInstance = Vtiger_Menu::getInstance($parenttab);
$menuInstance->addModule($moduleInstance);
}
$this->import_Tables($this->_modulexml);
$this->import_Blocks($this->_modulexml, $moduleInstance);
$this->import_CustomViews($this->_modulexml, $moduleInstance);
$this->import_SharingAccess($this->_modulexml, $moduleInstance);
$this->import_Events($this->_modulexml, $moduleInstance);
$this->import_Actions($this->_modulexml, $moduleInstance);
$this->import_RelatedLists($this->_modulexml, $moduleInstance);
$this->import_CustomLinks($this->_modulexml, $moduleInstance);
Vtiger_Module::fireEvent($moduleInstance->name,
Vtiger_Module::EVENT_MODULE_POSTINSTALL);
$moduleInstance->initWebservice();
}
/**
* Import Tables of the module
* @access private
*/
function import_Tables($modulenode) {
if(empty($modulenode->tables) || empty($modulenode->tables->table)) return;
/**
* Record the changes in schema file
*/
$schemafile = fopen("modules/$modulenode->name/schema.xml", 'w');
if($schemafile) {
fwrite($schemafile, "<?xml version='1.0'?>\n");
fwrite($schemafile, "<schema>\n");
fwrite($schemafile, "\t<tables>\n");
}
// Import the table via queries
foreach($modulenode->tables->table as $tablenode) {
$tablename = $tablenode->name;
$tablesql = "$tablenode->sql"; // Convert to string format
// Save the information in the schema file.
fwrite($schemafile, "\t\t<table>\n");
fwrite($schemafile, "\t\t\t<name>$tablename</name>\n");
fwrite($schemafile, "\t\t\t<sql><![CDATA[$tablesql]]></sql>\n");
fwrite($schemafile, "\t\t</table>\n");
// Avoid executing SQL that will DELETE or DROP table data
if(Vtiger_Utils::IsCreateSql($tablesql)) {
if(!Vtiger_Utils::checkTable($tablename)) {
self::log("SQL: $tablesql ... ", false);
Vtiger_Utils::ExecuteQuery($tablesql);
self::log("DONE");
}
} else {
if(Vtiger_Utils::IsDestructiveSql($tablesql)) {
self::log("SQL: $tablesql ... SKIPPED");
} else {
self::log("SQL: $tablesql ... ", false);
Vtiger_Utils::ExecuteQuery($tablesql);
self::log("DONE");
}
}
}
if($schemafile) {
fwrite($schemafile, "\t</tables>\n");
fwrite($schemafile, "</schema>\n");
fclose($schemafile);
}
}
/**
* Import Blocks of the module
* @access private
*/
function import_Blocks($modulenode, $moduleInstance) {
if(empty($modulenode->blocks) || empty($modulenode->blocks->block)) return;
foreach($modulenode->blocks->block as $blocknode) {
$blockInstance = $this->import_Block($modulenode, $moduleInstance, $blocknode);
$this->import_Fields($blocknode, $blockInstance, $moduleInstance);
}
}
/**
* Import Block of the module
* @access private
*/
function import_Block($modulenode, $moduleInstance, $blocknode) {
$blocklabel = $blocknode->label;
$blockInstance = new Vtiger_Block();
$blockInstance->label = $blocklabel;
$moduleInstance->addBlock($blockInstance);
return $blockInstance;
}
/**
* Import Fields of the module
* @access private
*/
function import_Fields($blocknode, $blockInstance, $moduleInstance) {
if(empty($blocknode->fields) || empty($blocknode->fields->field)) return;
foreach($blocknode->fields->field as $fieldnode) {
$fieldInstance = $this->import_Field($blocknode, $blockInstance, $moduleInstance, $fieldnode);
}
}
/**
* Import Field of the module
* @access private
*/
function import_Field($blocknode, $blockInstance, $moduleInstance, $fieldnode) {
$fieldInstance = new Vtiger_Field();
$fieldInstance->name = $fieldnode->fieldname;
$fieldInstance->label = $fieldnode->fieldlabel;
$fieldInstance->table = $fieldnode->tablename;
$fieldInstance->column = $fieldnode->columnname;
$fieldInstance->uitype = $fieldnode->uitype;
$fieldInstance->generatedtype= $fieldnode->generatedtype;
$fieldInstance->readonly = $fieldnode->readonly;
$fieldInstance->presence = $fieldnode->presence;
$fieldInstance->selected = $fieldnode->selected;
$fieldInstance->maximumlength= $fieldnode->maximumlength;
$fieldInstance->sequence = $fieldnode->sequence;
$fieldInstance->quickcreate = $fieldnode->quickcreate;
$fieldInstance->quicksequence= $fieldnode->quickcreatesequence;
$fieldInstance->typeofdata = $fieldnode->typeofdata;
$fieldInstance->displaytype = $fieldnode->displaytype;
$fieldInstance->info_type = $fieldnode->info_type;
if(!empty($fieldnode->helpinfo))
$fieldInstance->helpinfo = $fieldnode->helpinfo;
if(isset($fieldnode->masseditable))
$fieldInstance->masseditable = $fieldnode->masseditable;
if(isset($fieldnode->columntype) && !empty($fieldnode->columntype))
$fieldInstance->columntype = $fieldnode->columntype;
$blockInstance->addField($fieldInstance);
// Set the field as entity identifier if marked.
if(!empty($fieldnode->entityidentifier)) {
$moduleInstance->entityidfield = $fieldnode->entityidentifier->entityidfield;
$moduleInstance->entityidcolumn= $fieldnode->entityidentifier->entityidcolumn;
$moduleInstance->setEntityIdentifier($fieldInstance);
}
// Check picklist values associated with field if any.
if(!empty($fieldnode->picklistvalues) && !empty($fieldnode->picklistvalues->picklistvalue)) {
$picklistvalues = Array();
foreach($fieldnode->picklistvalues->picklistvalue as $picklistvaluenode) {
$picklistvalues[] = $picklistvaluenode;
}
$fieldInstance->setPicklistValues( $picklistvalues );
}
// Check related modules associated with this field
if(!empty($fieldnode->relatedmodules) && !empty($fieldnode->relatedmodules->relatedmodule)) {
$relatedmodules = Array();
foreach($fieldnode->relatedmodules->relatedmodule as $relatedmodulenode) {
$relatedmodules[] = $relatedmodulenode;
}
$fieldInstance->setRelatedModules($relatedmodules);
}
$this->__AddModuleFieldToCache($moduleInstance, $fieldnode->fieldname, $fieldInstance);
return $fieldInstance;
}
/**
* Import Custom views of the module
* @access private
*/
function import_CustomViews($modulenode, $moduleInstance) {
if(empty($modulenode->customviews) || empty($modulenode->customviews->customview)) return;
foreach($modulenode->customviews->customview as $customviewnode) {
$filterInstance = $this->import_CustomView($modulenode, $moduleInstance, $customviewnode);
}
}
/**
* Import Custom View of the module
* @access private
*/
function import_CustomView($modulenode, $moduleInstance, $customviewnode) {
$viewname = $customviewnode->viewname;
$setdefault=$customviewnode->setdefault;
$setmetrics=$customviewnode->setmetrics;
$filterInstance = new Vtiger_Filter();
$filterInstance->name = $viewname;
$filterInstance->isdefault = $setdefault;
$filterInstance->inmetrics = $setmetrics;
$moduleInstance->addFilter($filterInstance);
foreach($customviewnode->fields->field as $fieldnode) {
$fieldInstance = $this->__GetModuleFieldFromCache($moduleInstance, $fieldnode->fieldname);
$filterInstance->addField($fieldInstance, $fieldnode->columnindex);
if(!empty($fieldnode->rules->rule)) {
foreach($fieldnode->rules->rule as $rulenode) {
$filterInstance->addRule($fieldInstance, $rulenode->comparator, $rulenode->value, $rulenode->columnindex);
}
}
}
}
/**
* Import Sharing Access of the module
* @access private
*/
function import_SharingAccess($modulenode, $moduleInstance) {
if(empty($modulenode->sharingaccess)) return;
if(!empty($modulenode->sharingaccess->default)) {
foreach($modulenode->sharingaccess->default as $defaultnode) {
$moduleInstance->setDefaultSharing($defaultnode);
}
}
}
/**
* Import Events of the module
* @access private
*/
function import_Events($modulenode, $moduleInstance) {
if(empty($modulenode->events) || empty($modulenode->events->event)) return;
if(Vtiger_Event::hasSupport()) {
foreach($modulenode->events->event as $eventnode) {
$this->import_Event($modulenode, $moduleInstance, $eventnode);
}
}
}
/**
* Import Event of the module
* @access private
*/
function import_Event($modulenode, $moduleInstance, $eventnode) {
$event_condition = '';
if(!empty($eventnode->condition)) $event_condition = "$eventnode->condition";
Vtiger_Event::register($moduleInstance,
(string)$eventnode->eventname, (string)$eventnode->classname,
(string)$eventnode->filename, (string)$event_condition
);
}
/**
* Import actions of the module
* @access private
*/
function import_Actions($modulenode, $moduleInstance) {
if(empty($modulenode->actions) || empty($modulenode->actions->action)) return;
foreach($modulenode->actions->action as $actionnode) {
$this->import_Action($modulenode, $moduleInstance, $actionnode);
}
}
/**
* Import action of the module
* @access private
*/
function import_Action($modulenode, $moduleInstance, $actionnode) {
$actionstatus = $actionnode->status;
if($actionstatus == 'enabled')
$moduleInstance->enableTools($actionnode->name);
else
$moduleInstance->disableTools($actionnode->name);
}
/**
* Import related lists of the module
* @access private
*/
function import_RelatedLists($modulenode, $moduleInstance) {
if(empty($modulenode->relatedlists) || empty($modulenode->relatedlists->relatedlist)) return;
foreach($modulenode->relatedlists->relatedlist as $relatedlistnode) {
$relModuleInstance = $this->import_Relatedlist($modulenode, $moduleInstance, $relatedlistnode);
}
}
/**
* Import related list of the module.
* @access private
*/
function import_Relatedlist($modulenode, $moduleInstance, $relatedlistnode) {
$relModuleInstance = Vtiger_Module::getInstance($relatedlistnode->relatedmodule);
$label = $relatedlistnode->label;
$actions = false;
if(!empty($relatedlistnode->actions) && !empty($relatedlistnode->actions->action)) {
$actions = Array();
foreach($relatedlistnode->actions->action as $actionnode) {
$actions[] = "$actionnode";
}
}
if($relModuleInstance) {
$moduleInstance->setRelatedList($relModuleInstance, "$label", $actions, "$relatedlistnode->function");
}
return $relModuleInstance;
}
/**
* Import custom links of the module.
* @access private
*/
function import_CustomLinks($modulenode, $moduleInstance) {
if(empty($modulenode->customlinks) || empty($modulenode->customlinks->customlink)) return;
foreach($modulenode->customlinks->customlink as $customlinknode) {
$moduleInstance->addLink(
"$customlinknode->linktype",
"$customlinknode->linklabel",
"$customlinknode->linkurl",
"$customlinknode->linkicon",
"$customlinknode->sequence"
);
}
}
}
?>
@@ -0,0 +1,336 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/PackageImport.php');
/**
* Provides API to update module into vtiger CRM
* @package vtlib
*/
class Vtiger_PackageUpdate extends Vtiger_PackageImport {
var $_migrationinfo = false;
/**
* Constructor
*/
function Vtiger_PackageUpdate() {
parent::__construct();
}
/**
* Initialize Update
* @access private
*/
function initUpdate($moduleInstance, $zipfile, $overwrite) {
$module = $this->getModuleNameFromZip($zipfile);
if(!$moduleInstance || $moduleInstance->name != $module) {
self::log('Module name mismatch!');
return false;
}
if($module != null) {
$unzip = new Vtiger_Unzip($zipfile, $overwrite);
// Unzip selectively
$unzip->unzipAllEx( ".",
Array(
'include' => Array('templates', "modules/$module"), // We don't need manifest.xml
//'exclude' => Array('manifest.xml') // DEFAULT: excludes all not in include
),
// Templates folder to be renamed while copying
Array('templates' => "Smarty/templates/modules/$module"),
// Cron folder to be renamed while copying
Array('cron' => "cron/modules/$module")
);
// If data is not yet available
if(empty($this->_modulexml)) {
$this->__parseManifestFile($unzip);
}
if($unzip) $unzip->close();
}
return $module;
}
/**
* Update Module from zip file
* @param Vtiger_Module Instance of the module to update
* @param String Zip file name
* @param Boolean True for overwriting existing module
*/
function update($moduleInstance, $zipfile, $overwrite=true) {
$module = $this->initUpdate($moduleInstance, $zipfile, $overwrite);
if($module) {
// Call module update function
$this->update_Module($moduleInstance);
}
}
/**
* Update Module
* @access private
*/
function update_Module($moduleInstance) {
$tabname = $this->_modulexml->name;
$tablabel= $this->_modulexml->label;
$parenttab=$this->_modulexml->parent;
$tabversion=$this->_modulexml->version;
$isextension= false;
if(!empty($this->_modulexml->type)) {
$type = strtolower($this->_modulexml->type);
if($type == 'extension' || $type == 'language')
$isextension = true;
}
Vtiger_Module::fireEvent($moduleInstance->name,
Vtiger_Module::EVENT_MODULE_PREUPDATE);
// TODO Handle module property changes like menu, label etc...
/*if(!empty($parenttab) && $parenttab != '') {
$menuInstance = Vtiger_Menu::getInstance($parenttab);
$menuInstance->addModule($moduleInstance);
}*/
$this->handle_Migration($this->_modulexml, $moduleInstance);
$this->update_Tables($this->_modulexml);
$this->update_Blocks($this->_modulexml, $moduleInstance);
$this->update_CustomViews($this->_modulexml, $moduleInstance);
$this->update_SharingAccess($this->_modulexml, $moduleInstance);
$this->update_Events($this->_modulexml, $moduleInstance);
$this->update_Actions($this->_modulexml, $moduleInstance);
$this->update_RelatedLists($this->_modulexml, $moduleInstance);
$moduleInstance->__updateVersion($tabversion);
Vtiger_Module::fireEvent($moduleInstance->name,
Vtiger_Module::EVENT_MODULE_POSTUPDATE);
}
/**
* Parse migration information from manifest
* @access private
*/
function parse_Migration($modulenode) {
if(!$this->_migrations) {
$this->_migrations = Array();
if(!empty($modulenode->migrations) &&
!empty($modulenode->migrations->migration)) {
foreach($modulenode->migrations->migration as $migrationnode) {
$migrationattrs = $migrationnode->attributes();
$migrationversion = $migrationattrs['version'];
$this->_migrations["$migrationversion"] = $migrationnode;
}
}
// Sort the migration details based on version
if(count($this->_migrations) > 1) {
uksort($this->_migrations, 'version_compare');
}
}
}
/**
* Handle migration of the module
* @access private
*/
function handle_Migration($modulenode, $moduleInstance) {
// TODO Handle module migration SQL
$this->parse_Migration($modulenode);
$cur_version = $moduleInstance->version;
foreach($this->_migrations as $migversion=>$migrationnode) {
// Perform migration only for higher version than current
if(version_compare($cur_version, $migversion, '<')) {
self::log("Migrating to $migversion ... STARTED");
if(!empty($migrationnode->tables) && !empty($migrationnode->tables->table)) {
foreach($migrationnode->tables->table as $tablenode) {
$tablename = $tablenode->name;
$tablesql = "$tablenode->sql"; // Convert to string
// Skip SQL which are destructive
if(Vtiger_Utils::IsDestructiveSql($tablesql)) {
self::log("SQL: $tablesql ... SKIPPED");
} else {
// Supress any SQL query failures
self::log("SQL: $tablesql ... ", false);
Vtiger_Utils::ExecuteQuery($tablesql, true);
self::log("DONE");
}
}
}
self::log("Migrating to $migversion ... DONE");
}
}
}
/**
* Update Tables of the module
* @access private
*/
function update_Tables($modulenode) {
$this->import_Tables($modulenode);
}
/**
* Update Blocks of the module
* @access private
*/
function update_Blocks($modulenode, $moduleInstance) {
if(empty($modulenode->blocks) || empty($modulenode->blocks->block)) return;
foreach($modulenode->blocks->block as $blocknode) {
$blockInstance = Vtiger_Block::getInstance($blocknode->label, $moduleInstance);
if(!$blockInstance) {
$blockInstance = $this->import_Block($modulenode, $moduleInstance, $blocknode);
} else {
$this->update_Block($modulenode, $moduleInstance, $blocknode, $blockInstance);
}
$this->update_Fields($blocknode, $blockInstance, $moduleInstance);
}
}
/**
* Update Block of the module
* @access private
*/
function update_Block($modulenode, $moduleInstance, $blocknode, $blockInstance) {
// TODO Handle block property update
}
/**
* Update Fields of the module
* @access private
*/
function update_Fields($blocknode, $blockInstance, $moduleInstance) {
if(empty($blocknode->fields) || empty($blocknode->fields->field)) return;
foreach($blocknode->fields->field as $fieldnode) {
$fieldInstance = Vtiger_Field::getInstance($fieldnode->fieldname, $moduleInstance);
if(!$fieldInstance) {
$fieldInstance = $this->import_Field($blocknode, $blockInstance, $moduleInstance, $fieldnode);
} else {
$this->update_Field($blocknode, $blockInstance, $moduleInstance, $fieldnode, $fieldInstance);
}
$this->__AddModuleFieldToCache($moduleInstance, $fieldInstance->name, $fieldInstance);
}
}
/**
* Update Field of the module
* @access private
*/
function update_Field($blocknode, $blockInstance, $moduleInstance, $fieldnode, $fieldInstance) {
// TODO Handle field property update
if(!empty($fieldnode->helpinfo)) $fieldInstance->setHelpInfo($fieldnode->helpinfo);
if(!empty($fieldnode->masseditable)) $fieldInstance->setMassEditable($fieldnode->masseditable);
}
/**
* Import Custom views of the module
* @access private
*/
function update_CustomViews($modulenode, $moduleInstance) {
if(empty($modulenode->customviews) || empty($modulenode->customviews->customview)) return;
foreach($modulenode->customviews->customview as $customviewnode) {
$filterInstance = Vtiger_Filter::getInstance($customviewnode->viewname, $moduleInstance);
if(!$filterInstance) {
$filterInstance = $this->import_CustomView($modulenode, $moduleInstance, $customviewnode);
} else {
$this->update_CustomView($modulenode, $moduleInstance, $customviewnode, $filterInstance);
}
}
}
/**
* Update Custom View of the module
* @access private
*/
function update_CustomView($modulenode, $moduleInstance, $customviewnode, $filterInstance) {
// TODO Handle filter property update
}
/**
* Update Sharing Access of the module
* @access private
*/
function update_SharingAccess($modulenode, $moduleInstance) {
if(empty($modulenode->sharingaccess)) return;
// TODO Handle sharing access property update
}
/**
* Update Events of the module
* @access private
*/
function update_Events($modulenode, $moduleInstance) {
if(empty($modulenode->events) || empty($modulenode->events->event)) return;
if(Vtiger_Event::hasSupport()) {
foreach($modulenode->events->event as $eventnode) {
$this->update_Event($modulenode, $moduleInstance, $eventnode);
}
}
}
/**
* Update Event of the module
* @access private
*/
function update_Event($modulenode, $moduleInstance, $eventnode) {
//Vtiger_Event::register($moduleInstance, $eventnode->eventname, $eventnode->classname, $eventnode->filename);
// TODO Handle event property update
}
/**
* Update actions of the module
* @access private
*/
function update_Actions($modulenode, $moduleInstance) {
if(empty($modulenode->actions) || empty($modulenode->actions->action)) return;
foreach($modulenode->actions->action as $actionnode) {
$this->update_Action($modulenode, $moduleInstance, $actionnode);
}
}
/**
* Update action of the module
* @access private
*/
function update_Action($modulenode, $moduleInstance, $actionnode) {
// TODO Handle action property update
}
/**
* Update related lists of the module
* @access private
*/
function update_RelatedLists($modulenode, $moduleInstance) {
if(empty($modulenode->relatedlists) || empty($modulenode->relatedlists->relatedlist)) return;
foreach($modulenode->relatedlists->relatedlist as $relatedlistnode) {
$relModuleInstance = $this->import_Relatedlist($modulenode, $moduleInstance, $relatedlistnode);
}
}
/**
* Import related list of the module.
* @access private
*/
function update_Relatedlist($modulenode, $moduleInstance, $relatedlistnode) {
// TODO Handle related list update
}
}
?>
+120
View File
@@ -0,0 +1,120 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
/**
* Provides API to work with vtiger CRM Profile
* @package vtlib
*/
class Vtiger_Profile {
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delimit=true) {
Vtiger_Utils::Log($message, $delimit);
}
/**
* Initialize profile setup for Field
* @param Vtiger_Field Instance of the field
* @access private
*/
static function initForField($fieldInstance) {
global $adb;
// Allow field access to all
$adb->pquery("INSERT INTO vtiger_def_org_field (tabid, fieldid, visible, readonly) VALUES(?,?,?,?)",
Array($fieldInstance->getModuleId(), $fieldInstance->id, '0', '1'));
$profileids = self::getAllIds();
foreach($profileids as $profileid) {
$adb->pquery("INSERT INTO vtiger_profile2field (profileid, tabid, fieldid, visible, readonly) VALUES(?,?,?,?,?)",
Array($profileid, $fieldInstance->getModuleId(), $fieldInstance->id, '0', '1'));
}
}
/**
* Delete profile information related with field.
* @param Vtiger_Field Instance of the field
* @access private
*/
static function deleteForField($fieldInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_def_org_field WHERE fieldid=?", Array($fieldInstance->id));
$adb->pquery("DELETE FROM vtiger_profile2field WHERE fieldid=?", Array($fieldInstance->id));
}
/**
* Get all the existing profile ids
* @access private
*/
static function getAllIds() {
global $adb;
$profileids = Array();
$result = $adb->query('SELECT profileid FROM vtiger_profile');
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$profileids[] = $adb->query_result($result, $index, 'profileid');
}
return $profileids;
}
/**
* Initialize profile setup for the module
* @param Vtiger_Module Instance of module
* @access private
*/
static function initForModule($moduleInstance) {
global $adb;
$actionids = Array();
$result = $adb->query("SELECT actionid from vtiger_actionmapping WHERE actionname IN
('Save','EditView','Delete','index','DetailView')");
/*
* NOTE: Other actionname (actionid >= 5) is considered as utility (tools) for a profile.
* Gather all the actionid for associating to profile.
*/
for($index = 0; $index < $adb->num_rows($result); ++$index) {
$actionids[] = $adb->query_result($result, $index, 'actionid');
}
$profileids = self::getAllIds();
foreach($profileids as $profileid) {
$adb->pquery("INSERT INTO vtiger_profile2tab (profileid, tabid, permissions) VALUES (?,?,?)",
Array($profileid, $moduleInstance->id, 0));
if($moduleInstance->isentitytype) {
foreach($actionids as $actionid) {
$adb->pquery(
"INSERT INTO vtiger_profile2standardpermissions (profileid, tabid, Operation, permissions) VALUES(?,?,?,?)",
Array($profileid, $moduleInstance->id, $actionid, 0));
}
}
}
self::log("Initializing module permissions ... DONE");
}
/**
* Delete profile setup of the module
* @param Vtiger_Module Instance of module
* @access private
*/
static function deleteForModule($moduleInstance) {
global $adb;
$adb->pquery("DELETE FROM vtiger_profile2tab WHERE tabid=?", Array($moduleInstance->id));
$adb->pquery("DELETE FROM vtiger_profile2standardpermissions WHERE tabid=?", Array($moduleInstance->id));
}
}
?>
+122
View File
@@ -0,0 +1,122 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('vtlib/thirdparty/dUnzip2.inc.php');
/**
* Provides API to make working with zip file extractions easy
* @package vtlib
*/
class Vtiger_Unzip extends dUnzip2 {
/**
* Check existence of path in the given array
* @access private
*/
function __checkPathInArray($path, $pathArray) {
foreach($pathArray as $checkPath) {
if(strpos($path, $checkPath) === 0)
return true;
}
return false;
}
/**
* Check if the file path is directory
* @param String Zip file path
*/
function isdir($filepath) {
if(substr($filepath, -1, 1) == "/") return true;
return false;
}
/**
* Extended unzipAll function (look at base class)
* Allows you to rename while unzipping and handle exclusions.
* @access private
*/
Function unzipAllEx($targetDir=false, $includeExclude=false, $renamePaths=false, $ignoreFiles=false,
$baseDir="", $applyChmod=0777){
// We want to always maintain the structure
$maintainStructure = true;
if($targetDir === false)
$targetDir = dirname(__FILE__)."/";
if($renamePaths === false) $renamePaths = Array();
/*
* Setup includeExclude parameter
* FORMAT:
* Array(
* 'include'=> Array('zipfilepath1', 'zipfilepath2', ...),
* 'exclude'=> Array('zipfilepath3', ...)
* )
*
* DEFAULT: If include is specified only files under the specified path will be included.
* If exclude is specified folders or files will be excluded.
*/
if($includeExclude === false) $includeExclude = Array();
$lista = $this->getList();
if(sizeof($lista)) foreach($lista as $fileName=>$trash){
// Should the file be ignored?
if($includeExclude['include'] &&
!$this->__checkPathInArray($fileName, $includeExclude['include'])) {
// Do not include something not specified in include
continue;
}
if($includeExclude['exclude'] &&
$this->__checkPathInArray($fileName, $includeExclude['exclude'])) {
// Do not include something not specified in include
continue;
}
// END
$dirname = dirname($fileName);
// Rename the path with the matching one (as specified)
if(!empty($renamePaths)) {
foreach($renamePaths as $lookup => $replace) {
if(strpos($dirname, $lookup) === 0) {
$dirname = substr_replace($dirname, $replace, 0, strlen($lookup));
break;
}
}
}
// END
$outDN = "$targetDir/$dirname";
if(substr($dirname, 0, strlen($baseDir)) != $baseDir)
continue;
if(!is_dir($outDN) && $maintainStructure){
$str = "";
$folders = explode("/", $dirname);
foreach($folders as $folder){
$str = $str?"$str/$folder":$folder;
if(!is_dir("$targetDir/$str")){
$this->debugMsg(1, "Creating folder: $targetDir/$str");
mkdir("$targetDir/$str");
if($applyChmod)
chmod("$targetDir/$str", $applyChmod);
}
}
}
if(substr($fileName, -1, 1) == "/")
continue;
$this->unzip($fileName, "$targetDir/$dirname/".basename($fileName), $applyChmod);
}
}
}
?>
+227
View File
@@ -0,0 +1,227 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('config.inc.php');
include_once('include/utils/utils.php');
/**
* Provides few utility functions
* @package vtlib
*/
class Vtiger_Utils {
/**
* Check if given value is a number or not
* @param mixed String or Integer
*/
static function isNumber($value) {
return is_numeric($value)? intval($value) == $value : false;
}
/**
* Implode the prefix and suffix as string for given number of times
* @param String prefix to use
* @param Integer Number of times
* @param String suffix to use (optional)
*/
static function implodestr($prefix, $count, $suffix=false) {
$strvalue = '';
for($index = 0; $index < $count; ++$index) {
$strvalue .= $prefix;
if($suffix && $index != ($count-1)) {
$strvalue .= $suffix;
}
}
return $strvalue;
}
/**
* Function to check the file access is made within web root directory.
* @param String File path to check
* @param Boolean False to avoid die() if check fails
*/
static function checkFileAccess($filepath, $dieOnFail=true) {
global $root_directory;
// Set the base directory to compare with
$use_root_directory = $root_directory;
if(empty($use_root_directory)) {
$use_root_directory = realpath(dirname(__FILE__).'/../../.');
}
$realfilepath = realpath($filepath);
/** Replace all \\ with \ first */
$realfilepath = str_replace('\\\\', '\\', $realfilepath);
$rootdirpath = str_replace('\\\\', '\\', $use_root_directory);
/** Replace all \ with / now */
$realfilepath = str_replace('\\', '/', $realfilepath);
$rootdirpath = str_replace('\\', '/', $rootdirpath);
if(stripos($realfilepath, $rootdirpath) !== 0) {
if($dieOnFail) {
die("Sorry! Attempt to access restricted file.");
}
return false;
}
return true;
}
/**
* Log the debug message
* @param String Log message
* @param Boolean true to append end-of-line, false otherwise
*/
static function Log($message, $delimit=true) {
global $Vtiger_Utils_Log, $log;
$log->debug($message);
if(!isset($Vtiger_Utils_Log) || $Vtiger_Utils_Log == false) return;
print_r($message);
if($delimit) {
if(isset($_REQUEST)) echo "<BR>";
else echo "\n";
}
}
/**
* Escape the string to avoid SQL Injection attacks.
* @param String Sql statement string
*/
static function SQLEscape($value) {
if($value == null) return $value;
global $adb;
return $adb->sql_escape_string($value);
}
/**
* Check if table is present in database
* @param String tablename to check
*/
static function CheckTable($tablename) {
global $adb;
$old_dieOnError = $adb->dieOnError;
$adb->dieOnError = false;
$tablename = Vtiger_Utils::SQLEscape($tablename);
$tablecheck = $adb->query("SELECT 1 FROM $tablename LIMIT 1");
$tablePresent = true;
if(empty($tablecheck))
$tablePresent = false;
$adb->dieOnError = $old_dieOnError;
return $tablePresent;
}
/**
* Create table (supressing failure)
* @param String tablename to create
* @param String table creation criteria like '(columnname columntype, ....)'
* @param String Optional suffix to add during table creation
* <br>
* will be appended to CREATE TABLE $tablename SQL
*/
static function CreateTable($tablename, $criteria, $suffixTableMeta=false) {
global $adb;
$org_dieOnError = $adb->dieOnError;
$adb->dieOnError = false;
$sql = "CREATE TABLE " . $tablename . $criteria;
if($suffixTableMeta !== false) {
if($suffixTableMeta === true) {
if($adb->isMySQL()) {
$suffixTableMeta = ' ENGINE=InnoDB DEFAULT CHARSET=utf8';
} else {
// TODO Handle other database types.
}
}
$sql .= $suffixTableMeta;
}
$adb->query($sql);
$adb->dieOnError = $org_dieOnError;
}
/**
* Alter existing table
* @param String tablename to alter
* @param String alter criteria like ' ADD columnname columntype' <br>
* will be appended to ALTER TABLE $tablename SQL
*/
static function AlterTable($tablename, $criteria) {
global $adb;
$adb->query("ALTER TABLE " . $tablename . $criteria);
}
/**
* Add column to existing table
* @param String tablename to alter
* @param String columnname to add
* @param String columntype (criteria like 'VARCHAR(100)')
*/
static function AddColumn($tablename, $columnname, $criteria) {
global $adb;
if(!in_array($columnname, $adb->getColumnNames($tablename))) {
self::AlterTable($tablename, " ADD COLUMN $columnname $criteria");
}
}
/**
* Get SQL query
* @param String SQL query statement
*/
static function ExecuteQuery($sqlquery, $supressdie=false) {
global $adb;
$old_dieOnError = $adb->dieOnError;
if($supressdie) $adb->dieOnError = false;
$adb->query($sqlquery);
$adb->dieOnError = $old_dieOnError;
}
/**
* Get CREATE SQL for given table
* @param String tablename for which CREATE SQL is requried
*/
static function CreateTableSql($tablename) {
global $adb;
$create_table = $adb->query("SHOW CREATE TABLE $tablename");
$sql = decode_html($adb->query_result($create_table, 0, 1));
return $sql;
}
/**
* Check if the given SQL is a CREATE statement
* @param String SQL String
*/
static function IsCreateSql($sql) {
if(preg_match('/(CREATE TABLE)/', strtoupper($sql))) {
return true;
}
return false;
}
/**
* Check if the given SQL is destructive (DELETE's DATA)
* @param String SQL String
*/
static function IsDestructiveSql($sql) {
if(preg_match('/(DROP TABLE)|(DROP COLUMN)|(DELETE FROM)/',
strtoupper($sql))) {
return true;
}
return false;
}
}
?>
@@ -0,0 +1,115 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
/**
* Template class will enable you to replace a merge fields defined in the String
* with values set dynamically.
*
* @author Prasad
* @package vtlib
*/
class Vtiger_StringTemplate {
// Template variables set dynamically
var $tplvars = Array();
/**
* Identify variable with the following pattern
* $VARIABLE_KEY$
*/
var $_lookfor = '/\$([^\$]+)\$/';
/**
* Constructor
*/
function __construct() {
}
/**
* Assign replacement value for the variable.
*/
function assign($key, $value) {
$this->tplvars[$key] = $value;
}
/**
* Get replacement value for the variable.
*/
function get($key) {
$value = false;
if(isset($this->tplvars[$key])) {
$value = $this->tplvars[$key];
}
return $value;
}
/**
* Clear all the assigned variable values.
* (except the once in the given list)
*/
function clear($exceptvars=false) {
$restorevars = Array();
if($exceptvars) {
foreach($exceptvars as $varkey) {
$restorevars[$varkey] = $this->get($varkey);
}
}
unset($this->tplvars);
$this->tplvars = Array();
foreach($restorevars as $key=>$val) $this->assign($key, $val);
}
/**
* Merge the given file with variable values assigned.
* @param $instring input string template
* @param $avoidLookup should be true if only verbatim file copy needs to be done
* @returns merged contents
*/
function merge($instring, $avoidLookup=false) {
if(empty($instring)) return $instring;
if(!$avoidLookup) {
/** Look for variables */
$matches = Array();
preg_match_all($this->_lookfor, $instring, $matches);
/** Replace variables found with value assigned. */
$matchcount = count($matches[1]);
for($index = 0; $index < $matchcount; ++$index) {
$matchstr = $matches[0][$index];
$matchkey = $matches[1][$index];
$matchstr_regex = $this->__formatAsRegex($matchstr);
$replacewith = $this->get($matchkey);
if($replacewith) {
$instring = preg_replace(
"/$matchstr_regex/", $replacewith, $instring);
}
}
}
return $instring;
}
/**
* Clean up the input to be used as a regex
* @access private
*/
function __formatAsRegex($value) {
// If / is not already escaped as \/ do it now
$value = preg_replace('/\//', '\\/', $value);
// If $ is not already escaped as \$ do it now
$value = preg_replace('/(?<!\\\)\$/', '\\\\$', $value);
return $value;
}
}
?>
+36
View File
@@ -0,0 +1,36 @@
<?php
/*+***********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
*************************************************************************************/
include_once('vtigerversion.php');
/**
* Provides utility APIs to work with Vtiger Version detection
* @package vtlib
*/
class Vtiger_Version {
/**
* Get current version of vtiger in use.
*/
static function current() {
global $vtiger_current_version;
return $vtiger_current_version;
}
/**
* Check current version of vtiger with given version
* @param String Version against which comparision to be done
* @param String Condition like ( '=', '!=', '<', '<=', '>', '>=')
*/
static function check($with_version, $condition='=') {
$current_version = self::current();
return version_compare($current_version, $with_version, $condition);
}
}
?>
@@ -0,0 +1,42 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
include_once('vtlib/Vtiger/Utils.php');
/**
* Provides API to work with vtiger CRM Webservice (available from vtiger 5.1)
* @package vtlib
*/
class Vtiger_Webservice {
/**
* Helper function to log messages
* @param String Message to log
* @param Boolean true appends linebreak, false to avoid it
* @access private
*/
static function log($message, $delim=true) {
Vtiger_Utils::Log($message, $delim);
}
/**
* Initialize webservice for the given module
* @param Vtiger_Module Instance of the module.
*/
static function initialize($moduleInstance) {
if($moduleInstance->isentitytype) {
// TODO: Enable support when webservice API support is added.
if(function_exists('vtws_addDefaultModuleTypeEntity')) {
vtws_addDefaultModuleTypeEntity($moduleInstance->name);
self::log("Initializing webservices support ...DONE");
}
}
}
}
?>
+111
View File
@@ -0,0 +1,111 @@
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
require_once('vtlib/thirdparty/dZip.inc.php');
/**
* Wrapper class over dZip.
* @package vtlib
*/
class Vtiger_Zip extends dZip {
/**
* Push out the file content for download.
*/
function forceDownload($zipfileName) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=".basename($zipfileName).";" );
//header("Content-Transfer-Encoding: binary");
// For details on this workaround check here the ticket
// http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/5298
$disk_file_size = filesize($zipfileName);
$zipfilesize = $disk_file_size + ($disk_file_size % 1024);
header("Content-Length: ".$zipfilesize);
$fileContent = fread(fopen($zipfileName, "rb"), $zipfilesize);
echo $fileContent;
}
/**
* Get relative path (w.r.t base)
*/
function __getRelativePath($basepath, $srcpath) {
$base_realpath = $this->__normalizePath(realpath($basepath));
$src_realpath = $this->__normalizePath(realpath($srcpath));
$search_index = strpos($src_realpath, $base_realpath);
if($search_index === 0) {
$startindex = strlen($base_realpath)+1;
// On windows $base_realpath ends with / and On Linux it will not have / at end!
if(strrpos($base_realpath, '/') == strlen($base_realpath)-1) $startindex -= 1;
$relpath = substr($src_realpath, $startindex);
}
return $relpath;
}
/**
* Check and add '/' directory separator
*/
function __fixDirSeparator($path) {
if($path != '' && (strripos($path, '/') != strlen($path)-1)) $path .= '/';
return $path;
}
/**
* Normalize the directory path separators.
*/
function __normalizePath($path) {
if($path && strpos($path, '\\')!== false) $path = preg_replace("/\\\\/", "/", $path);
return $path;
}
/**
* Copy the directory on the disk into zip file.
*/
function copyDirectoryFromDisk($dirname, $zipdirname=null, $excludeList=null, $basedirname=null) {
$dir = opendir($dirname);
if(strripos($dirname, '/') != strlen($dirname)-1)
$dirname .= '/';
if($basedirname == null) $basedirname = realpath($dirname);
while(false !== ($file = readdir($dir))) {
if($file != '.' && $file != '..' &&
$file != '.svn' && $file != 'CVS') {
// Exclude the file/directory
if(!empty($excludeList) && in_array("$dirname$file", $excludeList))
continue;
if(is_dir("$dirname$file")) {
$this->copyDirectoryFromDisk("$dirname$file", $zipdirname, $excludeList, $basedirname);
} else {
$zippath = $dirname;
if($zipdirname != null && $zipdirname != '') {
$zipdirname = $this->__fixDirSeparator($zipdirname);
$zippath = $zipdirname.$this->__getRelativePath($basedirname, $dirname);
}
$this->copyFileFromDisk($dirname, $zippath, $file);
}
}
}
closedir($dir);
}
/**
* Copy the disk file into the zip.
*/
function copyFileFromDisk($path, $zippath, $file) {
$path = $this->__fixDirSeparator($path);
$zippath = $this->__fixDirSeparator($zippath);
$this->addFile("$path$file", "$zippath$file");
}
}
?>
+517
View File
@@ -0,0 +1,517 @@
<?php
/**
* DOWNLOADED FROM: http://www.phpclasses.org/browse/package/2495/
* License: BSD License
*/
?>
<?php
// 15/07/2006 (2.6)
// - Changed the algorithm to parse the ZIP file.. Now, the script will try to mount the compressed
// list, searching on the 'Central Dir' records. If it fails, the script will try to search by
// checking every signature. Thanks to Jayson Cruz for pointing it.
// 25/01/2006 (2.51)
// - Fixed bug when calling 'unzip' without calling 'getList' first. Thanks to Bala Murthu for pointing it.
// 01/12/2006 (2.5)
// - Added optional parameter "applyChmod" for the "unzip()" method. It auto applies the given chmod for
// extracted files.
// - Permission 777 (all read-write-exec) is default. If you want to change it, you'll need to make it
// explicit. (If you want the OS to determine, set "false" as "applyChmod" parameter)
// 28/11/2005 (2.4)
// - dUnzip2 is now compliant with old-style "Data Description", made by some compressors,
// like the classes ZipLib and ZipLib2 by 'Hasin Hayder'. Thanks to Ricardo Parreno for pointing it.
// 09/11/2005 (2.3)
// - Added optional parameter '$stopOnFile' on method 'getList()'.
// If given, file listing will stop when find given filename. (Useful to open and unzip an exact file)
// 06/11/2005 (2.21)
// - Added support to PK00 file format (Packed to Removable Disk) (thanks to Lito [PHPfileNavigator])
// - Method 'getExtraInfo': If requested file doesn't exist, return FALSE instead of Array()
// 31/10/2005 (2.2)
// - Removed redundant 'file_name' on centralDirs declaration (thanks to Lito [PHPfileNavigator])
// - Fixed redeclaration of file_put_contents when in PHP4 (not returning true)
##############################################################
# Class dUnzip2 v2.6
#
# Author: Alexandre Tedeschi (d)
# E-Mail: alexandrebr at gmail dot com
# Londrina - PR / Brazil
#
# Objective:
# This class allows programmer to easily unzip files on the fly.
#
# Requirements:
# This class requires extension ZLib Enabled. It is default
# for most site hosts around the world, and for the PHP Win32 dist.
#
# To do:
# * Error handling
# * Write a PHP-Side gzinflate, to completely avoid any external extensions
# * Write other decompress algorithms
#
# If you modify this class, or have any ideas to improve it, please contact me!
# You are allowed to redistribute this class, if you keep my name and contact e-mail on it.
#
# PLEASE! IF YOU USE THIS CLASS IN ANY OF YOUR PROJECTS, PLEASE LET ME KNOW!
# If you have problems using it, don't think twice before contacting me!
#
##############################################################
if(!function_exists('file_put_contents')){
// If not PHP5, creates a compatible function
Function file_put_contents($file, $data){
if($tmp = fopen($file, "w")){
fwrite($tmp, $data);
fclose($tmp);
return true;
}
echo "<b>file_put_contents:</b> Cannot create file $file<br>";
return false;
}
}
class dUnzip2{
Function getVersion(){
return "2.6";
}
// Public
var $fileName;
var $compressedList; // You will problably use only this one!
var $centralDirList; // Central dir list... It's a kind of 'extra attributes' for a set of files
var $endOfCentral; // End of central dir, contains ZIP Comments
var $debug;
// Private
var $fh;
var $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
var $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
var $dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature
// Public
Function dUnzip2($fileName){
$this->fileName = $fileName;
$this->compressedList =
$this->centralDirList =
$this->endOfCentral = Array();
}
Function getList($stopOnFile=false){
if(sizeof($this->compressedList)){
$this->debugMsg(1, "Returning already loaded file list.");
return $this->compressedList;
}
// Open file, and set file handler
$fh = fopen($this->fileName, "r");
$this->fh = &$fh;
if(!$fh){
$this->debugMsg(2, "Failed to load file.");
return false;
}
$this->debugMsg(1, "Loading list from 'End of Central Dir' index list...");
if(!$this->_loadFileListByEOF($fh, $stopOnFile)){
$this->debugMsg(1, "Failed! Trying to load list looking for signatures...");
if(!$this->_loadFileListBySignatures($fh, $stopOnFile)){
$this->debugMsg(1, "Failed! Could not find any valid header.");
$this->debugMsg(2, "ZIP File is corrupted or empty");
return false;
}
}
if($this->debug){
#------- Debug compressedList
$kkk = 0;
echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>";
foreach($this->compressedList as $fileName=>$item){
if(!$kkk && $kkk=1){
echo "<tr style='background: #ADA'>";
foreach($item as $fieldName=>$value)
echo "<td>$fieldName</td>";
echo '</tr>';
}
echo "<tr style='background: #CFC'>";
foreach($item as $fieldName=>$value){
if($fieldName == 'lastmod_datetime')
echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>";
else
echo "<td title='$fieldName' nowrap='nowrap'>$value</td>";
}
echo "</tr>";
}
echo "</table>";
#------- Debug centralDirList
$kkk = 0;
if(sizeof($this->centralDirList)){
echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>";
foreach($this->centralDirList as $fileName=>$item){
if(!$kkk && $kkk=1){
echo "<tr style='background: #AAD'>";
foreach($item as $fieldName=>$value)
echo "<td>$fieldName</td>";
echo '</tr>';
}
echo "<tr style='background: #CCF'>";
foreach($item as $fieldName=>$value){
if($fieldName == 'lastmod_datetime')
echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>";
else
echo "<td title='$fieldName' nowrap='nowrap'>$value</td>";
}
echo "</tr>";
}
echo "</table>";
}
#------- Debug endOfCentral
$kkk = 0;
if(sizeof($this->endOfCentral)){
echo "<table border='0' style='font: 11px Verdana' style='border: 1px solid #000'>";
echo "<tr style='background: #DAA'><td colspan='2'>dUnzip - End of file</td></tr>";
foreach($this->endOfCentral as $field=>$value){
echo "<tr>";
echo "<td style='background: #FCC'>$field</td>";
echo "<td style='background: #FDD'>$value</td>";
echo "</tr>";
}
echo "</table>";
}
}
return $this->compressedList;
}
Function getExtraInfo($compressedFileName){
return
isset($this->centralDirList[$compressedFileName])?
$this->centralDirList[$compressedFileName]:
false;
}
Function getZipInfo($detail=false){
return $detail?
$this->endOfCentral[$detail]:
$this->endOfCentral;
}
Function unzip($compressedFileName, $targetFileName=false, $applyChmod=0777){
if(!sizeof($this->compressedList)){
$this->debugMsg(1, "Trying to unzip before loading file list... Loading it!");
$this->getList(false, $compressedFileName);
}
$fdetails = &$this->compressedList[$compressedFileName];
if(!isset($this->compressedList[$compressedFileName])){
$this->debugMsg(2, "File '<b>$compressedFileName</b>' is not compressed in the zip.");
return false;
}
if(substr($compressedFileName, -1) == "/"){
$this->debugMsg(2, "Trying to unzip a folder name '<b>$compressedFileName</b>'.");
return false;
}
if(!$fdetails['uncompressed_size']){
$this->debugMsg(1, "File '<b>$compressedFileName</b>' is empty.");
return $targetFileName?
file_put_contents($targetFileName, ""):
"";
}
fseek($this->fh, $fdetails['contents-startOffset']);
$ret = $this->uncompress(
fread($this->fh, $fdetails['compressed_size']),
$fdetails['compression_method'],
$fdetails['uncompressed_size'],
$targetFileName
);
if($applyChmod && $targetFileName)
chmod($targetFileName, 0777);
return $ret;
}
Function unzipAll($targetDir=false, $baseDir="", $maintainStructure=true, $applyChmod=0777){
if($targetDir === false)
$targetDir = dirname(__FILE__)."/";
$lista = $this->getList();
if(sizeof($lista)) foreach($lista as $fileName=>$trash){
$dirname = dirname($fileName);
$outDN = "$targetDir/$dirname";
if(substr($dirname, 0, strlen($baseDir)) != $baseDir)
continue;
if(!is_dir($outDN) && $maintainStructure){
$str = "";
$folders = explode("/", $dirname);
foreach($folders as $folder){
$str = $str?"$str/$folder":$folder;
if(!is_dir("$targetDir/$str")){
$this->debugMsg(1, "Creating folder: $targetDir/$str");
mkdir("$targetDir/$str");
if($applyChmod)
chmod("$targetDir/$str", $applyChmod);
}
}
}
if(substr($fileName, -1, 1) == "/")
continue;
$maintainStructure?
$this->unzip($fileName, "$targetDir/$fileName", $applyChmod):
$this->unzip($fileName, "$targetDir/".basename($fileName), $applyChmod);
}
}
Function close(){ // Free the file resource
if($this->fh)
fclose($this->fh);
}
Function __destroy(){
$this->close();
}
// Private (you should NOT call these methods):
Function uncompress($content, $mode, $uncompressedSize, $targetFileName=false){
switch($mode){
case 0:
// Not compressed
return $targetFileName?
file_put_contents($targetFileName, $content):
$content;
case 1:
$this->debugMsg(2, "Shrunk mode is not supported... yet?");
return false;
case 2:
case 3:
case 4:
case 5:
$this->debugMsg(2, "Compression factor ".($mode-1)." is not supported... yet?");
return false;
case 6:
$this->debugMsg(2, "Implode is not supported... yet?");
return false;
case 7:
$this->debugMsg(2, "Tokenizing compression algorithm is not supported... yet?");
return false;
case 8:
// Deflate
return $targetFileName?
file_put_contents($targetFileName, gzinflate($content, $uncompressedSize)):
gzinflate($content, $uncompressedSize);
case 9:
$this->debugMsg(2, "Enhanced Deflating is not supported... yet?");
return false;
case 10:
$this->debugMsg(2, "PKWARE Date Compression Library Impoloding is not supported... yet?");
return false;
case 12:
// Bzip2
return $targetFileName?
file_put_contents($targetFileName, bzdecompress($content)):
bzdecompress($content);
case 18:
$this->debugMsg(2, "IBM TERSE is not supported... yet?");
return false;
default:
$this->debugMsg(2, "Unknown uncompress method: $mode");
return false;
}
}
Function debugMsg($level, $string){
if($this->debug)
if($level == 1)
echo "<b style='color: #777'>dUnzip2:</b> $string<br>";
if($level == 2)
echo "<b style='color: #F00'>dUnzip2:</b> $string<br>";
}
Function _loadFileListByEOF(&$fh, $stopOnFile=false){
// Check if there's a valid Central Dir signature.
// Let's consider a file comment smaller than 1024 characters...
// Actually, it length can be 65536.. But we're not going to support it.
for($x = 0; $x < 1024; $x++){
fseek($fh, -22-$x, SEEK_END);
$signature = fread($fh, 4);
if($signature == $this->dirSignatureE){
// If found EOF Central Dir
$eodir['disk_number_this'] = unpack("v", fread($fh, 2)); // number of this disk
$eodir['disk_number'] = unpack("v", fread($fh, 2)); // number of the disk with the start of the central directory
$eodir['total_entries_this'] = unpack("v", fread($fh, 2)); // total number of entries in the central dir on this disk
$eodir['total_entries'] = unpack("v", fread($fh, 2)); // total number of entries in
$eodir['size_of_cd'] = unpack("V", fread($fh, 4)); // size of the central directory
$eodir['offset_start_cd'] = unpack("V", fread($fh, 4)); // offset of start of central directory with respect to the starting disk number
$zipFileCommentLenght = unpack("v", fread($fh, 2)); // zipfile comment length
$eodir['zipfile_comment'] = $zipFileCommentLenght[1]?fread($fh, $zipFileCommentLenght[1]):''; // zipfile comment
$this->endOfCentral = Array(
'disk_number_this'=>$eodir['disk_number_this'][1],
'disk_number'=>$eodir['disk_number'][1],
'total_entries_this'=>$eodir['total_entries_this'][1],
'total_entries'=>$eodir['total_entries'][1],
'size_of_cd'=>$eodir['size_of_cd'][1],
'offset_start_cd'=>$eodir['offset_start_cd'][1],
'zipfile_comment'=>$eodir['zipfile_comment'],
);
// Then, load file list
fseek($fh, $this->endOfCentral['offset_start_cd']);
$signature = fread($fh, 4);
while($signature == $this->dirSignature){
$dir['version_madeby'] = unpack("v", fread($fh, 2)); // version made by
$dir['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract
$dir['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag
$dir['compression_method'] = unpack("v", fread($fh, 2)); // compression method
$dir['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time
$dir['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date
$dir['crc-32'] = fread($fh, 4); // crc-32
$dir['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size
$dir['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size
$fileNameLength = unpack("v", fread($fh, 2)); // filename length
$extraFieldLength = unpack("v", fread($fh, 2)); // extra field length
$fileCommentLength = unpack("v", fread($fh, 2)); // file comment length
$dir['disk_number_start'] = unpack("v", fread($fh, 2)); // disk number start
$dir['internal_attributes'] = unpack("v", fread($fh, 2)); // internal file attributes-byte1
$dir['external_attributes1']= unpack("v", fread($fh, 2)); // external file attributes-byte2
$dir['external_attributes2']= unpack("v", fread($fh, 2)); // external file attributes
$dir['relative_offset'] = unpack("V", fread($fh, 4)); // relative offset of local header
$dir['file_name'] = fread($fh, $fileNameLength[1]); // filename
$dir['extra_field'] = $extraFieldLength[1] ?fread($fh, $extraFieldLength[1]) :''; // extra field
$dir['file_comment'] = $fileCommentLength[1]?fread($fh, $fileCommentLength[1]):''; // file comment
// Convert the date and time, from MS-DOS format to UNIX Timestamp
$BINlastmod_date = str_pad(decbin($dir['lastmod_date'][1]), 16, '0', STR_PAD_LEFT);
$BINlastmod_time = str_pad(decbin($dir['lastmod_time'][1]), 16, '0', STR_PAD_LEFT);
$lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980;
$lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4));
$lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5));
$lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5));
$lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6));
$lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5));
$this->centralDirList[$dir['file_name']] = Array(
'version_madeby'=>$dir['version_madeby'][1],
'version_needed'=>$dir['version_needed'][1],
'general_bit_flag'=>str_pad(decbin($dir['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT),
'compression_method'=>$dir['compression_method'][1],
'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY),
'crc-32' =>str_pad(dechex(ord($dir['crc-32'][3])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($dir['crc-32'][2])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($dir['crc-32'][1])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($dir['crc-32'][0])), 2, '0', STR_PAD_LEFT),
'compressed_size'=>$dir['compressed_size'][1],
'uncompressed_size'=>$dir['uncompressed_size'][1],
'disk_number_start'=>$dir['disk_number_start'][1],
'internal_attributes'=>$dir['internal_attributes'][1],
'external_attributes1'=>$dir['external_attributes1'][1],
'external_attributes2'=>$dir['external_attributes2'][1],
'relative_offset'=>$dir['relative_offset'][1],
'file_name'=>$dir['file_name'],
'extra_field'=>$dir['extra_field'],
'file_comment'=>$dir['file_comment'],
);
$signature = fread($fh, 4);
}
// If loaded centralDirs, then try to identify the offsetPosition of the compressed data.
if($this->centralDirList) foreach($this->centralDirList as $filename=>$details){
$i = $this->_getFileHeaderInformation($fh, $details['relative_offset']);
$this->compressedList[$filename]['file_name'] = $filename;
$this->compressedList[$filename]['compression_method'] = $details['compression_method'];
$this->compressedList[$filename]['version_needed'] = $details['version_needed'];
$this->compressedList[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
$this->compressedList[$filename]['crc-32'] = $details['crc-32'];
$this->compressedList[$filename]['compressed_size'] = $details['compressed_size'];
$this->compressedList[$filename]['uncompressed_size'] = $details['uncompressed_size'];
$this->compressedList[$filename]['lastmod_datetime'] = $details['lastmod_datetime'];
$this->compressedList[$filename]['extra_field'] = $i['extra_field'];
$this->compressedList[$filename]['contents-startOffset']=$i['contents-startOffset'];
if(strtolower($stopOnFile) == strtolower($filename))
break;
}
return true;
}
}
return false;
}
Function _loadFileListBySignatures(&$fh, $stopOnFile=false){
fseek($fh, 0);
$return = false;
for(;;){
$details = $this->_getFileHeaderInformation($fh);
if(!$details){
$this->debugMsg(1, "Invalid signature. Trying to verify if is old style Data Descriptor...");
fseek($fh, 12 - 4, SEEK_CUR); // 12: Data descriptor - 4: Signature (that will be read again)
$details = $this->_getFileHeaderInformation($fh);
}
if(!$details){
$this->debugMsg(1, "Still invalid signature. Probably reached the end of the file.");
break;
}
$filename = $details['file_name'];
$this->compressedList[$filename] = $details;
$return = true;
if(strtolower($stopOnFile) == strtolower($filename))
break;
}
return $return;
}
Function _getFileHeaderInformation(&$fh, $startOffset=false){
if($startOffset !== false)
fseek($fh, $startOffset);
$signature = fread($fh, 4);
if($signature == $this->zipSignature){
# $this->debugMsg(1, "Zip Signature!");
// Get information about the zipped file
$file['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract
$file['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag
$file['compression_method'] = unpack("v", fread($fh, 2)); // compression method
$file['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time
$file['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date
$file['crc-32'] = fread($fh, 4); // crc-32
$file['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size
$file['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size
$fileNameLength = unpack("v", fread($fh, 2)); // filename length
$extraFieldLength = unpack("v", fread($fh, 2)); // extra field length
$file['file_name'] = fread($fh, $fileNameLength[1]); // filename
$file['extra_field'] = $extraFieldLength[1]?fread($fh, $extraFieldLength[1]):''; // extra field
$file['contents-startOffset']= ftell($fh);
// Bypass the whole compressed contents, and look for the next file
fseek($fh, $file['compressed_size'][1], SEEK_CUR);
// Convert the date and time, from MS-DOS format to UNIX Timestamp
$BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT);
$BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT);
$lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980;
$lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4));
$lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5));
$lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5));
$lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6));
$lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5));
// Mount file table
$i = Array(
'file_name' =>$file['file_name'],
'compression_method'=>$file['compression_method'][1],
'version_needed' =>$file['version_needed'][1],
'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY),
'crc-32' =>str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT).
str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT),
'compressed_size' =>$file['compressed_size'][1],
'uncompressed_size' =>$file['uncompressed_size'][1],
'extra_field' =>$file['extra_field'],
'general_bit_flag' =>str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT),
'contents-startOffset'=>$file['contents-startOffset']
);
return $i;
}
return false;
}
}
?>
+153
View File
@@ -0,0 +1,153 @@
<?php
/**
* DOWNLOADED FROM: http://www.phpclasses.org/browse/package/2495/
* License: BSD License
*/
?>
<?php
class dZip{
var $filename;
var $overwrite;
var $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
var $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
var $dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature
var $files_count = 0;
var $fh;
Function dZip($filename, $overwrite=true){
$this->filename = $filename;
$this->overwrite = $overwrite;
}
Function addDir($dirname, $fileComments=''){
if(substr($dirname, -1) != '/')
$dirname .= '/';
$this->addFile(false, $dirname, $fileComments);
}
Function addFile($filename, $cfilename, $fileComments='', $data=false){
if(!($fh = &$this->fh))
$fh = fopen($this->filename, $this->overwrite?'wb':'a+b');
// $filename can be a local file OR the data wich will be compressed
if(substr($cfilename, -1)=='/'){
$details['uncsize'] = 0;
$data = '';
}
elseif(file_exists($filename)){
$details['uncsize'] = filesize($filename);
$data = file_get_contents($filename);
}
elseif($filename){
echo "<b>Cannot add $filename. File not found</b><br>";
return false;
}
else{
$details['uncsize'] = strlen($data); // Prasad: Fixed instead of strlen($filename)
// DATA is given.. use it! :|
}
// if data to compress is too small, just store it
if($details['uncsize'] < 256){
$details['comsize'] = $details['uncsize'];
$details['vneeded'] = 10;
$details['cmethod'] = 0;
$zdata = &$data;
}
else{ // otherwise, compress it
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug (thanks to Eric Mueller)
$details['comsize'] = strlen($zdata);
$details['vneeded'] = 10;
$details['cmethod'] = 8;
}
$details['bitflag'] = 0;
$details['crc_32'] = crc32($data);
// Convert date and time to DOS Format, and set then
$lastmod_timeS = str_pad(decbin(date('s')>=32?date('s')-32:date('s')), 5, '0', STR_PAD_LEFT);
$lastmod_timeM = str_pad(decbin(date('i')), 6, '0', STR_PAD_LEFT);
$lastmod_timeH = str_pad(decbin(date('H')), 5, '0', STR_PAD_LEFT);
$lastmod_dateD = str_pad(decbin(date('d')), 5, '0', STR_PAD_LEFT);
$lastmod_dateM = str_pad(decbin(date('m')), 4, '0', STR_PAD_LEFT);
$lastmod_dateY = str_pad(decbin(date('Y')-1980), 7, '0', STR_PAD_LEFT);
# echo "ModTime: $lastmod_timeS-$lastmod_timeM-$lastmod_timeH (".date("s H H").")\n";
# echo "ModDate: $lastmod_dateD-$lastmod_dateM-$lastmod_dateY (".date("d m Y").")\n";
$details['modtime'] = bindec("$lastmod_timeH$lastmod_timeM$lastmod_timeS");
$details['moddate'] = bindec("$lastmod_dateY$lastmod_dateM$lastmod_dateD");
$details['offset'] = ftell($fh);
fwrite($fh, $this->zipSignature);
fwrite($fh, pack('s', $details['vneeded'])); // version_needed
fwrite($fh, pack('s', $details['bitflag'])); // general_bit_flag
fwrite($fh, pack('s', $details['cmethod'])); // compression_method
fwrite($fh, pack('s', $details['modtime'])); // lastmod_time
fwrite($fh, pack('s', $details['moddate'])); // lastmod_date
fwrite($fh, pack('V', $details['crc_32'])); // crc-32
fwrite($fh, pack('I', $details['comsize'])); // compressed_size
fwrite($fh, pack('I', $details['uncsize'])); // uncompressed_size
fwrite($fh, pack('s', strlen($cfilename))); // file_name_length
fwrite($fh, pack('s', 0)); // extra_field_length
fwrite($fh, $cfilename); // file_name
// ignoring extra_field
fwrite($fh, $zdata);
// Append it to central dir
$details['external_attributes'] = (substr($cfilename, -1)=='/'&&!$zdata)?16:32; // Directory or file name
$details['comments'] = $fileComments;
$this->appendCentralDir($cfilename, $details);
$this->files_count++;
}
Function setExtra($filename, $property, $value){
$this->centraldirs[$filename][$property] = $value;
}
Function save($zipComments=''){
if(!($fh = &$this->fh))
$fh = fopen($this->filename, $this->overwrite?'w':'a+');
$cdrec = "";
foreach($this->centraldirs as $filename=>$cd){
$cdrec .= $this->dirSignature;
$cdrec .= "\x0\x0"; // version made by
$cdrec .= pack('v', $cd['vneeded']); // version needed to extract
$cdrec .= "\x0\x0"; // general bit flag
$cdrec .= pack('v', $cd['cmethod']); // compression method
$cdrec .= pack('v', $cd['modtime']); // lastmod time
$cdrec .= pack('v', $cd['moddate']); // lastmod date
$cdrec .= pack('V', $cd['crc_32']); // crc32
$cdrec .= pack('V', $cd['comsize']); // compressed filesize
$cdrec .= pack('V', $cd['uncsize']); // uncompressed filesize
$cdrec .= pack('v', strlen($filename)); // file comment length
$cdrec .= pack('v', 0); // extra field length
$cdrec .= pack('v', strlen($cd['comments'])); // file comment length
$cdrec .= pack('v', 0); // disk number start
$cdrec .= pack('v', 0); // internal file attributes
$cdrec .= pack('V', $cd['external_attributes']); // internal file attributes
$cdrec .= pack('V', $cd['offset']); // relative offset of local header
$cdrec .= $filename;
$cdrec .= $cd['comments'];
}
$before_cd = ftell($fh);
fwrite($fh, $cdrec);
// end of central dir
fwrite($fh, $this->dirSignatureE);
fwrite($fh, pack('v', 0)); // number of this disk
fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory
fwrite($fh, pack('v', $this->files_count)); // total # of entries "on this disk"
fwrite($fh, pack('v', $this->files_count)); // total # of entries overall
fwrite($fh, pack('V', strlen($cdrec))); // size of central dir
fwrite($fh, pack('V', $before_cd)); // offset to start of central dir
fwrite($fh, pack('v', strlen($zipComments))); // .zip file comment length
fwrite($fh, $zipComments);
fclose($fh);
}
// Private
Function appendCentralDir($filename,$properties){
$this->centraldirs[$filename] = $properties;
}
}
?>
+592
View File
@@ -0,0 +1,592 @@
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Stig Bakken <ssb@php.net> |
// | Chuck Hagenbuch <chuck@horde.org> |
// +----------------------------------------------------------------------+
//
// $Id: Socket.php,v 1.38 2008/02/15 18:24:17 chagenbu Exp $
require_once dirname(__FILE__) . '/../PEAR.php';
define('NET_SOCKET_READ', 1);
define('NET_SOCKET_WRITE', 2);
define('NET_SOCKET_ERROR', 4);
/**
* Generalized Socket class.
*
* @version 1.1
* @author Stig Bakken <ssb@php.net>
* @author Chuck Hagenbuch <chuck@horde.org>
*/
class Net_Socket extends PEAR {
/**
* Socket file pointer.
* @var resource $fp
*/
var $fp = null;
/**
* Whether the socket is blocking. Defaults to true.
* @var boolean $blocking
*/
var $blocking = true;
/**
* Whether the socket is persistent. Defaults to false.
* @var boolean $persistent
*/
var $persistent = false;
/**
* The IP address to connect to.
* @var string $addr
*/
var $addr = '';
/**
* The port number to connect to.
* @var integer $port
*/
var $port = 0;
/**
* Number of seconds to wait on socket connections before assuming
* there's no more data. Defaults to no timeout.
* @var integer $timeout
*/
var $timeout = false;
/**
* Number of bytes to read at a time in readLine() and
* readAll(). Defaults to 2048.
* @var integer $lineLength
*/
var $lineLength = 2048;
/**
* Connect to the specified port. If called when the socket is
* already connected, it disconnects and connects again.
*
* @param string $addr IP address or host name.
* @param integer $port TCP port number.
* @param boolean $persistent (optional) Whether the connection is
* persistent (kept open between requests
* by the web server).
* @param integer $timeout (optional) How long to wait for data.
* @param array $options See options for stream_context_create.
*
* @access public
*
* @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
*/
function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
{
if (is_resource($this->fp)) {
@fclose($this->fp);
$this->fp = null;
}
if (!$addr) {
return $this->raiseError('$addr cannot be empty');
} elseif (strspn($addr, '.0123456789') == strlen($addr) ||
strstr($addr, '/') !== false) {
$this->addr = $addr;
} else {
$this->addr = @gethostbyname($addr);
}
$this->port = $port % 65536;
if ($persistent !== null) {
$this->persistent = $persistent;
}
if ($timeout !== null) {
$this->timeout = $timeout;
}
$openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
$errno = 0;
$errstr = '';
$old_track_errors = @ini_set('track_errors', 1);
if ($options && function_exists('stream_context_create')) {
if ($this->timeout) {
$timeout = $this->timeout;
} else {
$timeout = 0;
}
$context = stream_context_create($options);
// Since PHP 5 fsockopen doesn't allow context specification
if (function_exists('stream_socket_client')) {
$flags = $this->persistent ? STREAM_CLIENT_PERSISTENT : STREAM_CLIENT_CONNECT;
$addr = $this->addr . ':' . $this->port;
$fp = stream_socket_client($addr, $errno, $errstr, $timeout, $flags, $context);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
}
} else {
if ($this->timeout) {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
}
}
if (!$fp) {
if ($errno == 0 && isset($php_errormsg)) {
$errstr = $php_errormsg;
}
@ini_set('track_errors', $old_track_errors);
return $this->raiseError($errstr, $errno);
}
@ini_set('track_errors', $old_track_errors);
$this->fp = $fp;
return $this->setBlocking($this->blocking);
}
/**
* Disconnects from the peer, closes the socket.
*
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function disconnect()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
@fclose($this->fp);
$this->fp = null;
return true;
}
/**
* Find out if the socket is in blocking mode.
*
* @access public
* @return boolean The current blocking mode.
*/
function isBlocking()
{
return $this->blocking;
}
/**
* Sets whether the socket connection should be blocking or
* not. A read call to a non-blocking socket will return immediately
* if there is no data available, whereas it will block until there
* is data for blocking sockets.
*
* @param boolean $mode True for blocking sockets, false for nonblocking.
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function setBlocking($mode)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$this->blocking = $mode;
socket_set_blocking($this->fp, $this->blocking);
return true;
}
/**
* Sets the timeout value on socket descriptor,
* expressed in the sum of seconds and microseconds
*
* @param integer $seconds Seconds.
* @param integer $microseconds Microseconds.
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function setTimeout($seconds, $microseconds)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return socket_set_timeout($this->fp, $seconds, $microseconds);
}
/**
* Sets the file buffering size on the stream.
* See php's stream_set_write_buffer for more information.
*
* @param integer $size Write buffer size.
* @access public
* @return mixed on success or an PEAR_Error object otherwise
*/
function setWriteBuffer($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$returned = stream_set_write_buffer($this->fp, $size);
if ($returned == 0) {
return true;
}
return $this->raiseError('Cannot set write buffer.');
}
/**
* Returns information about an existing socket resource.
* Currently returns four entries in the result array:
*
* <p>
* timed_out (bool) - The socket timed out waiting for data<br>
* blocked (bool) - The socket was blocked<br>
* eof (bool) - Indicates EOF event<br>
* unread_bytes (int) - Number of bytes left in the socket buffer<br>
* </p>
*
* @access public
* @return mixed Array containing information about existing socket resource or a PEAR_Error instance otherwise
*/
function getStatus()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return socket_get_status($this->fp);
}
/**
* Get a specified line of data
*
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function gets($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @fgets($this->fp, $size);
}
/**
* Read a specified amount of data. This is guaranteed to return,
* and has the added benefit of getting everything in one fread()
* chunk; if you know the size of the data you're getting
* beforehand, this is definitely the way to go.
*
* @param integer $size The number of bytes to read from the socket.
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function read($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @fread($this->fp, $size);
}
/**
* Write a specified amount of data.
*
* @param string $data Data to write.
* @param integer $blocksize Amount of data to write at once.
* NULL means all at once.
*
* @access public
* @return mixed If the socket is not connected, returns an instance of PEAR_Error
* If the write succeeds, returns the number of bytes written
* If the write fails, returns false.
*/
function write($data, $blocksize = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
if (is_null($blocksize) && !OS_WINDOWS) {
return @fwrite($this->fp, $data);
} else {
if (is_null($blocksize)) {
$blocksize = 1024;
}
$pos = 0;
$size = strlen($data);
while ($pos < $size) {
$written = @fwrite($this->fp, substr($data, $pos, $blocksize));
if ($written === false) {
return false;
}
$pos += $written;
}
return $pos;
}
}
/**
* Write a line of data to the socket, followed by a trailing "\r\n".
*
* @access public
* @return mixed fputs result, or an error
*/
function writeLine($data)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return fwrite($this->fp, $data . "\r\n");
}
/**
* Tests for end-of-file on a socket descriptor.
*
* Also returns true if the socket is disconnected.
*
* @access public
* @return bool
*/
function eof()
{
return (!is_resource($this->fp) || feof($this->fp));
}
/**
* Reads a byte of data
*
* @access public
* @return 1 byte of data from the socket, or a PEAR_Error if
* not connected.
*/
function readByte()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return ord(@fread($this->fp, 1));
}
/**
* Reads a word of data
*
* @access public
* @return 1 word of data from the socket, or a PEAR_Error if
* not connected.
*/
function readWord()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 2);
return (ord($buf[0]) + (ord($buf[1]) << 8));
}
/**
* Reads an int of data
*
* @access public
* @return integer 1 int of data from the socket, or a PEAR_Error if
* not connected.
*/
function readInt()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 4);
return (ord($buf[0]) + (ord($buf[1]) << 8) +
(ord($buf[2]) << 16) + (ord($buf[3]) << 24));
}
/**
* Reads a zero-terminated string of data
*
* @access public
* @return string, or a PEAR_Error if
* not connected.
*/
function readString()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$string = '';
while (($char = @fread($this->fp, 1)) != "\x00") {
$string .= $char;
}
return $string;
}
/**
* Reads an IP Address and returns it in a dot formatted string
*
* @access public
* @return Dot formatted string, or a PEAR_Error if
* not connected.
*/
function readIPAddress()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 4);
return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]),
ord($buf[2]), ord($buf[3]));
}
/**
* Read until either the end of the socket or a newline, whichever
* comes first. Strips the trailing newline from the returned data.
*
* @access public
* @return All available data up to a newline, without that
* newline, or until the end of the socket, or a PEAR_Error if
* not connected.
*/
function readLine()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$line = '';
$timeout = time() + $this->timeout;
while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
$line .= @fgets($this->fp, $this->lineLength);
if (substr($line, -1) == "\n") {
return rtrim($line, "\r\n");
}
}
return $line;
}
/**
* Read until the socket closes, or until there is no more data in
* the inner PHP buffer. If the inner buffer is empty, in blocking
* mode we wait for at least 1 byte of data. Therefore, in
* blocking mode, if there is no data at all to be read, this
* function will never exit (unless the socket is closed on the
* remote end).
*
* @access public
*
* @return string All data until the socket closes, or a PEAR_Error if
* not connected.
*/
function readAll()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$data = '';
while (!feof($this->fp)) {
$data .= @fread($this->fp, $this->lineLength);
}
return $data;
}
/**
* Runs the equivalent of the select() system call on the socket
* with a timeout specified by tv_sec and tv_usec.
*
* @param integer $state Which of read/write/error to check for.
* @param integer $tv_sec Number of seconds for timeout.
* @param integer $tv_usec Number of microseconds for timeout.
*
* @access public
* @return False if select fails, integer describing which of read/write/error
* are ready, or PEAR_Error if not connected.
*/
function select($state, $tv_sec, $tv_usec = 0)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$read = null;
$write = null;
$except = null;
if ($state & NET_SOCKET_READ) {
$read[] = $this->fp;
}
if ($state & NET_SOCKET_WRITE) {
$write[] = $this->fp;
}
if ($state & NET_SOCKET_ERROR) {
$except[] = $this->fp;
}
if (false === ($sr = stream_select($read, $write, $except, $tv_sec, $tv_usec))) {
return false;
}
$result = 0;
if (count($read)) {
$result |= NET_SOCKET_READ;
}
if (count($write)) {
$result |= NET_SOCKET_WRITE;
}
if (count($except)) {
$result |= NET_SOCKET_ERROR;
}
return $result;
}
/**
* Turns encryption on/off on a connected socket.
*
* @param bool $enabled Set this parameter to true to enable encryption
* and false to disable encryption.
* @param integer $type Type of encryption. See
* http://se.php.net/manual/en/function.stream-socket-enable-crypto.php for values.
*
* @access public
* @return false on error, true on success and 0 if there isn't enough data and the
* user should try again (non-blocking sockets only). A PEAR_Error object
* is returned if the socket is not connected
*/
function enableCrypto($enabled, $type)
{
if (version_compare(phpversion(), "5.1.0", ">=")) {
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @stream_socket_enable_crypto($this->fp, $enabled, $type);
} else {
return $this->raiseError('Net_Socket::enableCrypto() requires php version >= 5.1.0');
}
}
}
+485
View File
@@ -0,0 +1,485 @@
<?php
// +-----------------------------------------------------------------------+
// | Copyright (c) 2002-2004, Richard Heyes |
// | All rights reserved. |
// | |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | are met: |
// | |
// | o Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | o Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution.|
// | o The names of the authors may not be used to endorse or promote |
// | products derived from this software without specific prior written |
// | permission. |
// | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
// | |
// +-----------------------------------------------------------------------+
// | Author: Richard Heyes <richard at php net> |
// +-----------------------------------------------------------------------+
//
// $Id: URL.php,v 1.49 2007/06/28 14:43:07 davidc Exp $
//
// Net_URL Class
class Net_URL
{
var $options = array('encode_query_keys' => false);
/**
* Full url
* @var string
*/
var $url;
/**
* Protocol
* @var string
*/
var $protocol;
/**
* Username
* @var string
*/
var $username;
/**
* Password
* @var string
*/
var $password;
/**
* Host
* @var string
*/
var $host;
/**
* Port
* @var integer
*/
var $port;
/**
* Path
* @var string
*/
var $path;
/**
* Query string
* @var array
*/
var $querystring;
/**
* Anchor
* @var string
*/
var $anchor;
/**
* Whether to use []
* @var bool
*/
var $useBrackets;
/**
* PHP4 Constructor
*
* @see __construct()
*/
function Net_URL($url = null, $useBrackets = true)
{
$this->__construct($url, $useBrackets);
}
/**
* PHP5 Constructor
*
* Parses the given url and stores the various parts
* Defaults are used in certain cases
*
* @param string $url Optional URL
* @param bool $useBrackets Whether to use square brackets when
* multiple querystrings with the same name
* exist
*/
function __construct($url = null, $useBrackets = true)
{
$this->url = $url;
$this->useBrackets = $useBrackets;
$this->initialize();
}
function initialize()
{
$HTTP_SERVER_VARS = !empty($_SERVER) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
$this->user = '';
$this->pass = '';
$this->host = '';
$this->port = 80;
$this->path = '';
$this->querystring = array();
$this->anchor = '';
// Only use defaults if not an absolute URL given
if (!preg_match('/^[a-z0-9]+:\/\//i', $this->url)) {
$this->protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http');
/**
* Figure out host/port
*/
if (!empty($HTTP_SERVER_VARS['HTTP_HOST']) &&
preg_match('/^(.*)(:([0-9]+))?$/U', $HTTP_SERVER_VARS['HTTP_HOST'], $matches))
{
$host = $matches[1];
if (!empty($matches[3])) {
$port = $matches[3];
} else {
$port = $this->getStandardPort($this->protocol);
}
}
$this->user = '';
$this->pass = '';
$this->host = !empty($host) ? $host : (isset($HTTP_SERVER_VARS['SERVER_NAME']) ? $HTTP_SERVER_VARS['SERVER_NAME'] : 'localhost');
$this->port = !empty($port) ? $port : (isset($HTTP_SERVER_VARS['SERVER_PORT']) ? $HTTP_SERVER_VARS['SERVER_PORT'] : $this->getStandardPort($this->protocol));
$this->path = !empty($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : '/';
$this->querystring = isset($HTTP_SERVER_VARS['QUERY_STRING']) ? $this->_parseRawQuerystring($HTTP_SERVER_VARS['QUERY_STRING']) : null;
$this->anchor = '';
}
// Parse the url and store the various parts
if (!empty($this->url)) {
$urlinfo = parse_url($this->url);
// Default querystring
$this->querystring = array();
foreach ($urlinfo as $key => $value) {
switch ($key) {
case 'scheme':
$this->protocol = $value;
$this->port = $this->getStandardPort($value);
break;
case 'user':
case 'pass':
case 'host':
case 'port':
$this->$key = $value;
break;
case 'path':
if ($value{0} == '/') {
$this->path = $value;
} else {
$path = dirname($this->path) == DIRECTORY_SEPARATOR ? '' : dirname($this->path);
$this->path = sprintf('%s/%s', $path, $value);
}
break;
case 'query':
$this->querystring = $this->_parseRawQueryString($value);
break;
case 'fragment':
$this->anchor = $value;
break;
}
}
}
}
/**
* Returns full url
*
* @return string Full url
* @access public
*/
function getURL()
{
$querystring = $this->getQueryString();
$this->url = $this->protocol . '://'
. $this->user . (!empty($this->pass) ? ':' : '')
. $this->pass . (!empty($this->user) ? '@' : '')
. $this->host . ($this->port == $this->getStandardPort($this->protocol) ? '' : ':' . $this->port)
. $this->path
. (!empty($querystring) ? '?' . $querystring : '')
. (!empty($this->anchor) ? '#' . $this->anchor : '');
return $this->url;
}
/**
* Adds or updates a querystring item (URL parameter).
* Automatically encodes parameters with rawurlencode() if $preencoded
* is false.
* You can pass an array to $value, it gets mapped via [] in the URL if
* $this->useBrackets is activated.
*
* @param string $name Name of item
* @param string $value Value of item
* @param bool $preencoded Whether value is urlencoded or not, default = not
* @access public
*/
function addQueryString($name, $value, $preencoded = false)
{
if ($this->getOption('encode_query_keys')) {
$name = rawurlencode($name);
}
if ($preencoded) {
$this->querystring[$name] = $value;
} else {
$this->querystring[$name] = is_array($value) ? array_map('rawurlencode', $value): rawurlencode($value);
}
}
/**
* Removes a querystring item
*
* @param string $name Name of item
* @access public
*/
function removeQueryString($name)
{
if ($this->getOption('encode_query_keys')) {
$name = rawurlencode($name);
}
if (isset($this->querystring[$name])) {
unset($this->querystring[$name]);
}
}
/**
* Sets the querystring to literally what you supply
*
* @param string $querystring The querystring data. Should be of the format foo=bar&x=y etc
* @access public
*/
function addRawQueryString($querystring)
{
$this->querystring = $this->_parseRawQueryString($querystring);
}
/**
* Returns flat querystring
*
* @return string Querystring
* @access public
*/
function getQueryString()
{
if (!empty($this->querystring)) {
foreach ($this->querystring as $name => $value) {
// Encode var name
$name = rawurlencode($name);
if (is_array($value)) {
foreach ($value as $k => $v) {
$querystring[] = $this->useBrackets ? sprintf('%s[%s]=%s', $name, $k, $v) : ($name . '=' . $v);
}
} elseif (!is_null($value)) {
$querystring[] = $name . '=' . $value;
} else {
$querystring[] = $name;
}
}
$querystring = implode(ini_get('arg_separator.output'), $querystring);
} else {
$querystring = '';
}
return $querystring;
}
/**
* Parses raw querystring and returns an array of it
*
* @param string $querystring The querystring to parse
* @return array An array of the querystring data
* @access private
*/
function _parseRawQuerystring($querystring)
{
$parts = preg_split('/[' . preg_quote(ini_get('arg_separator.input'), '/') . ']/', $querystring, -1, PREG_SPLIT_NO_EMPTY);
$return = array();
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
$value = substr($part, strpos($part, '=') + 1);
$key = substr($part, 0, strpos($part, '='));
} else {
$value = null;
$key = $part;
}
if (!$this->getOption('encode_query_keys')) {
$key = rawurldecode($key);
}
if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
$key = $matches[1];
$idx = $matches[2];
// Ensure is an array
if (empty($return[$key]) || !is_array($return[$key])) {
$return[$key] = array();
}
// Add data
if ($idx === '') {
$return[$key][] = $value;
} else {
$return[$key][$idx] = $value;
}
} elseif (!$this->useBrackets AND !empty($return[$key])) {
$return[$key] = (array)$return[$key];
$return[$key][] = $value;
} else {
$return[$key] = $value;
}
}
return $return;
}
/**
* Resolves //, ../ and ./ from a path and returns
* the result. Eg:
*
* /foo/bar/../boo.php => /foo/boo.php
* /foo/bar/../../boo.php => /boo.php
* /foo/bar/.././/boo.php => /foo/boo.php
*
* This method can also be called statically.
*
* @param string $path URL path to resolve
* @return string The result
*/
function resolvePath($path)
{
$path = explode('/', str_replace('//', '/', $path));
for ($i=0; $i<count($path); $i++) {
if ($path[$i] == '.') {
unset($path[$i]);
$path = array_values($path);
$i--;
} elseif ($path[$i] == '..' AND ($i > 1 OR ($i == 1 AND $path[0] != '') ) ) {
unset($path[$i]);
unset($path[$i-1]);
$path = array_values($path);
$i -= 2;
} elseif ($path[$i] == '..' AND $i == 1 AND $path[0] == '') {
unset($path[$i]);
$path = array_values($path);
$i--;
} else {
continue;
}
}
return implode('/', $path);
}
/**
* Returns the standard port number for a protocol
*
* @param string $scheme The protocol to lookup
* @return integer Port number or NULL if no scheme matches
*
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
*/
function getStandardPort($scheme)
{
switch (strtolower($scheme)) {
case 'http': return 80;
case 'https': return 443;
case 'ftp': return 21;
case 'imap': return 143;
case 'imaps': return 993;
case 'pop3': return 110;
case 'pop3s': return 995;
default: return null;
}
}
/**
* Forces the URL to a particular protocol
*
* @param string $protocol Protocol to force the URL to
* @param integer $port Optional port (standard port is used by default)
*/
function setProtocol($protocol, $port = null)
{
$this->protocol = $protocol;
$this->port = is_null($port) ? $this->getStandardPort($protocol) : $port;
}
/**
* Set an option
*
* This function set an option
* to be used thorough the script.
*
* @access public
* @param string $optionName The optionname to set
* @param string $value The value of this option.
*/
function setOption($optionName, $value)
{
if (!array_key_exists($optionName, $this->options)) {
return false;
}
$this->options[$optionName] = $value;
$this->initialize();
}
/**
* Get an option
*
* This function gets an option
* from the $this->options array
* and return it's value.
*
* @access public
* @param string $opionName The name of the option to retrieve
* @see $this->options
*/
function getOption($optionName)
{
if (!isset($this->options[$optionName])) {
return false;
}
return $this->options[$optionName];
}
}
?>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,106 @@
<?php
/**
* Listener for HTTP_Request and HTTP_Response objects
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2002-2007, Richard Heyes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* o The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category HTTP
* @package HTTP_Request
* @author Alexey Borzov <avb@php.net>
* @copyright 2002-2007 Richard Heyes
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id: Listener.php,v 1.3 2007/05/18 10:33:31 avb Exp $
* @link http://pear.php.net/package/HTTP_Request/
*/
/**
* Listener for HTTP_Request and HTTP_Response objects
*
* This class implements the Observer part of a Subject-Observer
* design pattern.
*
* @category HTTP
* @package HTTP_Request
* @author Alexey Borzov <avb@php.net>
* @version Release: 1.4.4
*/
class HTTP_Request_Listener
{
/**
* A listener's identifier
* @var string
*/
var $_id;
/**
* Constructor, sets the object's identifier
*
* @access public
*/
function HTTP_Request_Listener()
{
$this->_id = md5(uniqid('http_request_', 1));
}
/**
* Returns the listener's identifier
*
* @access public
* @return string
*/
function getId()
{
return $this->_id;
}
/**
* This method is called when Listener is notified of an event
*
* @access public
* @param object an object the listener is attached to
* @param string Event name
* @param mixed Additional data
* @abstract
*/
function update(&$subject, $event, $data = null)
{
echo "Notified of event: '$event'\n";
if (null !== $data) {
echo "Additional data: ";
var_dump($data);
}
}
}
?>
File diff suppressed because one or more lines are too long
@@ -0,0 +1,37 @@
vtlib uses third party libraries to enable certain functionality.
1. For creating and unpacking zip files
-- ====================================
vtlib/thirdparty/dZip.php
vtlib/thirdparty/dUnzip2.inc.php
DOWNLOAD URL:
http://www.phpclasses.org/browse/package/2495/
BSD License: http://www.opensource.org/licenses/bsd-license.html
NOTE: Bug Fix was added to function addFile of dZip class.
2. For Feed Parsing
-- ===============
vtlib/thirdparty/parser/feed/simplepie.inc
DOWNLOAD URL: http://simplepie.org
BSD License: http://www.opensource.org/licenses/bsd-license.php
3. For HTTP Communication
-- ======================
Vtiger_Net_Client is based on the following:
http://pear.php.net/package/HTTP_Request
[License: http://www.opensource.org/licenses/bsd-license.php]
http://pear.php.net/package/Net_URL
[License: http://www.opensource.org/licenses/bsd-license.php]
http://pear.php.net/package/Net_Socket
[License: http://www.php.net/license/3_01.txt]
http://pear.php.net/package/PEAR (Only PEAR.php)
[License: http://www.php.net/license/3_01.txt]