diff --git a/oss/vtiger/trunk/modules/Accounts/AccountHierarchy.php b/oss/vtiger/trunk/modules/Accounts/AccountHierarchy.php new file mode 100644 index 00000000..b36a408f --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/AccountHierarchy.php @@ -0,0 +1,43 @@ +assign("CATEGORY",$parent_tab); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); + +$check_button = Button_Check($currentModule); +$check_button['Import'] = 'no'; +$check_button['Export'] = 'no'; +$check_button['moduleSettings'] = 'no'; +$smarty->assign("CHECK", $check_button); + +$focus = CRMEntity::getInstance($currentModule); +$accountid = vtlib_purify($_REQUEST['accountid']); +if (!empty($accountid)) { + $hierarchy = $focus->getAccountHierarchy($accountid); +} +$smarty->assign("ACCOUNT_HIERARCHY",$hierarchy); +$smarty->display("AccountHierarchy.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/Accounts.js b/oss/vtiger/trunk/modules/Accounts/Accounts.js new file mode 100644 index 00000000..f2a3d1b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/Accounts.js @@ -0,0 +1,414 @@ +/********************************************************************************* + +** 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. + ********************************************************************************/ + + +document.write(""; +// mailer_export +if (isset($other_text['mailer_exp'])) +{ + $view_script .= ""; +} +// end of mailer export +if(isset($order_by) && $order_by != '') +{ + if($order_by == 'smownerid') + { + if( $adb->dbType == "pgsql") + $query .= ' GROUP BY user_name'; + $query .= ' ORDER BY user_name '.$sorder; + } + else + { + $tablename = getTableNameForField('Accounts',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if( $adb->dbType == "pgsql") + $query .= ' GROUP BY '.$tablename.$order_by; + + $query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } +} + + + +//Postgres 8 fixes +if( $adb->dbType == "pgsql") + $query = fixPostgresQuery( $query, $log, 0); + +if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true){ + $count_result = $adb->query( mkCountQuery( $query)); + $noofrows = $adb->query_result($count_result,0,"count"); +}else{ + $noofrows = null; +} + +$queryMode = (isset($_REQUEST['query']) && $_REQUEST['query'] == 'true'); +$start = ListViewSession::getRequestCurrentPage($currentModule, $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($query. " OFFSET $limit_start_rec LIMIT $list_max_entries_per_page", array()); +else + $list_result = $adb->pquery($query. " LIMIT $limit_start_rec, $list_max_entries_per_page", array()); + +$recordListRangeMsg = getRecordRangeMessage($list_result, $limit_start_rec); +$smarty->assign('recordListRange',$recordListRangeMsg); + +//mass merge for word templates -- *Raj*17/11 +while($row = $adb->fetch_array($list_result)) +{ + $ids[] = $row["crmid"]; +} +if(isset($ids)) +{ + $smarty->assign("ALLIDS", implode($ids,";")); +} +if(isPermitted("Accounts","Merge") == 'yes') +{ + $wordTemplateResult = fetchWordTemplateList("Accounts"); + $tempCount = $adb->num_rows($wordTemplateResult); + $tempVal = $adb->fetch_array($wordTemplateResult); + for($templateCount=0;$templateCount<$tempCount;$templateCount++) + { + $optionString .=""; + $tempVal = $adb->fetch_array($wordTemplateResult); + } + if($tempCount > 0) + { + $smarty->assign("WORDTEMPLATEOPTIONS","".$app_strings['LBL_SELECT_TEMPLATE_TO_MAIL_MERGE'].""); + + $smarty->assign("MERGEBUTTON",""); + } + else + { + global $current_user; + require("user_privileges/user_privileges_".$current_user->id.".php"); + if($is_admin == true) + { + $smarty->assign("MERGEBUTTON",''. $app_strings["LBL_CREATE_MERGE_TEMPLATE"].''); + } + } +} + +//mass merge for word templates + +//Retreive the List View Table Header +if($viewid !='') +$url_string .= "&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"Accounts",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search=getSearchListHeaderValues($focus,"Accounts",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER", $listview_header_search); + +$listview_entries = getListViewEntries($focus,"Accounts",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); + +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("AVALABLE_FIELDS", getMergeFields($currentModule,"available_fields")); +$smarty->assign("FIELDS_TO_MERGE", getMergeFields($currentModule,"fileds_to_merge")); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Accounts","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','accountname','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($currentModule); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); + +$check_button = Button_Check($currentModule); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Accounts/ListViewPagging.php b/oss/vtiger/trunk/modules/Accounts/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/ListViewTop.php b/oss/vtiger/trunk/modules/Accounts/ListViewTop.php new file mode 100644 index 00000000..ce37c5de --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/ListViewTop.php @@ -0,0 +1,107 @@ +$title,'Header'=>$listview_header,'Entries'=>$listview_entries) where as listview_header and listview_entries are arrays of header and entity values which are returned from function getListViewHeader and getListViewEntries +*/ +function getTopAccounts($maxval,$calCnt) +{ + $log = LoggerManager::getLogger('top accounts_list'); + $log->debug("Entering getTopAccounts() method ..."); + require_once("data/Tracker.php"); + require_once('modules/Potentials/Potentials.php'); + require_once('include/logging.php'); + require_once('include/ListView/ListView.php'); + global $app_strings; + global $adb; + global $current_language; + global $current_user; + $current_module_strings = return_module_language($current_language, "Accounts"); + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + $list_query = "select vtiger_account.accountid, vtiger_account.accountname, vtiger_account.tickersymbol, sum(vtiger_potential.amount) as amount from vtiger_potential inner join vtiger_crmentity on (vtiger_potential.potentialid=vtiger_crmentity.crmid) left join vtiger_account on (vtiger_potential.related_to=vtiger_account.accountid) left join vtiger_groups on (vtiger_groups.groupid = vtiger_crmentity.smownerid) where vtiger_crmentity.deleted=0 AND vtiger_crmentity.smownerid='".$current_user->id."' and vtiger_potential.sales_stage not in ('Closed Won', 'Closed Lost','".$app_strings['LBL_CLOSE_WON']."','".$app_strings['LBL_CLOSE_LOST']."')"; + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[6] == 3) + { + $sec_parameter=getListViewSecurityParameter('Accounts'); + $list_query .= $sec_parameter; + + } + $list_query .= " group by vtiger_account.accountid, vtiger_account.accountname, vtiger_account.tickersymbol order by amount desc"; + + $list_query .= " LIMIT 0," . $adb->sql_escape_string($maxval); + + if($calCnt == 'calculateCnt') { + $list_result_rows = $adb->query(mkCountQuery($list_query)); + return $adb->query_result($list_result_rows, 0, 'count'); + } + + $list_result=$adb->query($list_query); + $open_accounts_list = array(); + $noofrows = $adb->num_rows($list_result); + + if ($noofrows) { + for($i=0;$i<$noofrows;$i++) + { + $open_accounts_list[] = Array('accountid' => $adb->query_result($list_result,$i,'accountid'), + 'accountname' => $adb->query_result($list_result,$i,'accountname'), + 'amount' => $adb->query_result($list_result,$i,'amount'), + 'tickersymbol' => $adb->query_result($list_result,$i,'tickersymbol'), + ); + } + } + + $title=array(); + $title[]='myTopAccounts.gif'; + $title[]=$current_module_strings['LBL_TOP_ACCOUNTS']; + $title[]='home_myaccount'; + + $header=array(); + $header[]=$current_module_strings['LBL_LIST_ACCOUNT_NAME']; + $currencyid=fetchCurrency($current_user->id); + $rate_symbol = getCurrencySymbolandCRate($currencyid); + $rate = $rate_symbol['rate']; + $curr_symbol = $rate_symbol['symbol']; + $header[]=$current_module_strings['LBL_LIST_AMOUNT'].'('.$curr_symbol.')'; + + $entries=array(); + foreach($open_accounts_list as $account) + { + $value=array(); + $account_fields = array( + 'ACCOUNT_ID' => $account['accountid'], + 'ACCOUNT_NAME' => $account['accountname'], + 'AMOUNT' => ($account['amount']), + ); + + $Top_Accounts = (strlen($account['accountname']) > 20) ? (substr($account['accountname'],0,20).'...') : $account['accountname']; + $value[]=''.$Top_Accounts.''; + $value[]=convertFromDollar($account['amount'],$rate); + $entries[$account['accountid']]=$value; + } + $values=Array('ModuleName'=>'Accounts','Title'=>$title,'Header'=>$header,'Entries'=>$entries); + $log->debug("Exiting getTopAccounts method ..."); + if (($display_empty_home_blocks && count($entries) == 0 ) || (count($entries)>0)) + return $values; +} +?> diff --git a/oss/vtiger/trunk/modules/Accounts/MailerExport.php b/oss/vtiger/trunk/modules/Accounts/MailerExport.php new file mode 100644 index 00000000..c44c1e8e --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/MailerExport.php @@ -0,0 +1,325 @@ +query ($query,true,"Error: "."
$query"); + for ($tmp=0; $tmp < $adb->num_rows($result); $tmp++) + { + $myData = $adb->fetchByAssoc ($result); + $queryFields[] = Array('columnname'=>$myData['columnname'] + ,'uitype'=>'56','fieldlabel'=>$mod_strings[$myData['fieldlabel']] + ,'value'=> $valueArray); + } +} + +if ($step == "ask") +{ + require_once('config.php'); + require_once('include/database/PearDatabase.php'); + require_once('Smarty_setup.php'); + $smarty = new vtigerCRM_Smarty; + $valueArray = Array('' => $mod_strings['LBL_MAILER_EXPORT_IGNORE'], + '0' => $mod_strings['LBL_MAILER_EXPORT_NOTCHECKED'], + '1' => $mod_strings['LBL_MAILER_EXPORT_CHECKED']); + + $smarty->assign("MOD", return_module_language($current_language,'Accounts')); + $smarty->assign("CMOD", $mod_strings); + $smarty->assign("APP", $app_strings); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE",$currentModule); + $smarty->assign("EXPORTWHERE",$exportWhere); + $queryFields = Array(); + // get the Contacts CF fields + $cfquery = "SELECT columnname,fieldlabel,uitype FROM vtiger_field WHERE tablename='vtiger_contactscf' and vtiger_field.presence in (0,2)"; + $result = $adb->query ($cfquery,true,"Error: "."
$cfquery"); + for ($tmp=0; $tmp < $adb->num_rows($result); $tmp++) + { + $cfTmp = $adb->fetchByAssoc ($result); + $cfColName=$cfTmp['columnname']; + if ($cfTmp['uitype'] == 1) + $queryFields[$tmp] = $cfTmp; + elseif ($cfTmp['uitype'] == 15) + { + $queryFields[$tmp] = $cfTmp; + $queryFields[$tmp]['value'][''] = $mod_strings['LBL_MAILER_EXPORT_IGNORE']; + $cfValues = "SELECT ".$cfColName.",".$cfColName."id FROM vtiger_".$cfColName; + $resVal = $adb->query ($cfValues,true,"Error: "."
$cfValues"); + for ($tmp1=0; $tmp1 < $adb->num_rows($resVal); $tmp1++) + { + $cfTmp=$adb->fetchByAssoc ($resVal); + $queryFields[$tmp]['value'][$cfTmp[$cfColName]] = $cfTmp[$cfColName]; + } + } + elseif ($cfTmp['uitype'] == 56) + { + $queryFields[$tmp] = $cfTmp; + $queryFields[$tmp]['value'] = $valueArray; + } + } + // now add the standard fields + getStdContactFlds(&$queryFields, $adb, $valueArray); + // get the list of fields + $fieldList=""; + foreach ($queryFields as $myField) + { + if (strlen($fieldList) > 0) + $fieldList .= ','; + $fieldList .= $myField['columnname']; + } + $smarty->assign("FIELDLIST",$fieldList); + // and their types + $typeList =""; + foreach ($queryFields as $myField) + { + if (strlen($typeList) > 0) + $typeList .= ','; + $typeList .= $myField['uitype']; + } + + $smarty->assign("TYPELIST",$typeList); + $smarty->assign("QUERYFIELDS",$queryFields); + $smarty->assign("CATEGORY",$category); + $smarty->display('MailerExport.tpl'); + + +} +else +{ + require_once('../../config.php'); + chdir ($root_directory); + require_once("include/utils/CommonUtils.php"); + require_once('include/database/PearDatabase.php'); + require_once('include/logging.php'); + $exquery = Array(); + $fields = explode(",",$_POST['fieldlist']); + $types = explode(",",$_POST['typelist']); + $escapxportWhere = $adb->sql_escape_string($exportWhere); + if (($export_type == "email") || ($export_type == "emailplus") ) + { + + $where = ""; + + if(count($fields) > 0) + $where .= getExpWhereClause($fields,$types); + $exquery[0] = "SELECT crmentity.crmid, contactdetails.contactid, + contactdetails.salutation, contactdetails.firstname, + contactdetails.lastname, contactdetails.email FROM vtiger_account + INNER JOIN vtiger_crmentity crmentity on crmentity.crmid=vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid=vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid=vtiger_accountshipads.accountaddressid + INNER JOIN vtiger_accountscf ON vtiger_account.accountid = vtiger_accountscf.accountid + INNER JOIN vtiger_contactdetails contactdetails ON vtiger_account.accountid = contactdetails.accountid + INNER JOIN vtiger_contactscf contactscf ON contactscf.contactid = contactdetails.contactid + WHERE crmentity.deleted=0 AND contactdetails.email != '' ".$where; + + if (strlen ($exportWhere)) + $exquery[0] .= " AND ".$exportWhere; + + if ($export_type == "emailplus") + { + $exquery[1] = "SELECT crmentity.crmid, contactdetails.contactid, + contactdetails.salutation, contactdetails.firstname, + contactdetails.lastname, vtiger_account.email1 FROM vtiger_account + INNER JOIN vtiger_crmentity crmentity ON crmentity.crmid=vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid=vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid=vtiger_accountshipads.accountaddressid + INNER JOIN vtiger_accountscf ON vtiger_account.accountid = vtiger_accountscf.accountid + INNER JOIN vtiger_contactdetails contactdetails ON vtiger_account.accountid = contactdetails.accountid + INNER JOIN vtiger_contactscf contactscf ON contactscf.contactid = contactdetails.contactid + WHERE crmentity.deleted=0 + AND contactdetails.email = '' AND vtiger_account.email1 != '' ".$where; + + if (strlen ($exportWhere)) + $exquery[1] .= " AND ".$exportWhere; + } + } + else if ($export_type == "full") + { + $where = ''; + if(count($fields) > 0) + $where .= getExpWhereClause($fields,$types); + $exquery[0] = "select crmentity.crmid, contactdetails.contactid, + contactdetails.salutation, contactdetails.firstname, + contactdetails.lastname, contactdetails.email, vtiger_account.accountname," + ." vtiger_account.phone, vtiger_account.website, vtiger_accountshipads.ship_street," + ." vtiger_accountshipads.ship_code," + ." vtiger_accountshipads.ship_city, vtiger_accountshipads.ship_state," + ." vtiger_accountshipads.ship_country," + ." vtiger_accountbillads.bill_street, vtiger_accountbillads.bill_code," + ." vtiger_accountbillads.bill_city, vtiger_accountbillads.bill_state," + ." vtiger_accountbillads.bill_country" + ." FROM vtiger_account INNER JOIN vtiger_crmentity crmentity ON crmentity.crmid=vtiger_account.accountid" + ." LEFT JOIN vtiger_accountbillads ON vtiger_account.accountid=vtiger_accountbillads.accountaddressid" + ." LEFT JOIN vtiger_accountshipads ON vtiger_account.accountid=vtiger_accountshipads.accountaddressid" + ." INNER JOIN vtiger_accountscf ON vtiger_account.accountid = vtiger_accountscf.accountid" + ." INNER JOIN vtiger_contactdetails contactdetails ON vtiger_account.accountid = contactdetails.accountid" + ." INNER JOIN vtiger_contactscf contactscf ON contactscf.contactid = contactdetails.contactid" + ." WHERE crmentity.deleted=0 ".$where; + + if (strlen ($exportWhere)) + $exquery[0] .= " AND ".$exportWhere; + } + // Added for getting field labels of the fields selected in the above export queries. If any new fields added in the select clause then the below array need to be updated with the corresponding lablels + $fld_label_arr = Array("salutation"=>getTranslatedString('Salutation','Contacts'), + "lastname"=>getTranslatedString('Last Name','Contacts'), + "firstname"=>getTranslatedString('First Name','Contacts'), + "email"=>getTranslatedString('Email','Contacts'), + "accountname"=>getTranslatedString('Account Name','Accounts'), + "phone"=>getTranslatedString('Phone','Accounts'), + "website"=>getTranslatedString('Website','Accounts'), + "ship_street"=>getTranslatedString('Shipping Address','Accounts'), + "ship_code"=>getTranslatedString('Shipping Code','Accounts'), + "ship_city"=>getTranslatedString('Shipping City','Accounts'), + "ship_state"=>getTranslatedString('Shipping State','Accounts'), + "ship_country"=>getTranslatedString('Shipping Country','Accounts'), + "bill_street"=>getTranslatedString('Billing Address','Accounts'), + "bill_code"=>getTranslatedString('Billing Code','Accounts'), + "bill_city"=>getTranslatedString('Billing City','Accounts'), + "bill_state"=>getTranslatedString('Billing State','Accounts'), + "bill_country"=>getTranslatedString('Billing Country','Accounts') + ); + + for ($temp = 0; $temp < count($exquery); $temp++) + { + $result = $adb->query ($exquery[$temp],true,"Error exporting: "."
$query"); + if ($temp == 0) // We only need the headers for first query + { + $fields_array = $adb->getFieldsArray($result); + // Now walk through the array and replace any cf_* with the content of the + // name array, the index is the cf_ var name + for ($arraywalk = 0; $arraywalk < count($fields_array); $arraywalk++) + { + // echo "Checking: ".$fields_array[$arraywalk]; + if (strstr ($fields_array[$arraywalk], "vtiger_cf_")) + { + $fields_array[$arraywalk] = $name[$fields_array[$arraywalk]]; + // echo "Changing to: ".$fields_array[$arraywalk]; + } + else + $fields_array[$arraywalk] = ($fld_label_arr[$fields_array[$arraywalk]]!='')?$fld_label_arr[$fields_array[$arraywalk]]:$fields_array[$arraywalk]; + } + + + $header = implode("\",\"",array_values($fields_array)); + $header = "\"" .$header; + $header .= "\"\r\n"; + $content .= $header; + + $column_list = implode(",",array_values($fields_array)); + } + + while($val = $adb->fetchByAssoc($result, -1, false)) + { + $new_arr = array(); + + // foreach (array_values($val) as $value) + foreach ($val as $key => $value) + { + $value=br2nl_int($value); + array_push($new_arr, preg_replace("/\"/","\"\"",$value)); + } + + $line = implode("\",\"",$new_arr); + $line = "\"" .$line; + $line .= "\"\r\n"; + + $content .= $line; + } + } + + // echo "
Rows: ".$adb->num_rows($result); + header( "Content-Disposition: inline; filename=MailerExport.csv"); + header( "Content-Type: text/csv; charset=".$app_strings['LBL_CHARSET']); + header( "Expires: Mon, 26 Jul 2007 05:00:00 GMT" ); + header( "Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" ); + header( "Cache-Control: post-check=0, pre-check=0", false ); + header( "Content-Length: ".strlen($content)); + print $content; + exit (); + +} + +function getExpWhereClause($fields,$types) +{ + global $adb; + $where_cond = ""; + + foreach ($fields as $myField) + { + $myType = each($types); + if (strlen($_POST[$myField]) > 0) + { + // type 1 should use a LIKE search + if ($myType['value'] == 1) + { + $equals = " LIKE '"; + $postfix = "%'"; + } + else + { + $equals = " = '"; + $postfix = "'"; + } + // is customer field + if (substr($myField,0,3) == 'cf_') + $where_cond .= " AND contactscf.".$myField.$equals.$adb->sql_escape_string($_POST[$myField]).$postfix; + else + $where_cond .= " AND contactdetails.".$myField.$equals.$adb->sql_escape_string($_POST[$myField]).$postfix; + } + } + return $where_cond; + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/MassEdit.php b/oss/vtiger/trunk/modules/Accounts/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/MassEditSave.php b/oss/vtiger/trunk/modules/Accounts/MassEditSave.php new file mode 100644 index 00000000..0e1f2a6f --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/Merge.php b/oss/vtiger/trunk/modules/Accounts/Merge.php new file mode 100644 index 00000000..563b4dbc --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/Merge.php @@ -0,0 +1,298 @@ + + + + +pquery($sql, array($templateid)); +$temparray = $adb->fetch_array($result); + +$fileContent = $temparray['data']; +$filename=html_entity_decode($temparray['filename'], ENT_QUOTES, $default_charset); +// Fix For: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$filename= $randomfilename . "_word.doc"; + +$filesize=$temparray['filesize']; +$wordtemplatedownloadpath =$root_directory ."/test/wordtemplatedownload/"; + +$handle = fopen($wordtemplatedownloadpath.$filename,"wb"); +fwrite($handle,base64_decode($fileContent),$filesize); +fclose($handle); + +//<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>> +$mass_merge = $_REQUEST['allselectedboxes']; +$single_record = $_REQUEST['record']; + +if($mass_merge != "") +{ + $mass_merge = explode(";",$mass_merge); + $temp_mass_merge = $mass_merge; + if(array_pop($temp_mass_merge)=="") + array_pop($mass_merge); + //$mass_merge = implode(",",$mass_merge); +}else if($single_record != "") +{ + $mass_merge = $single_record; +}else +{ + die("Record Id is not found, cannot merge the document"); +} + +//echo $mass_merge; +//die; +//for setting vtiger_accountid=0 for the contacts which are deleted +$ct_query = "select crmid from vtiger_crmentity where setype='Contacts' and deleted=1"; +$result = $adb->pquery($ct_query, array()); + +while($row = $adb->fetch_array($result)) +{ + $deleted_id[] = $row['crmid']; +} + +if(count($deleted_id) > 0) +{ + $update_query = "update vtiger_contactdetails set accountid = 0 where contactid in (". generateQuestionMarks($deleted_id) .")"; + $result = $adb->pquery($update_query, array($deleted_id)); +} +//End setting vtiger_accountid=0 for the contacts which are deleted + +//<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>> +global $current_user; +require('user_privileges/user_privileges_'.$current_user->id.'.php'); +if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users" || $module == "Emails") +{ + $query1="select vtiger_tab.name,vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where vtiger_field.tabid in (4,6) and vtiger_field.block <> 75 and vtiger_field.presence in (0,2) order by vtiger_field.tablename"; + $params1 = array(); +} +else +{ + $profileList = getCurrentUserProfileList(); + $query1="select vtiger_tab.name,vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid in (4,6) and vtiger_field.block <> 75 AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid order by vtiger_field.tablename"; + $params1 = array($profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query1 = fixPostgresQuery( $query1, $log, 0); +} + +$result = $adb->pquery($query1, $params1); +$y=$adb->num_rows($result); + +for ($x=0; $x<$y; $x++) +{ + $tablename = $adb->query_result($result,$x,"tablename"); + $columnname = $adb->query_result($result,$x,"columnname"); + $modulename = $adb->query_result($result,$x,"name"); + + if($tablename == "crmentity") + { + if($modulename == "Contacts") + { + $tablename = "vtiger_crmentityContacts"; + } + } + $querycolumns[$x] = $tablename.".".$columnname; + if($columnname == "smownerid") + { + if($modulename == "Accounts") + { + $querycolumns[$x] = "case when (vtiger_users.user_name not like '') then concat(vtiger_users.last_name,' ',vtiger_users.first_name) else vtiger_groups.groupname end as userjoinname,vtiger_users.first_name,vtiger_users.last_name,vtiger_users.user_name,vtiger_users.yahoo_id,vtiger_users.title,vtiger_users.phone_work,vtiger_users.department,vtiger_users.phone_mobile,vtiger_users.phone_other,vtiger_users.phone_fax,vtiger_users.email1,vtiger_users.phone_home,vtiger_users.email2,vtiger_users.address_street,vtiger_users.address_city,vtiger_users.address_state,vtiger_users.address_postalcode,vtiger_users.address_country"; + } + if($modulename == "Contacts") + { + $querycolumns[$x] = "case when (usersContacts.user_name not like '') then concat(usersContacts.last_name,' ',usersContacts.first_name) else groupsContacts.groupname end as userjoincname"; + } + } + if($columnname == "parentid") + { + $querycolumns[$x] = "vtiger_accountAccount.accountname"; + } + if($columnname == "accountid") + { + $querycolumns[$x] = "vtiger_accountContacts.accountname"; + } + if($columnname == "reportsto") + { + $querycolumns[$x] = "vtiger_contactdetailsContacts.lastname"; + } + + if($modulename == "Accounts") + { + $field_label[$x] = "ACCOUNT_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + if($columnname == "smownerid") + { + $field_label[$x] = $field_label[$x].",USER_FIRSTNAME,USER_LASTNAME,USER_USERNAME,USER_YAHOOID,USER_TITLE,USER_OFFICEPHONE,USER_DEPARTMENT,USER_MOBILE,USER_OTHERPHONE,USER_FAX,USER_EMAIL,USER_HOMEPHONE,USER_OTHEREMAIL,USER_PRIMARYADDRESS,USER_CITY,USER_STATE,USER_POSTALCODE,USER_COUNTRY"; + } + } + + if($modulename == "Contacts") + { + $field_label[$x] = "CONTACT_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + } + +} + +$csvheader = implode(",",$field_label); +//<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>> + +if(count($querycolumns) > 0) +{ + $selectcolumns = implode($querycolumns,","); + + $query = "select $selectcolumns from vtiger_account + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid + inner join vtiger_accountbillads on vtiger_account.accountid=vtiger_accountbillads.accountaddressid + inner join vtiger_accountshipads on vtiger_account.accountid=vtiger_accountshipads.accountaddressid + inner join vtiger_accountscf on vtiger_account.accountid = vtiger_accountscf.accountid + left join vtiger_account as vtiger_accountAccount on vtiger_accountAccount.accountid = vtiger_account.parentid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_contactdetails on vtiger_contactdetails.accountid=vtiger_account.accountid + left join vtiger_crmentity as vtiger_crmentityContacts on vtiger_crmentityContacts.crmid = vtiger_contactdetails.contactid + left join vtiger_contactaddress on vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + left join vtiger_contactsubdetails on vtiger_contactdetails.contactid = vtiger_contactsubdetails.contactsubscriptionid + left join vtiger_contactscf on vtiger_contactdetails.contactid = vtiger_contactscf.contactid + left join vtiger_customerdetails on vtiger_contactdetails.contactid = vtiger_customerdetails.customerid + left join vtiger_contactdetails as vtiger_contactdetailsContacts on vtiger_contactdetailsContacts.contactid = vtiger_contactdetails.reportsto + left join vtiger_account as vtiger_accountContacts on vtiger_accountContacts.accountid = vtiger_contactdetails.accountid + left join vtiger_users as usersContacts on usersContacts.id = vtiger_crmentityContacts.smownerid + LEFT JOIN vtiger_groups as groupsContacts + ON groupsContacts.groupid = vtiger_crmentity.smownerid + where vtiger_crmentity.deleted=0 and (vtiger_crmentityContacts.deleted=0 || vtiger_crmentityContacts.deleted is null) and vtiger_account.accountid in(". generateQuestionMarks($mass_merge) .")"; + //echo $query; + //die; + $result = $adb->pquery($query, array($mass_merge)); +$avail_pick_arr = getAccessPickListValues('Accounts'); +while($columnValues = $adb->fetch_array($result)) +{ + $y=$adb->num_fields($result); + for($x=0; $x<$y; $x++) + { + $value = $columnValues[$x]; + foreach($columnValues as $key=>$val) + { + if($val == $value && $value != '') + { + if(array_key_exists($key,$avail_pick_arr)) + { + if(!in_array($val,$avail_pick_arr[$key])) + { + $value = "Not Accessible"; + } + } + } + } + //<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>> + if(trim($value) == "--None--" || trim($value) == "--none--") + { + $value = ""; + } + //<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>> + $actual_values[$x] = $value; + $actual_values[$x] = str_replace('"'," ",$actual_values[$x]); + //if value contains any line feed or carriage return replace the value with ".value." + if (preg_match ("/(\r\n)/", $actual_values[$x])) + { + $actual_values[$x] = '"'.$actual_values[$x].'"'; + } + $actual_values[$x] = decode_html(str_replace(","," ",$actual_values[$x])); + } + $mergevalue[] = implode($actual_values,","); +} +$csvdata = implode($mergevalue,"###"); +}else +{ + die("No fields to do Merge"); +} + +// Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$datafilename = $randomfilename . "_data.csv"; + +$handle = fopen($wordtemplatedownloadpath.$datafilename,"wb"); +fwrite($handle,$csvheader."\r\n"); +fwrite($handle,str_replace("###","\r\n",$csvdata)); +fclose($handle); +?> + + + diff --git a/oss/vtiger/trunk/modules/Accounts/Popup.php b/oss/vtiger/trunk/modules/Accounts/Popup.php new file mode 100644 index 00000000..eb0e6e50 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/Popup.php @@ -0,0 +1,16 @@ + diff --git a/oss/vtiger/trunk/modules/Accounts/ProcessDuplicates.php b/oss/vtiger/trunk/modules/Accounts/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Accounts/QuickCreate.php b/oss/vtiger/trunk/modules/Accounts/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Accounts/Save.php b/oss/vtiger/trunk/modules/Accounts/Save.php new file mode 100644 index 00000000..9b03c92c --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/Save.php @@ -0,0 +1,217 @@ +pquery($query, $params); + if($adb->num_rows($result) > 0) + { + echo $mod_strings['LBL_ACCOUNT_EXIST']; + } + else + { + echo 'SUCCESS'; + } + die; +} +//Ended + +$local_log =& LoggerManager::getLogger('index'); +global $log; +$focus = new Accounts(); +global $current_user; +$currencyid=fetchCurrency($current_user->id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; +$curr_symbol = $rate_symbol['symbol']; +if(isset($_REQUEST['record'])) +{ + $focus->id = $_REQUEST['record']; +$log->info("id is ".$focus->id); +} +if(isset($_REQUEST['mode'])) +{ + $focus->mode = $_REQUEST['mode']; +} + +foreach($focus->column_fields as $fieldname => $val) +{ + if(isset($_REQUEST[$fieldname])) + { + if(is_array($_REQUEST[$fieldname])) + $value = $_REQUEST[$fieldname]; + else + $value = trim($_REQUEST[$fieldname]); + $log->DEBUG($fieldname."=Field Name &first& Value =".$value); + $focus->column_fields[$fieldname] = $value; + } +} + +if(isset($_REQUEST['annual_revenue'])) +{ + $value = convertToDollar($_REQUEST['annual_revenue'],$rate); + $focus->column_fields['annual_revenue'] = $value; +} + +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']; +} + +//When changing the Account Address Information it should also change the related contact address - dina +if($focus->mode == 'edit' && $_REQUEST['address_change'] == 'yes') +{ + $query = "update vtiger_contactaddress set mailingcity=?,mailingstreet=?,mailingcountry=?,mailingzip=?,mailingpobox=?,mailingstate=?,othercountry=?,othercity=?,otherstate=?,otherzip=?,otherstreet=?,otherpobox=? where contactaddressid in (select contactid from vtiger_contactdetails where accountid=?)" ; + $params = array($focus->column_fields['bill_city'], $focus->column_fields['bill_street'], $focus->column_fields['bill_country'], + $focus->column_fields['bill_code'], $focus->column_fields['bill_pobox'], $focus->column_fields['bill_state'], $focus->column_fields['ship_country'], + $focus->column_fields['ship_city'], $focus->column_fields['ship_state'], $focus->column_fields['ship_code'], $focus->column_fields['ship_street'], + $focus->column_fields['ship_pobox'], $focus->id); + $adb->pquery($query, $params); +} +//Changing account address - Ends + +$focus->save("Accounts"); +$return_id = $focus->id; + +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Accounts"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +$local_log->debug("Saved record with id of ".$return_id); + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + +//Send notification mail to the assigned to owner about the vtiger_account creation +if($focus->column_fields['notify_owner'] == 1 || $focus->column_fields['notify_owner'] == 'on') + $status = sendNotificationToOwner('Accounts',$focus); + +header("Location: index.php?action=$return_action&module=$return_module&parenttab=$parenttab&record=$return_id&viewname=$return_viewname&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +/** Function to save Accounts custom field info into database +* @param integer $entity_id - accountid +*/ +function save_customfields($entity_id) +{ + global $log; + $log->debug("Entering save_customfields(".$entity_id.") method ..."); + $log->info("save customfields invoked"); + global $adb; + $dbquery = "SELECT * FROM customfields WHERE module = 'Accounts'"; + $result = $adb->pquery($dbquery, array()); + + $custquery = "SELECT * FROM vtiger_accountcf WHERE vtiger_accountid = ?"; + $cust_result = $adb->pquery($custquery, array($entity_id)); + if($adb->num_rows($result) != 0) + { + + $columns=''; + $values=''; + $ins_params = array(); + $update=''; + $upd_params = array(); + + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $fldName=$adb->query_result($result,$i,"fieldlabel"); + $colName=$adb->query_result($result,$i,"column_name"); + if(isset($_REQUEST[$colName])) + { + $fldvalue=$_REQUEST[$colName]; + if(get_magic_quotes_gpc() == 1) + { + $fldvalue = stripslashes($fldvalue); + } + } + else + { + $fldvalue = ''; + } + + if(isset($_REQUEST['record']) && $_REQUEST['record'] != '' && $adb->num_rows($cust_result) !=0) + { + //Update Block + if($i == 0) + { + $update = $colName."=?"; + array_push($upd_params, $fldvalue); + } + else + { + $update .= ', '.$colName."=?"; + array_push($upd_params, $fldvalue); + } + } + else + { + //Insert Block + if($i == 0) + { + $columns='accountid, '.$colName; + array_push($ins_params, $entity_id, $fldvalue); + } + else + { + $columns .= ', '.$colName; + array_push($ins_params, $fldvalue); + } + } + } + if(isset($_REQUEST['record']) && $_REQUEST['record'] != '' && $adb->num_rows($cust_result) !=0) + { + //Update Block + $query = "UPDATE vtiger_accountcf SET $update WHERE vtiger_accountid=?"; + array_push($upd_params, $entity_id); + $adb->pquery($query, $upd_params); + } + else + { + //Insert Block + $query = "INSERT INTO vtiger_accountcf ($columns) VALUES(" . generateQuestionMarks($ins_params) .")"; + $adb->pquery($query, $ins_params); + } + + } + $log->debug("Exiting save_customfields method ..."); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/Settings.php b/oss/vtiger/trunk/modules/Accounts/Settings.php new file mode 100644 index 00000000..48a80c0b --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/Settings.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/TagCloud.php b/oss/vtiger/trunk/modules/Accounts/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Accounts/Tickerdetail.php b/oss/vtiger/trunk/modules/Accounts/Tickerdetail.php new file mode 100644 index 00000000..2577bdd6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/Tickerdetail.php @@ -0,0 +1,100 @@ + + Company Report + +
+
+ + + + + + + + + '; + $output .=''; + $output .= ' + +
'.$comp.'
'; + $output .='
'; + foreach($first_array as $arr => $val) + { + $output .= ''; + for($j=0;$j + '; + } + $output .= ''; + } + $output .='
'.$val[$j+1].'
'; + array_shift($second_array[0]); + array_shift($second_array[0]); + foreach($second_array as $arr => $val) + { + $output .= ''; + for($j=0;$j + '; + } + $output .= ''; + } + $output .='
'.$val[$j+1].'
[Chart]
 
'; + $output .= ' + + + + + + + + +
BUSINESS SUMMARY
+
+ + +
+
+
+ '; +echo $output; +} +else +{ + $output = ''; + $output .= "
"; + $output .= "".$data.""; + $output .= "
"; + echo $output; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/UnifiedSearch.php b/oss/vtiger/trunk/modules/Accounts/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Accounts/index.php b/oss/vtiger/trunk/modules/Accounts/index.php new file mode 100644 index 00000000..87ea1151 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/index.php @@ -0,0 +1,57 @@ + + diff --git a/oss/vtiger/trunk/modules/Accounts/language/en_us.lang.php b/oss/vtiger/trunk/modules/Accounts/language/en_us.lang.php new file mode 100644 index 00000000..1468183c --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/language/en_us.lang.php @@ -0,0 +1,242 @@ +'Accounts', +'LBL_MODULE_TITLE'=>'Accounts: Home', +'LBL_SEARCH_FORM_TITLE'=>'Account Search', +'LBL_LIST_FORM_TITLE'=>'Account List', +'LBL_NEW_FORM_TITLE'=>'New Account', +'LBL_MEMBER_ORG_FORM_TITLE'=>'Member Organizations', +// Label for Top Accounts in Home Page, added for 4.2 GA +'LBL_TOP_ACCOUNTS'=>'My Top Accounts', +'LBL_TOP_AMOUNT'=>'Amount', +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_LIST_CITY'=>'City', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_STATE'=>'State', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_EMAIL_ADDRESS'=>'Email Address', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', +'LBL_LIST_AMOUNT' => 'Total Amount', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'Account:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_PHONE'=>'Phone:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_TICKER_SYMBOL'=>'Ticker Symbol:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_MEMBER_OF'=>'Member of:', +'LBL_EMAIL'=>'Email:', +'LBL_EMPLOYEES'=>'Employees:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_OWNERSHIP'=>'Ownership:', +'LBL_RATING'=>'Rating:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_SIC_CODE'=>'SIC Code:', +'LBL_TYPE'=>'Type:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_ACCOUNT_INFORMATION'=>'Account Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_BILLING_ADDRESS'=>'Billing Address:', +'LBL_SHIPPING_ADDRESS'=>'Shipping Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_DESCRIPTION'=>'Description:', +'NTC_COPY_BILLING_ADDRESS'=>'Copy billing address to shipping address', +'NTC_COPY_SHIPPING_ADDRESS'=>'Copy shipping address to billing address', +'NTC_REMOVE_MEMBER_ORG_CONFIRMATION'=>'Are you sure you want to remove this record as a member organization?', +'LBL_DUPLICATE'=>'Potential Duplicate Accounts', +'MSG_DUPLICATE' => 'Creating this vtiger_account may vtiger_potentialy create a duplicate vtiger_account. You may either select an vtiger_account from the list below or you may click on Create New Account to continue creating a new vtiger_account with the previously entered data.', + +'LBL_INVITEE'=>'Contacts', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", + +'LBL_SELECT_ACCOUNT'=>'Select Account', +'LBL_GENERAL_INFORMATION'=>'General Information', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_PROSPECT'=>'Prospect', +'LBL_INVESTOR'=>'Investor', +'LBL_RESELLER'=>'Reseller', +'LBL_PARTNER'=>'Partner', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Account Tools', +//Added for 4GA +'Account Name'=>'Account Name', +'Phone'=>'Phone', +'Website'=>'Website', +'Fax'=>'Fax', +'Ticker Symbol'=>'Ticker Symbol', +'Other Phone'=>'Other Phone', +'Member Of'=>'Member Of', +'Email'=>'Email', +'Employees'=>'Employees', +'Other Email'=>'Other Email', +'Ownership'=>'Ownership', +'Rating'=>'Rating', +'industry'=>'Industry', +'SIC Code'=>'SIC Code', +'Type'=>'Type', +'Annual Revenue'=>'Annual Revenue', +'Assigned To'=>'Assigned To', +'Billing Address'=>'Billing Address', +'Shipping Address'=>'Shipping Address', +'Billing City'=>'Billing City', +'Shipping City'=>'Shipping City', +'Billing State'=>'Billing State', +'Shipping State'=>'Shipping State', +'Billing Code'=>'Billing Postal Code', +'Shipping Code'=>'Shipping Postal Code', +'Billing Country'=>'Billing Country', +'Shipping Country'=>'Shipping Country', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Description'=>'Description', +'Shipping Po Box'=>'Shipping PO Box', +'Billing Po Box'=>'Billing PO Box', + +//Added after 4.2 patch 2 +'Email Opt Out'=>'Email Opt Out', +'LBL_EMAIL_OPT_OUT'=>'Email Opt Out:', + +//Added after 5Alpha5 +'Notify Owner'=>'Notify Owner', + +//Added for existing picklist entries + +'--None--'=>'--None--', + +'Acquired'=>'Acquired', +'Active'=>'Active', +'Market Failed'=>'Market Failed', +'Project Cancelled'=>'Project Cancelled', +'Shutdown'=>'Shutdown', + +'Apparel'=>'Apparel', +'Banking'=>'Banking', +'Biotechnology'=>'Biotechnology', +'Chemicals'=>'Chemicals', +'Communications'=>'Communications', +'Construction'=>'Construction', +'Consulting'=>'Consulting', +'Education'=>'Education', +'Electronics'=>'Electronics', +'Energy'=>'Energy', +'Engineering'=>'Engineering', +'Entertainment'=>'Entertainment', +'Environmental'=>'Environmental', +'Finance'=>'Finance', +'Food & Beverage'=>'Food & Beverage', +'Government'=>'Government', +'Healthcare'=>'Healthcare', +'Hospitality'=>'Hospitality', +'Insurance'=>'Insurance', +'Machinery'=>'Machinery', +'Manufacturing'=>'Manufacturing', +'Media'=>'Media', +'Not For Profit'=>'Not For Profit', +'Recreation'=>'Recreation', +'Retail'=>'Retail', +'Shipping'=>'Shipping', +'Technology'=>'Technology', +'Telecommunications'=>'Telecommunications', +'Transportation'=>'Transportation', +'Utilities'=>'Utilities', +'Other'=>'Other', + +'Analyst'=>'Analyst', +'Competitor'=>'Competitor', +'Customer'=>'Customer', +'Integrator'=>'Integrator', +'Investor'=>'Investor', +'Partner'=>'Partner', +'Press'=>'Press', +'Prospect'=>'Prospect', +'Reseller'=>'Reseller', +'LBL_START_DATE' => 'Start Date', +'LBL_END_DATE' => 'End Date', + +// Added/Updated for vtiger CRM 5.0.4 + +//added to fix the issue #4081 +'LBL_ACCOUNT_EXIST' => 'Account Name Already Exists!', + +// mailer export +'LBL_MAILER_EXPORT' => 'Mailer Export', +'LBL_MAILER_EXPORT_CONTACTS_TYPE'=>'Select Contacts:', +'LBL_MAILER_EXPORT_CONTACTS_DESCR'=>'Contacts can also be selected via "Custom Fields" and some standard fields.', +'LBL_MAILER_EXPORT_RESULTS_TYPE'=>'Select export type:', +'LBL_MAILER_EXPORT_RESULTS_DESCR'=>'The data will gathered from the Accounts and their Contacts, that were returned + from the previous search.', +'LBL_EXPORT_RESULTS_EMAIL' => 'Export E-Mailer data', +'LBL_EXPORT_RESULTS_EMAIL_CORP'=>'Export E-Mail data, using "Company Email" from the Account if the Contacts "Email" is empty', +'LBL_EXPORT_RESULTS_FULL'=>'Export data with the Contacts, E-Mail, Account name, Address, Telephone, etc.', +'LBL_EXPORT_RESULTS_GO'=>'Export', +'LBL_MAILER_EXPORT_IGNORE' => '--ignore--', +'LBL_MAILER_EXPORT_CHECKED' =>'Checked', +'LBL_MAILER_EXPORT_NOTCHECKED' => 'Not Checked', + +// Added after 5.0.4 GA + +//Module Sequence Numbering +'Account No'=>'Account No', +// END + +// Account Hierarchy +'LBL_SHOW_ACCOUNT_HIERARCHY' => 'Show Account Hierarchy', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Accounts/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Accounts/language/zh_cn.lang.php new file mode 100644 index 00000000..df2fa0e8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/language/zh_cn.lang.php @@ -0,0 +1,240 @@ + '客户', + 'LBL_MODULE_TITLE' => '客户: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻客户', + 'LBL_LIST_FORM_TITLE' => '客户列表', + 'LBL_NEW_FORM_TITLE' => '新增客户', + 'LBL_MEMBER_ORG_FORM_TITLE' => '成员组织性质', +// Label for Top Accounts in Home Page, added for 4.2 GA + 'LBL_TOP_ACCOUNTS' => '我的重要客户', + 'LBL_TOP_AMOUNT' => '金额', + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_LIST_CITY' => '乡镇市区', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '县市', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件地址', + 'LBL_LIST_CONTACT_NAME' => '联系人姓名', + 'LBL_LIST_AMOUNT' => '机会总计', + +//DON'T CONVERT THESE THEY ARE MAPPINGS + 'db_name' => 'LBL_LIST_ACCOUNT_NAME', + 'db_website' => 'LBL_LIST_WEBSITE', + 'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + + 'LBL_ACCOUNT' => '客户:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_PHONE' => '电话:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_TICKER_SYMBOL' => '传票符号:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_ANY_PHONE' => '其它电话:', + 'LBL_MEMBER_OF' => '成员:', + 'LBL_EMAIL' => '电子邮件:', + 'LBL_EMPLOYEES' => '员工:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子邮件:', + 'LBL_ANY_EMAIL' => '其它电子邮件:', + 'LBL_OWNERSHIP' => '所有者:', + 'LBL_RATING' => '评价:', + 'LBL_INDUSTRY' => '行业别:', + 'LBL_SIC_CODE' => '统一编号:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年营业额:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_ACCOUNT_INFORMATION' => '账号信息', + 'LBL_CUSTOM_INFORMATION' => '客户信息', + 'LBL_BILLING_ADDRESS' => '账单地址:', + 'LBL_SHIPPING_ADDRESS' => '送货地址:', + 'LBL_ANY_ADDRESS' => '其它地址:', + 'LBL_CITY' => '乡镇市区:', +'LBL_STATE' => '县市:', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '国家:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息', + 'LBL_DESCRIPTION' => '描述:', + 'NTC_COPY_BILLING_ADDRESS' => '复制账单地址内容到送货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '复制送货地址内容到账单地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '您确定要删除这笔成员/组织的记录吗?', + 'LBL_DUPLICATE' => '复制潜在案件客户', + 'MSG_DUPLICATE' => '由潜在案件客户中复制建立新客户,您可以点选客户列表中的客户以复制建立新的客户,并且继承它的相关数据。', + + 'LBL_INVITEE' => '联系人', + 'ERR_DELETE_RECORD' => '要删除账号您必须指定一笔记录编号.', + + 'LBL_SELECT_ACCOUNT' => '选择客户', + 'LBL_GENERAL_INFORMATION' => '主要信息', + +//for v4 release added + 'LBL_NEW_POTENTIAL' => '新增潜在案件', + 'LBL_POTENTIAL_TITLE' => '潜在案件', + +'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议记录', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '邮件', + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_CONTACT_TITLE' => '联系人', + +//Added vtiger_fields after RC1 - Release + 'LBL_ALL' => '全部', + 'LBL_PROSPECT' => '期望', + 'LBL_INVESTOR' => '投资者', + 'LBL_RESELLER' => '转售人', + 'LBL_PARTNER' => '伙伴', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '客户工具', +//Added for 4GA + 'Account Name' => '客户名称', + 'Phone' => '电话', + 'Website' => '网址', + 'Fax' => '传真', + 'Ticker Symbol' => '传票符号', + 'Other Phone' => '其它电话', + 'Member Of' => '成员', + 'Email' => '电子邮件', + 'Employees' => '员工', + 'Other Email' => '其它电子邮件', + 'Ownership' => '拥有者', + 'Rating' => '评价', + 'industry' => '行业别', + 'SIC Code' => '统一编号', + 'Type' => '类型', + 'Annual Revenue' => '年营业额', + 'Assigned To' => '负责人', + 'Billing Address' => '账单地址', + 'Shipping Address' => '送货地址', + 'Billing City' => '乡镇市区', + 'Shipping City' => '乡镇市区', + 'Billing State' => '县市', + 'Shipping State' => '县市', + 'Billing Code' => '邮政编码', + 'Shipping Code' => '邮政编码', + 'Billing Country' => '国家', + 'Shipping Country' => '国家', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Description' => '描述', + 'Shipping Po Box' => '付款地址采购订单信箱', + 'Billing Po Box' => '付款地址采购订单信箱', + +//Added after 4.2 patch 2 + 'Email Opt Out' => '拒绝电子邮件打扰', + 'LBL_EMAIL_OPT_OUT' => '拒绝电子邮件打扰:', + +//Added after 5Alpha5 + 'Notify Owner' => '提醒负责人', + +//Added for existing picklist entries + + '--None--' => '-- 无 --', + + 'Acquired' => '取得', + 'Active' => '启用', + 'Market Failed' => '市场失利', + 'Project Cancelled' => '项目取消', + 'Shutdown' => '关闭', + +'Apparel' => '存在', + 'Banking' => '银行', + 'Biotechnology' => '生物科技', + 'Chemicals' => '化学', + 'Communications' => '交通', + 'Construction' => '建筑', + 'Consulting' => '顾问', + 'Education' => '教育', + 'Electronics' => '电子', + 'Energy' => '能源', + 'Engineering' => '工程', + 'Entertainment' => '娱乐', + 'Environmental' => '环境', + 'Finance' => '财务', + 'Food & Beverage' => '饮食', + 'Government' => '政府', + 'Healthcare' => '健康照护', + 'Hospitality' => '医院', + 'Insurance' => '保险', + 'Machinery' => '机械', + 'Manufacturing' => '工厂', + 'Media' => '媒体', + 'Not For Profit' => '非营利', + 'Recreation' => '娱乐中心', + 'Retail' => '零售', + 'Shipping' => '运输', + 'Technology' => '科技', + 'Telecommunications' => '通讯', + 'Transportation' => '传输', + 'Utilities' => '工具', + 'Other' => '其它', + + 'Analyst' => '分析师', + 'Competitor' => '竞争者', + 'Customer' => '客户', + 'Integrator' => '整合者', + 'Investor' => '投资者', + 'Partner' => '伙伴', + 'Press' => '新闻', + 'Prospect' => '潜在客户', + 'Reseller' => '盘商', + 'LBL_START_DATE' => '开始日期', + 'LBL_END_DATE' => '结束日期', + +//added to fix the issue #4081 +'LBL_ACCOUNT_EXIST' => '帐户名称已存在!', + +// mailer export +'LBL_MAILER_EXPORT' => '邮寄导出', +'LBL_MAILER_EXPORT_CONTACTS_TYPE'=>'选择通讯录:', +'LBL_MAILER_EXPORT_CONTACTS_DESCR'=>'联络可能被选择通过"自定义字段"和一些标准字段。.', +'LBL_MAILER_EXPORT_RESULTS_TYPE'=>'选择导出类型:', +'LBL_MAILER_EXPORT_RESULTS_DESCR'=>'聚集从账户及其联系人的数据, 还给前次搜索.', +'LBL_EXPORT_RESULTS_EMAIL' => '导出邮件联系人数据', +'LBL_EXPORT_RESULTS_EMAIL_CORP'=>'导出邮件数据, 如果联系人"电邮"为空则用"公司电邮"', +'LBL_EXPORT_RESULTS_FULL'=>'导出联系人数据,电子邮件帐户名称,地址,电话等.', + +'LBL_EXPORT_RESULTS_GO'=>'导出', +'LBL_MAILER_EXPORT_IGNORE' => '--忽略--', +'LBL_MAILER_EXPORT_CHECKED' =>'检查', +'LBL_MAILER_EXPORT_NOTCHECKED' => '不进行检查', + +// Added after 5.0.4 GA + +//Module Sequence Numbering +'Account No'=>'帐号', +// END + +// Account Hierarchy +'LBL_SHOW_ACCOUNT_HIERARCHY' => '查看账号级别', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Accounts/updateRelations.php b/oss/vtiger/trunk/modules/Accounts/updateRelations.php new file mode 100644 index 00000000..1d2c0dc4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Accounts/updateRelations.php @@ -0,0 +1,50 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + elseif($dest_mod == 'Products') + $adb->pquery("insert into vtiger_seproductsrel values(?,?,?)", array($forCRMRecord, $id, $currentModule)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Activities/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Activities/language/zh_cn.lang.php new file mode 100644 index 00000000..74ecf6c3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Activities/language/zh_cn.lang.php @@ -0,0 +1,89 @@ + '活动', + 'LBL_MODULE_TITLE' => '活动:首页', + 'LBL_SEARCH_FORM_TITLE' => '活动查找', + 'LBL_LIST_FORM_TITLE' => '活动列表', + 'LBL_NEW_FORM_TITLE' => '新增活动', + 'LBL_TASK_INFORMATION' => '任务信息', + 'LBL_EVENT_INFORMATION' => '事件信息', + 'LBL_NAME' => '主题:', + 'LBL_CONTACT_NAME' => '联系人:', + 'LBL_OPEN_ACTIVITIES' => '在做的活动', + 'LBL_ACTIVITY' => '活动:', + 'LBL_HISTORY' => '历史纪录', + 'LBL_UPCOMING' => '最近安排', + 'LBL_TODAY' => '显示到时间', + 'LBL_NEW_TASK_BUTTON_TITLE' => '新增任务 [Alt+N]', + 'LBL_NEW_TASK_BUTTON_KEY' => 'N', + 'LBL_NEW_TASK_BUTTON_LABEL' => '新增任务', + 'LBL_SCHEDULE_MEETING_BUTTON_TITLE' => '安排会议 [Alt+M]', + 'LBL_SCHEDULE_MEETING_BUTTON_KEY' => 'M', + 'LBL_SCHEDULE_MEETING_BUTTON_LABEL' => '安排会议', + 'LBL_SCHEDULE_CALL_BUTTON_TITLE' => '安排电话 [Alt+C]', + 'LBL_SCHEDULE_CALL_BUTTON_KEY' => 'C', + 'LBL_SCHEDULE_CALL_BUTTON_LABEL' => '安排电话', + 'LBL_NEW_NOTE_BUTTON_TITLE' => '新增备忘录 [Alt+T]', + 'LBL_NEW_ATTACH_BUTTON_TITLE' => '附加文件 [Alt+F]', + 'LBL_NEW_NOTE_BUTTON_KEY' => 'T', + 'LBL_NEW_ATTACH_BUTTON_KEY' => 'F', + 'LBL_NEW_NOTE_BUTTON_LABEL' => '新增备忘录', + 'LBL_NEW_ATTACH_BUTTON_LABEL' => '附加文件', + 'LBL_TRACK_EMAIL_BUTTON_TITLE' => '撰写邮件 [Alt+K]', + 'LBL_TRACK_EMAIL_BUTTON_KEY' => 'K', + 'LBL_TRACK_EMAIL_BUTTON_LABEL' => '撰写邮件', + 'LBL_LIST_CLOSE' => '完成', + 'LBL_LIST_STATUS' => '状态', + 'LBL_LIST_CONTACT' => '联系人', + 'LBL_LIST_ACCOUNT'=> '客户', + 'LBL_LIST_RELATED_TO' => '相关对象', + 'LBL_LIST_DUE_DATE' => '到期日期', + 'LBL_LIST_DATE' => '日期', + 'LBL_LIST_SUBJECT' => '主题', + 'LBL_LIST_LAST_MODIFIED' => '最新修改', + 'LBL_LIST_RECURRING_TYPE' => '重复类型', + 'ERR_DELETE_RECORD' => '必须指定纪录编号才能删除客户.', + 'NTC_NONE_SCHEDULED' => '沒有安排.', + 'LBL_ATTACHMENTS' => '附件', + 'LBL_NEW_ATTACHMENT' => '新增附件', + 'LBL_ALL' => '所有', + 'LBL_CALL' => '电话', + 'LBL_MEETING' => '会议:', + 'LBL_TASK' => '任务', + 'Subject' => '主题', + 'Assigned To' => '负责人', + 'Start Date & Time' => '开始日期和时间', + 'Time Start' => '开始时间', + 'New Event' => '新增事件', + 'New Task' => '新增事件', + 'Due Date' => '到期日期', + 'Related To' => '相关对象', + 'Contact Name' => '联系人姓名:', + 'Status' => '状态', + 'Priority' => '优先级', + 'Send Notification' => '发送通知', + 'Created Time' => '创建时间', + 'Modified Time' => '修改时间', + 'Activity Type' => '活动类型', + 'Description' => '描述', + 'Duration' => '持续', + 'Duration Minutes' => '持续分钟', + 'Location' => '地点', + 'Send Reminder' => '发送提醒', + 'LBL_YES' => '是', + 'LBL_NO' => '不是', + 'LBL_DAYS' => '天', + 'LBL_MINUTES' => '分钟', + 'LBL_HOURS' => '小时', + 'LBL_BEFORE_EVENT' => '前', + 'Close' => '完成', + 'Start Date' => '开始日期', + 'Type' => '活动类型', + 'End Date' => '结束日期', + 'Recurrence' => '重复事件', + 'Recurring Type' => '重复类型', + 'LBL_NOTIFICATION_ERROR' => '邮件错误:请在 设置=>发送邮件服务器设置 检查您的发送邮件服务器设置或是目前使用者没有设置邮箱', + 'hours/minutes' => '小时/分钟', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Administration/Forms.php b/oss/vtiger/trunk/modules/Administration/Forms.php new file mode 100644 index 00000000..88f9afd2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Administration/Forms.php @@ -0,0 +1,24 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Administration/index.php b/oss/vtiger/trunk/modules/Administration/index.php new file mode 100644 index 00000000..55184609 --- /dev/null +++ b/oss/vtiger/trunk/modules/Administration/index.php @@ -0,0 +1,25 @@ + diff --git a/oss/vtiger/trunk/modules/Administration/language/en_us.lang.php b/oss/vtiger/trunk/modules/Administration/language/en_us.lang.php new file mode 100644 index 00000000..114b65a3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Administration/language/en_us.lang.php @@ -0,0 +1,28 @@ +'Administration', +'LBL_MODULE_TITLE'=>'Administration: Home', + +'LBL_NEW_FORM_TITLE'=>'New Account', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the account.", +); + +?> diff --git a/oss/vtiger/trunk/modules/Administration/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Administration/language/zh_cn.lang.php new file mode 100644 index 00000000..06651422 --- /dev/null +++ b/oss/vtiger/trunk/modules/Administration/language/zh_cn.lang.php @@ -0,0 +1,27 @@ + '管理', + 'LBL_MODULE_TITLE' => '管理: 首页', + 'LBL_NEW_FORM_TITLE' => '新增账号', + 'ERR_DELETE_RECORD' => '在删除账号前必须输入正确的记录编号.', +); + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/Activity.php b/oss/vtiger/trunk/modules/Calendar/Activity.php new file mode 100644 index 00000000..eb3e2535 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Activity.php @@ -0,0 +1,952 @@ +'crmid','vtiger_activity'=>'activityid','vtiger_seactivityrel'=>'activityid','vtiger_cntactivityrel'=>'activityid','vtiger_salesmanactivityrel'=>'activityid','vtiger_activity_reminder'=>'activity_id','vtiger_recurringevents'=>'activityid','vtiger_activitycf'=>'activityid'); + + var $column_fields = Array(); + var $sortby_fields = Array('subject','due_date','date_start','smownerid','activitytype','lastname'); //Sorting is added for due date and start date + + // This is used to retrieve related vtiger_fields from form posts. + var $additional_column_fields = Array('assigned_user_name', 'assigned_user_id', 'contactname', 'contact_phone', 'contact_email', 'parent_name'); + + /** + * Mandatory table for supporting custom fields. + */ + var $customFieldTable = Array('vtiger_activitycf', 'activityid'); + + // This is the list of vtiger_fields that are in the lists. + var $list_fields = Array( + 'Close'=>Array('activity'=>'status'), + 'Type'=>Array('activity'=>'activitytype'), + 'Subject'=>Array('activity'=>'subject'), + 'Related to'=>Array('seactivityrel'=>'parent_id'), + 'Start Date'=>Array('activity'=>'date_start'), + 'Start Time'=>Array('activity','time_start'), + 'End Date'=>Array('activity'=>'due_date'), + 'End Time'=>Array('activity','time_end'), + 'Recurring Type'=>Array('recurringevents'=>'recurringtype'), + 'Assigned To'=>Array('crmentity'=>'smownerid'), + 'Contact Name'=>Array('contactdetails'=>'lastname') + ); + + var $range_fields = Array( + 'name', + 'date_modified', + 'start_date', + 'id', + 'status', + 'date_due', + 'time_start', + 'description', + 'contact_name', + 'priority', + 'duehours', + 'dueminutes', + 'location' + ); + + + var $list_fields_name = Array( + 'Close'=>'status', + 'Type'=>'activitytype', + 'Subject'=>'subject', + 'Contact Name'=>'lastname', + 'Related to'=>'parent_id', + 'Start Date & Time'=>'date_start', + 'End Date & Time'=>'due_date', + 'Recurring Type'=>'recurringtype', + 'Assigned To'=>'assigned_user_id'); + + var $list_link_field= 'subject'; + + //Added these variables which are used as default order by and sortorder in ListView + var $default_order_by = 'due_date'; + var $default_sort_order = 'ASC'; + + //var $groupTable = Array('vtiger_activitygrouprelation','activityid'); + + function Activity() { + $this->log = LoggerManager::getLogger('Calendar'); + $this->db = PearDatabase::getInstance(); + $this->column_fields = getColumnFields('Calendar'); + } + + function save_module($module) + { + global $adb; + //Handling module specific save + //Insert into seactivity rel + if(isset($this->column_fields['parent_id']) && $this->column_fields['parent_id'] != '') + { + $this->insertIntoEntityTable("vtiger_seactivityrel", $module); + } + elseif($this->column_fields['parent_id']=='' && $insertion_mode=="edit") + { + $this->deleteRelation("vtiger_seactivityrel"); + } + //Insert into cntactivity rel + if(isset($this->column_fields['contact_id']) && $this->column_fields['contact_id'] != '') + { + $this->insertIntoEntityTable('vtiger_cntactivityrel', $module); + } + elseif($this->column_fields['contact_id'] =='' && $insertion_mode=="edit") + { + $this->deleteRelation('vtiger_cntactivityrel'); + } + + $recur_type=''; + if(($recur_type == "--None--" || $recur_type == '') && $this->mode == "edit") + { + $sql = 'delete from vtiger_recurringevents where activityid=?'; + $adb->pquery($sql, array($this->id)); + } + //Handling for recurring type + //Insert into vtiger_recurring event table + if(isset($this->column_fields['recurringtype']) && $this->column_fields['recurringtype']!='' && $this->column_fields['recurringtype']!='--None--') + { + $recur_type = trim($this->column_fields['recurringtype']); + $recur_data = getrecurringObjValue(); + if(is_object($recur_data)) + $this->insertIntoRecurringTable($recur_data); + } + + //Insert into vtiger_activity_remainder table + + $this->insertIntoReminderTable('vtiger_activity_reminder',$module,""); + + //Handling for invitees + $selected_users_string = $_REQUEST['inviteesid']; + $invitees_array = explode(';',$selected_users_string); + $this->insertIntoInviteeTable($module,$invitees_array); + + //Inserting into sales man activity rel + $this->insertIntoSmActivityRel($module); + + $this->insertIntoActivityReminderPopup($module); + } + + + /** Function to insert values in vtiger_activity_reminder_popup table for the specified module + * @param $cbmodule -- module:: Type varchar + */ + function insertIntoActivityReminderPopup($cbmodule) { + + global $adb; + + $cbrecord = $this->id; + if(isset($cbmodule) && isset($cbrecord)) { + $cbdate = $this->column_fields['date_start']; + $cbtime = $this->column_fields['time_start']; + + $reminder_query = "SELECT reminderid FROM vtiger_activity_reminder_popup WHERE semodule = ? and recordid = ?"; + $reminder_params = array($cbmodule, $cbrecord); + $reminderidres = $adb->pquery($reminder_query, $reminder_params); + + $reminderid = null; + if($adb->num_rows($reminderidres) > 0) { + $reminderid = $adb->query_result($reminderidres, 0, "reminderid"); + } + + if(isset($reminderid)) { + $callback_query = "UPDATE vtiger_activity_reminder_popup set status = 0, date_start = ?, time_start = ? WHERE reminderid = ?"; + $callback_params = array($cbdate, $cbtime, $reminderid); + } else { + $callback_query = "INSERT INTO vtiger_activity_reminder_popup (recordid, semodule, date_start, time_start) VALUES (?,?,?,?)"; + $callback_params = array($cbrecord, $cbmodule, $cbdate, $cbtime); + } + + $adb->pquery($callback_query, $callback_params); + } + } + + + /** Function to insert values in vtiger_activity_remainder table for the specified module, + * @param $table_name -- table name:: Type varchar + * @param $module -- module:: Type varchar + */ + function insertIntoReminderTable($table_name,$module,$recurid) + { + global $log; + $log->info("in insertIntoReminderTable ".$table_name." module is ".$module); + if($_REQUEST['set_reminder'] == 'Yes') + { + $log->debug("set reminder is set"); + $rem_days = $_REQUEST['remdays']; + $log->debug("rem_days is ".$rem_days); + $rem_hrs = $_REQUEST['remhrs']; + $log->debug("rem_hrs is ".$rem_hrs); + $rem_min = $_REQUEST['remmin']; + $log->debug("rem_minutes is ".$rem_min); + $reminder_time = $rem_days * 24 * 60 + $rem_hrs * 60 + $rem_min; + $log->debug("reminder_time is ".$reminder_time); + if ($recurid == "") + { + if($_REQUEST['mode'] == 'edit') + { + $this->activity_reminder($this->id,$reminder_time,0,$recurid,'edit'); + } + else + { + $this->activity_reminder($this->id,$reminder_time,0,$recurid,''); + } + } + else + { + $this->activity_reminder($this->id,$reminder_time,0,$recurid,''); + } + } + elseif($_REQUEST['set_reminder'] == 'No') + { + $this->activity_reminder($this->id,'0',0,$recurid,'delete'); + } + } + + + // Code included by Jaguar - starts + /** Function to insert values in vtiger_recurringevents table for the specified tablename,module + * @param $recurObj -- Recurring Object:: Type varchar + */ +function insertIntoRecurringTable(& $recurObj) +{ + global $log,$adb; + $log->info("in insertIntoRecurringTable "); + $st_date = $recurObj->startdate->get_formatted_date(); + $log->debug("st_date ".$st_date); + $end_date = $recurObj->enddate->get_formatted_date(); + $log->debug("end_date is set ".$end_date); + $type = $recurObj->recur_type; + $log->debug("type is ".$type); + $flag="true"; + + if($_REQUEST['mode'] == 'edit') + { + $activity_id=$this->id; + + $sql='select min(recurringdate) AS min_date,max(recurringdate) AS max_date, recurringtype, activityid from vtiger_recurringevents where activityid=? group by activityid, recurringtype'; + $result = $adb->pquery($sql, array($activity_id)); + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $recur_type_b4_edit = $adb->query_result($result,$i,"recurringtype"); + $date_start_b4edit = $adb->query_result($result,$i,"min_date"); + $end_date_b4edit = $adb->query_result($result,$i,"max_date"); + } + if(($st_date == $date_start_b4edit) && ($end_date==$end_date_b4edit) && ($type == $recur_type_b4_edit)) + { + if($_REQUEST['set_reminder'] == 'Yes') + { + $sql = 'delete from vtiger_activity_reminder where activity_id=?'; + $adb->pquery($sql, array($activity_id)); + $sql = 'delete from vtiger_recurringevents where activityid=?'; + $adb->pquery($sql, array($activity_id)); + $flag="true"; + } + elseif($_REQUEST['set_reminder'] == 'No') + { + $sql = 'delete from vtiger_activity_reminder where activity_id=?'; + $adb->pquery($sql, array($activity_id)); + $flag="false"; + } + else + $flag="false"; + } + else + { + $sql = 'delete from vtiger_activity_reminder where activity_id=?'; + $adb->pquery($sql, array($activity_id)); + $sql = 'delete from vtiger_recurringevents where activityid=?'; + $adb->pquery($sql, array($activity_id)); + } + } + $date_array = $recurObj->recurringdates; + if(isset($recurObj->recur_freq) && $recurObj->recur_freq != null) + $recur_freq = $recurObj->recur_freq; + else + $recur_freq = 1; + if($recurObj->recur_type == 'Daily' || $recurObj->recur_type == 'Yearly') + $recurringinfo = $recurObj->recur_type; + elseif($recurObj->recur_type == 'Weekly') + { + $recurringinfo = $recurObj->recur_type; + if($recurObj->dayofweek_to_rpt != null) + $recurringinfo = $recurringinfo.'::'.implode('::',$recurObj->dayofweek_to_rpt); + } + elseif($recurObj->recur_type == 'Monthly') + { + $recurringinfo = $recurObj->recur_type.'::'.$recurObj->repeat_monthby; + if($recurObj->repeat_monthby == 'date') + $recurringinfo = $recurringinfo.'::'.$recurObj->rptmonth_datevalue; + else + $recurringinfo = $recurringinfo.'::'.$recurObj->rptmonth_daytype.'::'.$recurObj->dayofweek_to_rpt[0]; + } + else + { + $recurringinfo = ''; + } + if($flag=="true") + { + for($k=0; $k< count($date_array); $k++) + { + $tdate=$date_array[$k]; + if($tdate <= $end_date) + { + $max_recurid_qry = 'select max(recurringid) AS recurid from vtiger_recurringevents;'; + $result = $adb->pquery($max_recurid_qry, array()); + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $recur_id = $adb->query_result($result,$i,"recurid"); + } + $current_id =$recur_id+1; + $recurring_insert = "insert into vtiger_recurringevents values (?,?,?,?,?,?)"; + $rec_params = array($current_id, $this->id, $tdate, $type, $recur_freq, $recurringinfo); + $adb->pquery($recurring_insert, $rec_params); + if($_REQUEST['set_reminder'] == 'Yes') + { + $this->insertIntoReminderTable("vtiger_activity_reminder",$module,$current_id,''); + } + } + } + } +} + + + /** Function to insert values in vtiger_invitees table for the specified module,tablename ,invitees_array + * @param $table_name -- table name:: Type varchar + * @param $module -- module:: Type varchar + * @param $invitees_array Array + */ + function insertIntoInviteeTable($module,$invitees_array) + { + global $log,$adb; + $log->debug("Entering insertIntoInviteeTable(".$module.",".$invitees_array.") method ..."); + if($this->mode == 'edit'){ + $sql = "delete from vtiger_invitees where activityid=?"; + $adb->pquery($sql, array($this->id)); + } + foreach($invitees_array as $inviteeid) + { + if($inviteeid != '') + { + $query="insert into vtiger_invitees values(?,?)"; + $adb->pquery($query, array($this->id, $inviteeid)); + } + } + $log->debug("Exiting insertIntoInviteeTable method ..."); + + } + + + /** Function to insert values in vtiger_salesmanactivityrel table for the specified module + * @param $module -- module:: Type varchar + */ + + function insertIntoSmActivityRel($module) + { + global $adb; + global $current_user; + if($this->mode == 'edit'){ + $sql = "delete from vtiger_salesmanactivityrel where activityid=?"; + $adb->pquery($sql, array($this->id)); + } + + $user_sql = $adb->pquery("select count(*) as count from vtiger_users where id=?", array($this->column_fields['assigned_user_id'])); + if($adb->query_result($user_sql, 0, 'count') != 0) { + $sql_qry = "insert into vtiger_salesmanactivityrel (smid,activityid) values(?,?)"; + $adb->pquery($sql_qry, array($this->column_fields['assigned_user_id'], $this->id)); + + if(isset($_REQUEST['inviteesid']) && $_REQUEST['inviteesid']!='') + { + $selected_users_string = $_REQUEST['inviteesid']; + $invitees_array = explode(';',$selected_users_string); + foreach($invitees_array as $inviteeid) + { + if($inviteeid != '') + { + $resultcheck = $adb->pquery("select * from vtiger_salesmanactivityrel where activityid=? and smid=?",array($this->id,$inviteeid)); + if($adb->num_rows($resultcheck) != 1){ + $query="insert into vtiger_salesmanactivityrel values(?,?)"; + $adb->pquery($query, array($inviteeid, $this->id)); + } + } + } + } + } +} + + + // Mike Crowe Mod --------------------------------------------------------Default ordering for us + /** + * Function to get sort order + * return string $sorder - sortorder string either 'ASC' or 'DESC' + */ + function getSortOrder() + { + global $log; + $log->debug("Entering getSortOrder() method ..."); + if(isset($_REQUEST['sorder'])) + $sorder = $this->db->sql_escape_string($_REQUEST['sorder']); + else + $sorder = (($_SESSION['ACTIVITIES_SORT_ORDER'] != '')?($_SESSION['ACTIVITIES_SORT_ORDER']):($this->default_sort_order)); + $log->debug("Exiting getSortOrder method ..."); + return $sorder; + } + + /** + * Function to get order by + * return string $order_by - fieldname(eg: 'subject') + */ + function getOrderBy() + { + global $log; + $log->debug("Entering getOrderBy() method ..."); + + $use_default_order_by = ''; + if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) { + $use_default_order_by = $this->default_order_by; + } + + if (isset($_REQUEST['order_by'])) + $order_by = $this->db->sql_escape_string($_REQUEST['order_by']); + else + $order_by = (($_SESSION['ACTIVITIES_ORDER_BY'] != '')?($_SESSION['ACTIVITIES_ORDER_BY']):($use_default_order_by)); + $log->debug("Exiting getOrderBy method ..."); + return $order_by; + } + // Mike Crowe Mod -------------------------------------------------------- + + + +//Function Call for Related List -- Start + /** + * Function to get Activity related Contacts + * @param integer $id - activityid + * returns related Contacts record in array format + */ + function get_contacts($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule,$current_user; + $log->debug("Entering get_contacts(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + $returnset = '&return_module='.$this_module.'&return_action=DetailView&activity_mode=Events&return_id='.$id; + + $search_string = ''; + $button = ''; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + } + + $query = 'select vtiger_users.user_name,vtiger_contactdetails.accountid,vtiger_contactdetails.contactid, vtiger_contactdetails.firstname,vtiger_contactdetails.lastname, vtiger_contactdetails.department, vtiger_contactdetails.title, vtiger_contactdetails.email, vtiger_contactdetails.phone, vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime from vtiger_contactdetails inner join vtiger_cntactivityrel on vtiger_cntactivityrel.contactid=vtiger_contactdetails.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid where vtiger_cntactivityrel.activityid='.$id.' and vtiger_crmentity.deleted=0'; + + $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_contacts method ..."); + return $return_value; + } + + /** + * Function to get Activity related Users + * @param integer $id - activityid + * returns related Users record in array format + */ + + function get_users($id) { + global $log; + $log->debug("Entering get_contacts(".$id.") method ..."); + global $app_strings; + + $focus = new Users(); + + $button = ''; + + $returnset = '&return_module=Calendar&return_action=CallRelatedList&return_id='.$id; + + $query = 'SELECT vtiger_users.id, vtiger_users.first_name,vtiger_users.last_name, vtiger_users.user_name, vtiger_users.email1, vtiger_users.email2, vtiger_users.status, vtiger_users.is_admin, vtiger_user2role.roleid, vtiger_users.yahoo_id, vtiger_users.phone_home, vtiger_users.phone_work, vtiger_users.phone_mobile, vtiger_users.phone_other, vtiger_users.phone_fax,vtiger_activity.date_start,vtiger_activity.due_date,vtiger_activity.time_start,vtiger_activity.duration_hours,vtiger_activity.duration_minutes from vtiger_users inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.smid=vtiger_users.id inner join vtiger_activity on vtiger_activity.activityid=vtiger_salesmanactivityrel.activityid inner join vtiger_user2role on vtiger_user2role.userid=vtiger_users.id where vtiger_activity.activityid='.$id; + + $return_data = GetRelatedList('Calendar','Users',$focus,$query,$button,$returnset); + + if($return_data == null) $return_data = Array(); + $return_data['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_users method ..."); + return $return_data; + } + + /** + * Function to get activities for given criteria + * @param string $criteria - query string + * returns activity records in array format($list) or null value + */ + function get_full_list($criteria) { + global $log; + $log->debug("Entering get_full_list(".$criteria.") method ..."); + $query = "select vtiger_crmentity.crmid,vtiger_crmentity.smownerid,vtiger_crmentity.setype, vtiger_activity.*, + vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, vtiger_contactdetails.contactid + from vtiger_activity + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid + left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid + left join vtiger_contactdetails on vtiger_contactdetails.contactid= vtiger_cntactivityrel.contactid + left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid + WHERE vtiger_crmentity.deleted=0 ".$criteria; + $result =& $this->db->query($query); + + if($this->db->getRowCount($result) > 0){ + + // We have some data. + while ($row = $this->db->fetchByAssoc($result)) { + foreach($this->list_fields_name as $field) + { + if (isset($row[$field])) { + $this->$field = $row[$field]; + } + else { + $this->$field = ''; + } + } + $list[] = $this; + } + } + if (isset($list)) + { + $log->debug("Exiting get_full_list method ..."); + return $list; + } + else + { + $log->debug("Exiting get_full_list method ..."); + return null; + } + + } + + +//calendarsync + /** + * Function to get meeting count + * @param string $user_name - User Name + * return integer $row["count(*)"] - count + */ + function getCount_Meeting($user_name) + { + global $log; + $log->debug("Entering getCount_Meeting(".$user_name.") method ..."); + $query = "select count(*) from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid where user_name=? and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Meeting'"; + $result = $this->db->pquery($query, array($user_name),true,"Error retrieving contacts count"); + $rows_found = $this->db->getRowCount($result); + $row = $this->db->fetchByAssoc($result, 0); + $log->debug("Exiting getCount_Meeting method ..."); + return $row["count(*)"]; + } + + function get_calendars($user_name,$from_index,$offset) + { + global $log; + $log->debug("Entering get_calendars(".$user_name.",".$from_index.",".$offset.") method ..."); + $query = "select vtiger_activity.location as location,vtiger_activity.duration_hours as duehours, vtiger_activity.duration_minutes as dueminutes,vtiger_activity.time_start as time_start, vtiger_activity.subject as name,vtiger_crmentity.modifiedtime as date_modified, vtiger_activity.date_start start_date,vtiger_activity.activityid as id,vtiger_activity.status as status, vtiger_crmentity.description as description, vtiger_activity.priority as vtiger_priority, vtiger_activity.due_date as date_due ,vtiger_contactdetails.firstname cfn, vtiger_contactdetails.lastname cln from vtiger_activity inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid where user_name='" .$user_name ."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Meeting' limit " .$from_index ."," .$offset; + $log->debug("Exiting get_calendars method ..."); + return $this->process_list_query1($query); + } +//calendarsync + /** + * Function to get task count + * @param string $user_name - User Name + * return integer $row["count(*)"] - count + */ + function getCount($user_name) + { + global $log; + $log->debug("Entering getCount(".$user_name.") method ..."); + $query = "select count(*) from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid where user_name=? and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Task'"; + $result = $this->db->pquery($query,array($user_name), true,"Error retrieving contacts count"); + $rows_found = $this->db->getRowCount($result); + $row = $this->db->fetchByAssoc($result, 0); + + $log->debug("Exiting getCount method ..."); + return $row["count(*)"]; + } + + /** + * Function to get list of task for user with given limit + * @param string $user_name - User Name + * @param string $from_index - query string + * @param string $offset - query string + * returns tasks in array format + */ + function get_tasks($user_name,$from_index,$offset) + { + global $log; + $log->debug("Entering get_tasks(".$user_name.",".$from_index.",".$offset.") method ..."); + $query = "select vtiger_activity.subject as name,vtiger_crmentity.modifiedtime as date_modified, vtiger_activity.date_start start_date,vtiger_activity.activityid as id,vtiger_activity.status as status, vtiger_crmentity.description as description, vtiger_activity.priority as priority, vtiger_activity.due_date as date_due ,vtiger_contactdetails.firstname cfn, vtiger_contactdetails.lastname cln from vtiger_activity inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid where user_name='" .$user_name ."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Task' limit " .$from_index ."," .$offset; + $log->debug("Exiting get_tasks method ..."); + return $this->process_list_query1($query); + + } + + /** + * Function to process the activity list query + * @param string $query - query string + * return array $response - activity lists + */ + function process_list_query1($query) + { + global $log; + $log->debug("Entering process_list_query1(".$query.") method ..."); + $result =& $this->db->query($query,true,"Error retrieving $this->object_name list: "); + $list = Array(); + $rows_found = $this->db->getRowCount($result); + if($rows_found != 0) + { + $task = Array(); + for($index = 0 , $row = $this->db->fetchByAssoc($result, $index); $row && $index <$rows_found;$index++, $row = $this->db->fetchByAssoc($result, $index)) + + { + foreach($this->range_fields as $columnName) + { + if (isset($row[$columnName])) { + + $task[$columnName] = $row[$columnName]; + } + else + { + $task[$columnName] = ""; + } + } + + $task[contact_name] = return_name($row, 'cfn', 'cln'); + + $list[] = $task; + } + } + + $response = Array(); + $response['list'] = $list; + $response['row_count'] = $rows_found; + $response['next_offset'] = $next_offset; + $response['previous_offset'] = $previous_offset; + + + $log->debug("Exiting process_list_query1 method ..."); + return $response; + } + + /** + * Function to get reminder for activity + * @param integer $activity_id - activity id + * @param string $reminder_time - reminder time + * @param integer $reminder_sent - 0 or 1 + * @param integer $recurid - recuring eventid + * @param string $remindermode - string like 'edit' + */ + function activity_reminder($activity_id,$reminder_time,$reminder_sent=0,$recurid,$remindermode='') + { + global $log; + $log->debug("Entering vtiger_activity_reminder(".$activity_id.",".$reminder_time.",".$reminder_sent.",".$recurid.",".$remindermode.") method ..."); + //Check for vtiger_activityid already present in the reminder_table + $query_exist = "SELECT activity_id FROM ".$this->reminder_table." WHERE activity_id = ?"; + $result_exist = $this->db->pquery($query_exist, array($activity_id)); + + if($remindermode == 'edit') + { + if($this->db->num_rows($result_exist) > 0) + { + $query = "UPDATE ".$this->reminder_table." SET"; + $query .=" reminder_sent = ?, reminder_time = ? WHERE activity_id =?"; + $params = array($reminder_sent, $reminder_time, $activity_id); + } + else + { + $query = "INSERT INTO ".$this->reminder_table." VALUES (?,?,?,?)"; + $params = array($activity_id, $reminder_time, 0, $recurid); + } + } + elseif(($remindermode == 'delete') && ($this->db->num_rows($result_exist) > 0)) + { + $query = "DELETE FROM ".$this->reminder_table." WHERE activity_id = ?"; + $params = array($activity_id); + } + else + { + $query = "INSERT INTO ".$this->reminder_table." VALUES (?,?,?,?)"; + $params = array($activity_id, $reminder_time, 0, $recurid); + } + $this->db->pquery($query,$params,true,"Error in processing vtiger_table $this->reminder_table"); + $log->debug("Exiting vtiger_activity_reminder method ..."); + } + + //Used for vtigerCRM Outlook Add-In + /** + * Function to get tasks to display in outlookplugin + * @param string $username - User name + * return string $query - sql query + */ + function get_tasksforol($username) + { + global $log,$adb; + $log->debug("Entering get_tasksforol(".$username.") method ..."); + global $current_user; + require_once("modules/Users/Users.php"); + $seed_user=new Users(); + $user_id=$seed_user->retrieve_user_id($username); + $current_user=$seed_user; + $current_user->retrieve_entity_info($user_id, 'Users'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $sql1 = "select tablename,columnname from vtiger_field where tabid=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.presence in (0,2)"; + $params1 = array(); + }else + { + $profileList = getCurrentUserProfileList(); + $sql1 = "select tablename,columnname from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.displaytype in (1,2,4,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + $params1 = array(); + if (count($profileList) > 0) { + $sql1 .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params1, $profileList); + } + } + $result1 = $adb->pquery($sql1,$params1); + for($i=0;$i < $adb->num_rows($result1);$i++) + { + $permitted_lists[] = $adb->query_result($result1,$i,'tablename'); + $permitted_lists[] = $adb->query_result($result1,$i,'columnname'); + /*if($adb->query_result($result1,$i,'columnname') == "parentid") + { + $permitted_lists[] = 'vtiger_account'; + $permitted_lists[] = 'accountname'; + }*/ + } + $permitted_lists = array_chunk($permitted_lists,2); + $column_table_lists = array(); + for($i=0;$i < count($permitted_lists);$i++) + { + $column_table_lists[] = implode(".",$permitted_lists[$i]); + } + + $query = "select vtiger_activity.activityid as taskid, ".implode(',',$column_table_lists)." from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid + inner join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid + left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid + left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid + where vtiger_users.user_name='".$username."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Task'"; + $log->debug("Exiting get_tasksforol method ..."); + return $query; + } + + /** + * Function to get calendar query for outlookplugin + * @param string $username - User name * return string $query - sql query */ + function get_calendarsforol($user_name) + { + global $log,$adb; + $log->debug("Entering get_calendarsforol(".$user_name.") method ..."); + global $current_user; + require_once("modules/Users/Users.php"); + $seed_user=new Users(); + $user_id=$seed_user->retrieve_user_id($user_name); + $current_user=$seed_user; + $current_user->retrieve_entity_info($user_id, 'Users'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $sql1 = "select tablename,columnname from vtiger_field where tabid=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.presence in (0,2)"; + $params1 = array(); + }else + { + $profileList = getCurrentUserProfileList(); + $sql1 = "select tablename,columnname from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid=9 and tablename <> 'vtiger_recurringevents' and tablename <> 'vtiger_activity_reminder' and vtiger_field.displaytype in (1,2,4,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + $params1 = array(); + if (count($profileList) > 0) { + $sql1 .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params1,$profileList); + } + } + $result1 = $adb->pquery($sql1, $params1); + for($i=0;$i < $adb->num_rows($result1);$i++) + { + $permitted_lists[] = $adb->query_result($result1,$i,'tablename'); + $permitted_lists[] = $adb->query_result($result1,$i,'columnname'); + if($adb->query_result($result1,$i,'columnname') == "date_start") + { + $permitted_lists[] = 'vtiger_activity'; + $permitted_lists[] = 'time_start'; + } + if($adb->query_result($result1,$i,'columnname') == "due_date") + { + $permitted_lists[] = 'vtiger_activity'; + $permitted_lists[] = 'time_end'; + } + } + $permitted_lists = array_chunk($permitted_lists,2); + $column_table_lists = array(); + for($i=0;$i < count($permitted_lists);$i++) + { + $column_table_lists[] = implode(".",$permitted_lists[$i]); + } + + $query = "select vtiger_activity.activityid as clndrid, ".implode(',',$column_table_lists)." from vtiger_activity + inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.activityid=vtiger_activity.activityid + inner join vtiger_users on vtiger_users.id=vtiger_salesmanactivityrel.smid + left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid=vtiger_activity.activityid + left join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_cntactivityrel.contactid + left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid + where vtiger_users.user_name='".$user_name."' and vtiger_crmentity.deleted=0 and vtiger_activity.activitytype='Meeting'"; + $log->debug("Exiting get_calendarsforol method ..."); + return $query; + } + + // Function to unlink all the dependent entities of the given Entity by Id + function unlinkDependencies($module, $id) { + global $log; + + $sql = 'DELETE FROM vtiger_activity_reminder WHERE activity_id=?'; + $this->db->pquery($sql, array($id)); + + $sql = 'DELETE FROM vtiger_recurringevents WHERE activityid=?'; + $this->db->pquery($sql, array($id)); + + parent::unlinkDependencies($module, $id); + } + + // Function to unlink an entity with given Id from another entity + function unlinkRelationship($id, $return_module, $return_id) { + global $log; + if(empty($return_module) || empty($return_id)) return; + + if($return_module == 'Contacts') { + $sql = 'DELETE FROM vtiger_cntactivityrel WHERE contactid = ? AND activityid = ?'; + $this->db->pquery($sql, array($return_id, $id)); + } elseif($return_module == 'HelpDesk') { + $sql = 'DELETE FROM vtiger_seticketsrel WHERE ticketid = ? AND crmid = ?'; + $this->db->pquery($sql, array($return_id, $id)); + } else { + $sql='DELETE FROM vtiger_seactivityrel WHERE activityid=?'; + $this->db->pquery($sql, array($id)); + + $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)'; + $params = array($id, $return_module, $return_id, $id, $return_module, $return_id); + $this->db->pquery($sql, $params); + } + } + + /** + * this function sets the status flag of activity to true or false depending on the status passed to it + * @param string $status - the status of the activity flag to set + * @return:: true if successful; false otherwise + */ + function setActivityReminder($status){ + global $adb; + if($status == "on"){ + $flag = 0; + }elseif($status == "off"){ + $flag = 1; + }else{ + return false; + } + $sql = "update vtiger_activity_reminder_popup set status=1 where recordid=?"; + $adb->pquery($sql, array($this->id)); + return true; + } + + /* + * Function to get the relation tables for related modules + * @param - $secmodule secondary module name + * returns the array with table names and fieldnames storing relations between module and this module + */ + function setRelationTables($secmodule){ + $rel_tables = array ( + "Contacts" => array("vtiger_cntactivityrel"=>array("activityid","contactid"),"vtiger_activity"=>"activityid"), + "Leads" => array("vtiger_seactivityrel"=>array("activityid","crmid"),"vtiger_activity"=>"activityid"), + "Accounts" => array("vtiger_seactivityrel"=>array("activityid","crmid"),"vtiger_activity"=>"activityid"), + "Potentials" => array("vtiger_seactivityrel"=>array("activityid","crmid"),"vtiger_activity"=>"activityid"), + ); + return $rel_tables[$secmodule]; + } + + /* + * Function to get the secondary query part of a report + * @param - $module primary module name + * @param - $secmodule secondary module name + * returns the query string formed on fetching the related data for report for secondary module + */ + function generateReportsSecQuery($module,$secmodule){ + $query = $this->getRelationQuery($module,$secmodule,"vtiger_activity","activityid"); + $query .=" left join vtiger_crmentity as vtiger_crmentityCalendar on vtiger_crmentityCalendar.crmid=vtiger_activity.activityid and vtiger_crmentityCalendar.deleted=0 + left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid + left join vtiger_contactdetails as vtiger_contactdetailsCalendar on vtiger_contactdetailsCalendar.contactid= vtiger_cntactivityrel.contactid + left join vtiger_activitycf on vtiger_activitycf.activityid = vtiger_crmentity.crmid + left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid + left join vtiger_activity_reminder on vtiger_activity_reminder.activity_id = vtiger_activity.activityid + left join vtiger_recurringevents on vtiger_recurringevents.activityid = vtiger_activity.activityid + left join vtiger_crmentity as vtiger_crmentityRelCalendar on vtiger_crmentityRelCalendar.crmid = vtiger_seactivityrel.crmid and vtiger_crmentityRelCalendar.deleted=0 + left join vtiger_account as vtiger_accountRelCalendar on vtiger_accountRelCalendar.accountid=vtiger_crmentityRelCalendar.crmid + left join vtiger_leaddetails as vtiger_leaddetailsRelCalendar on vtiger_leaddetailsRelCalendar.leadid = vtiger_crmentityRelCalendar.crmid + left join vtiger_potential as vtiger_potentialRelCalendar on vtiger_potentialRelCalendar.potentialid = vtiger_crmentityRelCalendar.crmid + left join vtiger_quotes as vtiger_quotesRelCalendar on vtiger_quotesRelCalendar.quoteid = vtiger_crmentityRelCalendar.crmid + left join vtiger_purchaseorder as vtiger_purchaseorderRelCalendar on vtiger_purchaseorderRelCalendar.purchaseorderid = vtiger_crmentityRelCalendar.crmid + left join vtiger_invoice as vtiger_invoiceRelCalendar on vtiger_invoiceRelCalendar.invoiceid = vtiger_crmentityRelCalendar.crmid + left join vtiger_salesorder as vtiger_salesorderRelCalendar on vtiger_salesorderRelCalendar.salesorderid = vtiger_crmentityRelCalendar.crmid + left join vtiger_troubletickets as vtiger_troubleticketsRelCalendar on vtiger_troubleticketsRelCalendar.ticketid = vtiger_crmentityRelCalendar.crmid + left join vtiger_campaign as vtiger_campaignRelCalendar on vtiger_campaignRelCalendar.campaignid = vtiger_crmentityRelCalendar.crmid + left join vtiger_groups as vtiger_groupsCalendar on vtiger_groupsCalendar.groupid = vtiger_crmentityCalendar.smownerid + left join vtiger_users as vtiger_usersCalendar on vtiger_usersCalendar.id = vtiger_crmentityCalendar.smownerid"; + return $query; + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/ActivityAjax.php b/oss/vtiger/trunk/modules/Calendar/ActivityAjax.php new file mode 100644 index 00000000..650a151e --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/ActivityAjax.php @@ -0,0 +1,239 @@ +debug("In CalendarAjax file"); +$mysel = vtlib_purify($_REQUEST['view']); +if($_REQUEST['file'] == 'OpenListView') +{ + require_once('Smarty_setup.php'); + $smarty = new vtigerCRM_Smarty; + require_once("modules/Calendar/OpenListView.php"); + $smarty->assign("APP",$app_strings); + $smarty->assign("IMAGE_PATH",$image_path); + if($_REQUEST['mode'] == '0') + { + $activities[0] = getPendingActivities(0); + $smarty->assign("ACTIVITIES",$activities); + $smarty->display("upcomingActivities.tpl"); + } + else if($_REQUEST['mode'] == '1') + { + $activities[1] = getPendingActivities(1); + $smarty->assign("ACTIVITIES",$activities); + $smarty->display("pendingActivities.tpl"); + } + die(); +} +$calendar_arr = Array(); +$calendar_arr['IMAGE_PATH'] = $image_path; +$date_data = array(); +if ( isset($_REQUEST['day'])) +{ + $date_data['day'] = $_REQUEST['day']; +} +if ( isset($_REQUEST['month'])) +{ + $date_data['month'] = $_REQUEST['month']; +} +if ( isset($_REQUEST['week'])) +{ + $date_data['week'] = $_REQUEST['week']; +} +if ( isset($_REQUEST['year'])) +{ + if ($_REQUEST['year'] > 2037 || $_REQUEST['year'] < 1970) + { + print("".$app_strings['LBL_CAL_LIMIT_MSG'].""); + exit; + } + $date_data['year'] = $_REQUEST['year']; +} + + +if((isset($_REQUEST['type']) && $_REQUEST['type'] !='') || (isset($_REQUEST['n_type']) && $_REQUEST['n_type'] !='')) +{ + $type = $_REQUEST['type']; + $n_type = $_REQUEST['n_type']; + $cal_log->debug("type value is:".$type); + if($type == 'minical') + { + $cal_log->debug("going to get mini calendar"); + $temp_module = $currentModule; + $mod_strings = return_module_language($current_language,'Calendar'); + $currentModule = 'Calendar'; + $calendar_arr['IMAGE_PATH'] = $image_path; + $calendar_arr['calendar'] = new Calendar('month',$date_data); + $calendar_arr['view'] = 'month'; + $calendar_arr['size'] = 'small'; + if($current_user->hour_format != '') + $calendar_arr['calendar']->hour_format=$current_user->hour_format; + $calendar_arr['calendar']->add_Activities($current_user); + calendar_layout($calendar_arr); + $mod_strings = return_module_language($current_language,$temp_module); + $currentModule = vtlib_purify($_REQUEST['module']); + } + elseif($type == 'settings') + { + $cal_log->debug("going to get calendar Settings"); + require_once('modules/Calendar/calendar_share.php'); + } + else + { + $subtab = vtlib_purify($_REQUEST['subtab']); + if(empty($mysel)) + { + $mysel = 'day'; + } + $calendar_arr['calendar'] = new Calendar($mysel,$date_data); + + $calendar_arr['view'] = $mysel; + if($calendar_arr['calendar']->view == 'day') + $start_date = $end_date = $calendar_arr['calendar']->date_time->get_formatted_date(); + elseif($calendar_arr['calendar']->view == 'week') + { + $start_date = $calendar_arr['calendar']->slices[0]; + $end_date = $calendar_arr['calendar']->slices[6]; + } + elseif($calendar_arr['calendar']->view == 'month') + { + $start_date = $calendar_arr['calendar']->date_time->getThismonthDaysbyIndex(0); + $end_date = $calendar_arr['calendar']->date_time->getThismonthDaysbyIndex($calendar_arr['calendar']->date_time->daysinmonth - 1); + $start_date = $start_date->get_formatted_date(); + $end_date = $end_date->get_formatted_date(); + } + elseif($calendar_arr['calendar']->view == 'year') + { + $start_date = $calendar_arr['calendar']->date_time->getThisyearMonthsbyIndex(0); + $end_date = $calendar_arr['calendar']->date_time->get_first_day_of_changed_year('increment'); + $start_date = $start_date->get_formatted_date(); + $end_date = $end_date->get_formatted_date(); + } + else + { + die("view:".$calendar_arr['calendar']->view." is not defined"); + } + + if($type == 'change_owner' || $type == 'activity_delete' || $type == 'change_status' || $type == 'activity_postpone' || $n_type == 'nav') + { + if($current_user->hour_format != '') + $calendar_arr['calendar']->hour_format=$current_user->hour_format; + + if($type == 'change_status') + { + $return_id = vtlib_purify($_REQUEST['record']); + if(isset($_REQUEST['status'])) + { + $status = $_REQUEST['status']; + $activity_type = "Task"; + } + elseif(isset($_REQUEST['eventstatus'])) + { + $status = $_REQUEST['eventstatus']; + $activity_type = "Events"; + } + ChangeStatus($status,$return_id,$activity_type); + $mail_data = getActivityMailInfo($return_id,$status,$activity_type); + if($mail_data['sendnotification'] == 1) + { + getEventNotification($activity_type,$mail_data['subject'],$mail_data); + } + $invitee_qry = "select * from vtiger_invitees where activityid=?"; + $invitee_res = $adb->pquery($invitee_qry, array($return_id)); + $count = $adb->num_rows($invitee_res); + if($count != 0) + { + for($j = 0; $j < $count; $j++) + { + $invitees_ids[]= $adb->query_result($invitee_res,$j,"inviteeid"); + + } + $invitees_ids_string = implode(';',$invitees_ids); + sendInvitation($invitees_ids_string,$activity_type,$mail_data['subject'],$mail_data); + } + } + if($type == 'activity_postpone') + { + } + if ($_REQUEST['viewOption'] == 'hourview' && ($mysel == 'day' || $mysel == 'week' || $mysel == 'month' || $mysel == 'year')) + { + $calendar_arr['calendar']->add_Activities($current_user); + } + + if(isset($_REQUEST['viewOption']) && $_REQUEST['viewOption'] != null && $subtab == 'event') + { + if($_REQUEST['viewOption'] == 'hourview') + { + $cal_log->debug("going to get calendar Event HourView"); + if($calendar_arr['view'] == 'day') + { + echo getDayViewLayout($calendar_arr)."####".getEventInfo($calendar_arr,'listcnt'); + } + elseif($calendar_arr['view'] == 'week') + { + echo getWeekViewLayout($calendar_arr)."####".getEventInfo($calendar_arr,'listcnt'); + } + elseif($calendar_arr['view'] == 'month') + { + echo getMonthViewLayout($calendar_arr)."####".getEventInfo($calendar_arr,'listcnt'); + } + elseif($calendar_arr['view'] == 'year') + { + echo getYearViewLayout($calendar_arr)."####".getEventInfo($calendar_arr,'listcnt'); + } + else + { + die("view:".$view['view']." is not defined"); + } + } + elseif($_REQUEST['viewOption'] == 'listview') + { + $cal_log->debug("going to get calendar Event ListView"); + //To get Events List + $activity_arr = getEventList($calendar_arr, $start_date, $end_date); + $activity_list = $activity_arr[0]; + $navigation_arr = $activity_arr[1]; + echo constructEventListView($calendar_arr,$activity_list,$navigation_arr)."####".getEventInfo($calendar_arr,'listcnt'); + } + } + elseif($subtab == 'todo') + { + $cal_log->debug("going to get calendar Todo ListView"); + //To get Todos List + $todo_arr = getTodoList($calendar_arr, $start_date, $end_date); + $todo_list = $todo_arr[0]; + $navigation_arr = $todo_arr[1]; + echo constructTodoListView($todo_list,$calendar_arr,$subtab,$navigation_arr)."####".getTodoInfo($calendar_arr,'listcnt'); + } + } + elseif($type == 'view') + { + checkFileAccess('modules/Calendar/'.$_REQUEST['file'].'.php'); + require_once('modules/Calendar/'.$_REQUEST['file'].'.php'); + } + else + { + die("View option is not defined"); + } + } +} +else +{ + require_once('include/Ajax/CommonAjax.php'); + //die("type is not set"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/ActivityReminderCallbackAjax.php b/oss/vtiger/trunk/modules/Calendar/ActivityReminderCallbackAjax.php new file mode 100644 index 00000000..86457bc0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/ActivityReminderCallbackAjax.php @@ -0,0 +1,128 @@ +pquery("select * from vtiger_users where id=?",array($current_user->id)); +$active_res = $adb->query_result($active,0,'reminder_interval'); +if($active_res!='None'){ + $reminder_next=$adb->query_result($active,0,"reminder_next_time"); + $lastlogin_time =$adb->query_result($active,0,"date_entered"); + if(empty($reminder_next)) { + $reminder_next = date('Y-m-d H:i'); + } + if(strtotime($lastlogin_time) > strtotime($reminder_next)) { + $reminder_next = $lastlogin_time; + } + $reminder_next_time = strtotime($reminder_next); + $cur_time = mktime(date('H'),date('i'),0,date('m'),date('d'),date('Y')); + + if($reminder_next_time <= $cur_time) + { + $cb_time=$adb->query_result($active,0,"reminder_interval"); + $cb_time = ConvertToMinutes($cb_time); + $cb_mktime = strtotime($reminder_next); + $cbdate1 = date('Y-m-d', strtotime("+$cb_time minutes", $cb_mktime)); + $cbtime1 = date('H:i', strtotime("+$cb_time minutes", $cb_mktime)); + $callback_query = + "SELECT * FROM vtiger_activity_reminder_popup inner join vtiger_crmentity where " . + " vtiger_activity_reminder_popup.status = 0 and " . + " vtiger_activity_reminder_popup.recordid = vtiger_crmentity.crmid " . + " and vtiger_crmentity.smownerid = ".$current_user->id." and vtiger_crmentity.deleted = 0 " . + " and ((DATE_FORMAT(vtiger_activity_reminder_popup.date_start,'%Y-%m-%d') < '" . $cbdate1 . "')" . + " OR ((DATE_FORMAT(vtiger_activity_reminder_popup.date_start,'%Y-%m-%d') = '" . $cbdate1 . "')" . + " AND (TIME_FORMAT(vtiger_activity_reminder_popup.time_start,'%H:%i') <= '" . $cbtime1 . "')))"; + + $result = $adb->query($callback_query); + + $cbrows = $adb->num_rows($result); + if($cbrows > 0) { + for($index = 0; $index < $cbrows; ++$index) { + $reminderid = $adb->query_result($result, $index, "reminderid"); + $cbrecord = $adb->query_result($result, $index, "recordid"); + $cbmodule = $adb->query_result($result, $index, "semodule"); + + $focus = CRMEntity::getInstance($cbmodule); + + if($cbmodule == 'Calendar') { + $focus->retrieve_entity_info($cbrecord,$cbmodule); + + $cbsubject = $focus->column_fields['subject']; + $cbactivitytype = $focus->column_fields['activitytype']; + $cbdate = $focus->column_fields["date_start"]; + $cbtime = $focus->column_fields["time_start"]; + } else { + // For non-calendar records. + $cbsubject = array_values(getEntityName($cbmodule, $cbrecord)); + $cbsubject = $cbsubject[0]; + $cbactivitytype = getTranslatedString($cbmodule, $cbmodule); + $cbdate = $adb->query_result($result, $index, 'date_start'); + $cbtime = $adb->query_result($result, $index, 'time_start'); + } + + if($cbactivitytype=='Task') + $cbstatus = $focus->column_fields["taskstatus"]; + else + $cbstatus = $focus->column_fields["eventstatus"]; + // Appending recordid we can get unique callback dom id for that record. + $popupid = "ActivityReminder_$cbrecord"; + if($cbdate <= date('Y-m-d')){ + if($cbdate == date('Y-m-d') && $cbtime > date('H:i')) $cbcolor = ''; + else $cbcolor= '#FF1515'; + } + $smarty->assign("THEME", $theme); + $smarty->assign("popupid", $popupid); + $smarty->assign("APP", $app_strings); + $smarty->assign("cbreminderid", $reminderid); + $smarty->assign("cbdate", $cbdate); + $smarty->assign("cbtime", $cbtime); + $smarty->assign("cbsubject", $cbsubject); + $smarty->assign("cbmodule", $cbmodule); + $smarty->assign("cbrecord", $cbrecord); + $smarty->assign("cbstatus", $cbstatus); + $smarty->assign("cbcolor", $cbcolor); + $smarty->assign("cblinkdtl", $cblinkdtl); + $smarty->assign("activitytype", $cbactivitytype); + $smarty->display("ActivityReminderCallback.tpl"); + + $mark_reminder_as_read = "UPDATE vtiger_activity_reminder_popup set status = 1 where reminderid = ?"; + $adb->pquery($mark_reminder_as_read, array($reminderid)); + } + } + $reminder_next = date('Y-m-d H:i', strtotime("+$cb_time minutes", $cur_time)); + // NOTE date_entered has CURRENT_TIMESTAMP constraint, so we need to reset when updating the table + $adb->pquery("UPDATE vtiger_users set reminder_next_time=?, date_entered=? where id=?",array($reminder_next, $lastlogin_time, $current_user->id)); + $reminder_interval_reset = (strtotime($reminder_next) - $cur_time) * 1000; + + // NOTE (Overcome Browser's issue): If required comment out the following line if condition below. + // To make popup work fine when interval is set to 1 minute, we need decrement the timeout + // if($reminder_interval_reset / 1000 == 60) $reminder_interval_reset = (40 * 1000); + + echo ""; + } +} +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/ActivityReminderSetupCallbackAjax.php b/oss/vtiger/trunk/modules/Calendar/ActivityReminderSetupCallbackAjax.php new file mode 100644 index 00000000..4ec94824 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/ActivityReminderSetupCallbackAjax.php @@ -0,0 +1,45 @@ +pquery($reminder_query, array($reminderid, $cbmodule, $cbrecord)); + echo ":#:SUCCESS"; + } else { + echo ":#:FAILURE"; + } + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/Appointment.php b/oss/vtiger/trunk/modules/Calendar/Appointment.php new file mode 100644 index 00000000..8cd69651 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Appointment.php @@ -0,0 +1,297 @@ +participant = Array(); + $this->participant_state = Array(); + $this->description = ""; + } + + /** To get the events of the specified user and shared events + * @param $userid -- The user Id:: Type integer + * @param $from_datetime -- The start date Obj :: Type Array + * @param $to_datetime -- The end date Obj :: Type Array + * @param $view -- The calendar view :: Type String + * @returns $list :: Type Array + */ + + function readAppointment($userid, &$from_datetime, &$to_datetime, $view) + { + global $current_user,$adb; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $and = "AND ((vtiger_activity.date_start between ? AND ?) + OR (vtiger_activity.date_start < ? AND vtiger_activity.due_date > ?) + OR (vtiger_activity.due_date between ? AND ?))"; + + $q= "select vtiger_activity.*, vtiger_crmentity.*, case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name FROM vtiger_activity inner join vtiger_crmentity on vtiger_activity.activityid = vtiger_crmentity.crmid left join vtiger_recurringevents on vtiger_activity.activityid=vtiger_recurringevents.activityid left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid WHERE vtiger_crmentity.deleted = 0 and vtiger_activity.activitytype not in ('Emails','Task') $and "; + + // User Select Customization: Changes should made also in (calendayLaout getEventList) and one more BELOW + $query_filter_prefix = calendarview_getSelectedUserFilterQuerySuffix(); + $q .= $query_filter_prefix; + // END + $params = array($from_datetime->get_formatted_date(), $to_datetime->get_formatted_date(), $from_datetime->get_formatted_date(), $from_datetime->get_formatted_date(), $from_datetime->get_formatted_date(), $to_datetime->get_formatted_date()); + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3) + { + //Added for User Based Custom View for Calendar + $sec_parameter=getCalendarViewSecurityParameter(); + $q .= $sec_parameter; + } + + $q .= " AND vtiger_recurringevents.activityid is NULL "; + $q .= " group by vtiger_activity.activityid ORDER by vtiger_activity.date_start,vtiger_activity.time_start"; + + $r = $adb->pquery($q, $params); + $n = $adb->getRowCount($r); + $a = 0; + $list = Array(); + + while ( $a < $n ) + { + + $result = $adb->fetchByAssoc($r); + $start_timestamp = strtotime($result["date_start"]); + $end_timestamp = strtotime($result["due_date"]); + if($from_datetime->ts <= $start_timestamp) $from = $start_timestamp; + else $from = $from_datetime->ts; + if($to_datetime->ts <= $end_timestamp) $to = $to_datetime->ts; + else $to = $end_timestamp; + for($j = $from; $j <= $to; $j=$j+(60*60*24)) + { + + $obj = &new Appointment(); + $temp_start = date("Y-m-d",$j); + $result["date_start"]= $temp_start ; + list($obj->temphour,$obj->tempmin) = explode(":",$result["time_start"]); + if($start_timestamp != $end_timestamp && $view == 'day'){ + if($j == $start_timestamp){ + $result["duration_hours"] = 24 - $obj->temphour; + }elseif($j > $start_timestamp && $j < $end_timestamp){ + list($obj->temphour,$obj->tempmin)= $current_user->start_hour !=''?explode(":",$current_user->start_hour):explode(":","08:00"); + $result["duration_hours"] = 24 - $obj->temphour; + }elseif($j == $end_timestamp){ + list($obj->temphour,$obj->tempmin)= $current_user->start_hour !=''?explode(":",$current_user->start_hour):explode(":","08:00"); + list($ehr,$emin) = explode(":",$result["time_end"]); + $result["duration_hours"] = $ehr - $obj->temphour; + } + } + $obj->readResult($result, $view); + $list[] = $obj; + unset($obj); + + } + $a++; + + } + //Get Recurring events + $q = "SELECT vtiger_activity.*, vtiger_crmentity.*, case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name , vtiger_recurringevents.recurringid, vtiger_recurringevents.recurringdate as date_start ,vtiger_recurringevents.recurringtype,vtiger_groups.groupname from vtiger_activity inner join vtiger_crmentity on vtiger_activity.activityid = vtiger_crmentity.crmid inner join vtiger_recurringevents on vtiger_activity.activityid=vtiger_recurringevents.activityid left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid "; + $q.=" where vtiger_crmentity.deleted = 0 and vtiger_activity.activitytype not in ('Emails','Task') AND (recurringdate between ? and ?) "; + + // User Select Customization + $q .= $query_filter_prefix; + // END + + $params = array($from_datetime->get_formatted_date(), $to_datetime->get_formatted_date()); + + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3) + { + $sec_parameter=getListViewSecurityParameter('Calendar'); + $q .= $sec_parameter; + } + + $q .= " ORDER by vtiger_recurringevents.recurringid"; + $r = $adb->pquery($q, $params); + $n = $adb->getRowCount($r); + $a = 0; + while ( $a < $n ) + { + $obj = &new Appointment(); + $result = $adb->fetchByAssoc($r); + list($obj->temphour,$obj->tempmin) = explode(":",$result["time_start"]); + $obj->readResult($result,$view); + $a++; + $list[] = $obj; + unset($obj); + } + + + usort($list,'compare'); + return $list; + } + + + /** To read and set the events value in Appointment Obj + * @param $act_array -- The vtiger_activity array :: Type Array + * @param $view -- The calendar view :: Type String + */ + function readResult($act_array, $view) + { + global $adb,$current_user,$app_strings; + $format_sthour=''; + $format_stmin=''; + $this->description = $act_array["description"]; + $this->eventstatus = getRoleBasesdPickList('eventstatus',$act_array["eventstatus"]); + $this->priority = getRoleBasesdPickList('taskpriority',$act_array["priority"]); + $this->subject = $act_array["subject"]; + $this->activity_type = $act_array["activitytype"]; + $this->duration_hour = $act_array["duration_hours"]; + $this->duration_minute = $act_array["duration_minutes"]; + $this->creatorid = $act_array["smcreatorid"]; + //$this->creator = getUserName($act_array["smcreatorid"]); + $this->assignedto = $act_array["user_name"]; + $this->owner = $act_array["user_name"]; + if(!is_admin($current_user)) + { + if($act_array["smownerid"]!=0 && $act_array["smownerid"] != $current_user->id && $act_array["visibility"] == "Public"){ + $que = "select * from vtiger_sharedcalendar where sharedid=? and userid=?"; + $row = $adb->pquery($que, array($current_user->id, $act_array["smownerid"])); + $no = $adb->getRowCount($row); + if($no > 0) + $this->shared = true; + } + } + $this->image_name = $act_array["activitytype"].".gif"; + if(!empty($act_array["recurringid"]) && !empty($act_array["recurringtype"])) + $this->recurring="Recurring.gif"; + + $this->record = $act_array["activityid"]; + list($styear,$stmonth,$stday) = explode("-",$act_array["date_start"]); + if($act_array["notime"] != 1){ + $st_hour = twoDigit($this->temphour); + list($sthour,$stmin) = split(":",$act_array["time_start"]); + }else{ + $st_hour = 'notime'; + $stmin = '00'; + $sthour= '00'; + } + list($eyear,$emonth,$eday) = explode("-",$act_array["due_date"]); + list($end_hour,$end_min) = split(":",$act_array["time_end"]); + + $start_date_arr = Array( + 'min' => $stmin, + 'hour' => $sthour, + 'day' => $stday, + 'month' => $stmonth, + 'year' => $styear + ); + $end_date_arr = Array( + 'min' => $end_min, + 'hour' => $end_hour, + 'day' => $eday, + 'month' => $emonth, + 'year' => $eyear + ); + $this->start_time = new vt_DateTime($start_date_arr,true); + $this->end_time = new vt_DateTime($end_date_arr,true); + if($view == 'day' || $view == 'week') + { + $this->formatted_datetime= $act_array["date_start"].":".$st_hour; + } + elseif($view == 'year') + { + list($year,$month,$date) = explode("-",$act_array["date_start"]); + $this->formatted_datetime = $month; + } + else + { + $this->formatted_datetime= $act_array["date_start"]; + } + return; + } + + +} + +/** To two array values + * @param $a -- The vtiger_activity array :: Type Array + * @param $b -- The vtiger_activity array :: Type Array + * @returns value 0 or 1 or -1 depends on comparision result + */ +function compare($a,$b) +{ + if ($a->start_time->ts == $b->start_time->ts) + { + return 0; + } + return ($a->start_time->ts < $b->start_time->ts) ? -1 : 1; +} +function getRoleBasesdPickList($fldname,$exist_val) +{ + global $adb,$app_strings,$current_user; + $is_Admin = $current_user->is_admin; + if($is_Admin == 'off' && $fldname != '') + { + $roleid=$current_user->roleid; + $roleids = Array(); + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + $roleids = $subrole; + array_push($roleids, $roleid); + + //here we are checking wheather the table contains the sortorder column .If sortorder is present in the main picklist table, then the role2picklist will be applicable for this table... + + $sql="select * from vtiger_$fldname where $fldname=?"; + $res = $adb->pquery($sql,array(decode_html($exist_val))); + $picklistvalueid = $adb->query_result($res,0,'picklist_valueid'); + if ($picklistvalueid != null) { + $pick_query="select * from vtiger_role2picklist where picklistvalueid=$picklistvalueid and roleid in (". generateQuestionMarks($roleids) .")"; + + $res_val=$adb->pquery($pick_query,array($roleids)); + $num_val = $adb->num_rows($res_val); + } + if($num_val > 0) + $pick_val = $exist_val; + else + $pick_val = $app_strings['LBL_NOT_ACCESSIBLE']; + + + }else + $pick_val = $exist_val; + + return $pick_val; + +} +?> diff --git a/oss/vtiger/trunk/modules/Calendar/Calendar.js b/oss/vtiger/trunk/modules/Calendar/Calendar.js new file mode 100644 index 00000000..51bc89b5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Calendar.js @@ -0,0 +1,99 @@ + +/********************************************************************************* + +** 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. + ********************************************************************************/ + +function set_values(form) { + + if (form.duedate_flag.checked) { + + form.duedate_flag.value='on'; + + form.duedate.value=""; + + form.duetime.value=""; + + form.duedate.readOnly=true; + + form.duetime.readOnly=true; + + document.images.jscal_trigger.width = 0; + + document.images.jscal_trigger.height = 0; + + } + + else { + + form.duedate_flag.value='off'; + + form.duedate.readOnly=false; + + form.duetime.readOnly=false; + + if (form.duetime.readonly) alert (alert_arr.READONLY); + + document.images.jscal_trigger.width = 16; + + document.images.jscal_trigger.height = 16; + + } + +} +function toggleTime() +{ + if(getObj("notime").checked) + { + getObj("notime").value = 'on'; + getObj("duration_hours").disabled = true; + getObj("duration_minutes").disabled = true; + } + else + { + getObj("notime").value = 'off'; + getObj("duration_minutes").disabled = false; + getObj("duration_hours").disabled = false; + } +} + +function toggleAssignType(currType) + +{ + + if (currType=="U") + + { + + getObj("assign_user").style.display="block" + + getObj("assign_team").style.display="none" + + } + + else + + { + + getObj("assign_user").style.display="none" + + getObj("assign_team").style.display="block" + + } + +} + +function showActivityView(selectactivity_view) +{ + //script to reload the page with the view type when the combo values are changed + View_name = selectactivity_view.options[selectactivity_view.options.selectedIndex].value; + document.frmOpenLstView.action = "index.php?module=Home&action=index&activity_view="+View_name; + document.frmOpenLstView.submit(); +} + + diff --git a/oss/vtiger/trunk/modules/Calendar/Calendar.php b/oss/vtiger/trunk/modules/Calendar/Calendar.php new file mode 100644 index 00000000..50dfa3ce --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Calendar.php @@ -0,0 +1,297 @@ +view = $view; + $this->date_time = new vt_DateTime($data,true); + $this->constructLayout(); + } + /** + * Function to get calendarview Label + * @param string $view - calendarview + * return string - calendarview Label + */ + function getCalendarView($view) + { + switch($view) + { + case 'day': + return "DAY"; + case 'week': + return "WEEK"; + case 'month': + return "MON"; + case 'year': + return "YEAR"; + } + } + + /** + * Function to set values for calendar object depends on calendar view + */ + function constructLayout() + { + global $current_user; + switch($this->view) + { + case 'day': + for($i=-1;$i<=23;$i++) + { + if($i == -1) + { + $layout = new Layout('hour',$this->date_time->getTodayDatetimebyIndex(0)); + $this->day_slice[$layout->start_time->get_formatted_date().':notime'] = $layout; + $this->slices['notime'] = $layout->start_time->get_formatted_date().":notime"; + } + else + { + $layout = new Layout('hour',$this->date_time->getTodayDatetimebyIndex($i)); + $this->day_slice[$layout->start_time->get_formatted_date().':'.$layout->start_time->z_hour] = $layout; + array_push($this->slices, $layout->start_time->get_formatted_date().":".$layout->start_time->z_hour); + } + } + break; + case 'week': + $weekview_days = 7; + for($i=0;$i<$weekview_days;$i++) + { + $layout = new Layout('day',$this->date_time->getThisweekDaysbyIndex($i)); + $this->week_array[$layout->start_time->get_formatted_date()] = $layout; + for($h=-1;$h<=23;$h++) + { + if($h == -1) + { + $hour_list = new Layout('hour',$this->date_time->getTodayDatetimebyIndex(0,$layout->start_time->day,$layout->start_time->month,$layout->start_time->year)); + $this->week_slice[$layout->start_time->get_formatted_date().':notime'] = $hour_list; + $this->week_hour_slices['notime'] = $layout->start_time->get_formatted_date().":notime"; + } + else + { + $hour_list = new Layout('hour',$this->date_time->getTodayDatetimebyIndex($h,$layout->start_time->day,$layout->start_time->month,$layout->start_time->year)); + $this->week_slice[$layout->start_time->get_formatted_date().':'.$hour_list->start_time->z_hour] = $hour_list; + array_push($this->week_hour_slices, $layout->start_time->get_formatted_date().":".$hour_list->start_time->z_hour); + } + } + array_push($this->slices, $layout->start_time->get_formatted_date()); + + } + break; + case 'month': + $arr = getCalendarDaysInMonth($this->date_time); + $this->month_array = $arr["month_array"]; + $this->slices = $arr["slices"]; + $this->date_time = $arr["date_time"]; + break; + case 'year': + $this->month_day_slices = Array(); + for($i=0;$i<12;$i++){ + $currMonth = $this->date_time->getThisyearMonthsbyIndex($i); + $layout = new Layout('month',$this->date_time->getThisyearMonthsbyIndex($i)); + $this->year_array[$layout->start_time->z_month] = $layout; + + $arr = getCalendarDaysInMonth($currMonth); + $slices = $arr["slices"]; + + $this->month_day_slices[$i] = $slices; + array_push($this->slices, $layout->start_time->z_month); + } + break; + } + } + + /** + * Function to get date info depends on calendarview + * @param string $type - string 'increment' or 'decrment' + */ + + function get_datechange_info($type) + { + if($type == 'next') + $mode = 'increment'; + if($type == 'prev') + $mode = 'decrment'; + switch($this->view) + { + case 'day': + $day = $this->date_time->get_changed_day($mode); + break; + case 'week': + $day = $this->date_time->get_first_day_of_changed_week($mode); + break; + case 'month': + $day = $this->date_time->get_first_day_of_changed_month($mode); + break; + case 'year': + $day = $this->date_time->get_first_day_of_changed_year($mode); + break; + default: + return "view is not supported"; + } + return $day->get_date_str(); + } + + /** + * Function to get activities + * @param array $current_user - user data + * @param string $free_busy - + */ + function add_Activities($current_user,$free_busy='') + { + if(isset($current_user->start_hour) && $current_user->start_hour !='') + { + list($sthour,$stmin)= explode(":",$current_user->start_hour); + $hr = $sthour+0; + $this->day_start_hour=$hr; + } + else + { + $this->day_start_hour=8; + } + if(isset($current_user->end_hour) && $current_user->end_hour !='') + { + list($endhour,$endmin)=explode(":",$current_user->end_hour); + $endhour = $endhour+0; + $this->day_end_hour=$endhour; + } + else + { + $this->day_end_hour=23; + } + if ( $this->view == 'week') + { + $start_datetime = $this->date_time->getThisweekDaysbyIndex(0); + $end_datetime = $this->date_time->getThisweekDaysbyIndex(6); + } elseif($this->view == 'month') { + $start_datetime = $this->date_time->getThismonthDaysbyIndex(0); + $end_datetime = $this->date_time->getThismonthDaysbyIndex($this->date_time->daysinmonth-1); + } elseif($this->view == 'year'){ + $start_datetime = $this->date_time->getThisyearMonthsbyIndex(0); + $end_datetime = $this->date_time->get_first_day_of_changed_year('increment'); + }else { + $start_datetime = $this->date_time; + $end_datetime = $this->date_time->getTodayDatetimebyIndex(23); + } + + $activities = Array(); + $activities = Appointment::readAppointment($current_user->id,$start_datetime,$end_datetime,$this->view); + if(!empty($activities)) + { + foreach($activities as $key=>$value) + { + if($this->view == 'day') + { + array_push($this->day_slice[$value->formatted_datetime]->activities, $value); + } + elseif($this->view == 'week') + { + array_push($this->week_slice[$value->formatted_datetime]->activities, $value); + } + elseif($this->view == 'month') + { + array_push($this->month_array[$value->formatted_datetime]->activities,$value); + } + elseif($this->view == 'year') + { + array_push($this->year_array[$value->formatted_datetime]->activities,$value); + } + else + die("view:".$this->view." is not defined"); + + } + } + + } +} + +class Layout +{ + var $view = 'day'; + var $start_time; + var $end_time; + var $activities = Array(); + + /** + * Constructor for Layout class + * @param string $view - calendarview + * @param string $time - time string + */ + + function Layout($view,$time) + { + $this->view = $view; + $this->start_time = $time; + if ( $view == 'month') + $this->end_time = $this->start_time->getMonthendtime(); + if ( $view == 'day') + $this->end_time = $this->start_time->getDayendtime(); + if ( $view == 'hour') + $this->end_time = $this->start_time->getHourendtime(); + } + + /** + * Function to get view + * return currentview + */ + + function getView() + { + return $this->view; + } +} + +/** + * this function returns the days in a month in an array format + * @param object $date_time - the date time object for the current month + * @return array $result - the array containing current months days information + */ +function getCalendarDaysInMonth($date_time){ + global $current_user; + $month_array = array(); + $slices = array(); + $monthview_days = $date_time->daysinmonth; + + $firstday_of_month = $date_time->getThisMonthsDayByIndex(0); + $fdom = $firstday_of_month; + + $num_of_prev_days = ($fdom->dayofweek+1)%7-1; + for($i=-$num_of_prev_days;$i<42;$i++){ + $pd = $date_time->getThisMonthsDayByIndex($i); + + $layout = new Layout('day', $pd); + $month_array[$layout->start_time->get_formatted_date()] = $layout; + array_push($slices, $layout->start_time->get_formatted_date()); + } + + $result = array("month_array"=>$month_array, "slices"=>$slices, "date_time"=>$date_time); + return $result; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/CalendarAjax.php b/oss/vtiger/trunk/modules/Calendar/CalendarAjax.php new file mode 100644 index 00000000..ce66087f --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/CalendarAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Calendar/CalendarCommon.php b/oss/vtiger/trunk/modules/Calendar/CalendarCommon.php new file mode 100644 index 00000000..8c1097ef --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/CalendarCommon.php @@ -0,0 +1,617 @@ +pquery($query, array($id)); + $rows = $adb->num_rows($result); + for($j=0;$j<$rows;$j++) + { + + $id = $adb->query_result($result,$j,'sharedid'); + $sharedname = $adb->query_result($result,$j,'user_name'); + $sharedid[$id]=$sharedname; + + } + return $sharedid; +} + +/** + * To get the lists of vtiger_users id who shared their calendar with specified user + * @param $sharedid -- The shared user id :: Type integer + * @returns $shared_ids -- a comma seperated vtiger_users id :: Type string + */ +function getSharedCalendarId($sharedid) +{ + global $adb; + $query = "SELECT * from vtiger_sharedcalendar where sharedid=?"; + $result = $adb->pquery($query, array($sharedid)); + if($adb->num_rows($result)!=0) + { + for($j=0;$j<$adb->num_rows($result);$j++) + $userid[] = $adb->query_result($result,$j,'userid'); + $shared_ids = implode (",",$userid); + } + return $shared_ids; +} + +/** + * To get userid and username of all vtiger_users except the current user + * @param $id -- The user id :: Type integer + * @returns $user_details -- Array in the following format: + * $user_details=Array($userid1=>$username, $userid2=>$username,............,$useridn=>$username); + */ +function getOtherUserName($id) +{ + global $adb; + $user_details=Array(); + $query="select * from vtiger_users where deleted=0 and status='Active' and id!=?"; + $result = $adb->pquery($query, array($id)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $userid=$adb->query_result($result,$i,'id'); + $username=$adb->query_result($result,$i,'user_name'); + $user_details[$userid]=$username; + } + return $user_details; +} + +/** + * To get userid and username of vtiger_users in hierarchy level + * @param $id -- The user id :: Type integer + * @returns $user_details -- Array in the following format: + * $user_details=Array($userid1=>$username, $userid2=>$username,............,$useridn=>$username); + */ + +function getSharingUserName($id) +{ + global $adb,$current_user; + $user_details=Array(); + $assigned_user_id = $current_user->id; + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[getTabid('Calendar')] == 3 or $defaultOrgSharingPermission[getTabid('Calendar')] == 0)) + { + $role_seq = implode($parent_roles, "::"); + $query = "select id as id,user_name as user_name from vtiger_users where id=? and status='Active' union select vtiger_user2role.userid as id,vtiger_users.user_name as user_name 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 ? and status='Active' union select shareduserid as id,vtiger_users.user_name as user_name from vtiger_tmp_write_user_sharing_per inner join vtiger_users on vtiger_users.id=vtiger_tmp_write_user_sharing_per.shareduserid where status='Active' and vtiger_tmp_write_user_sharing_per.userid=? and vtiger_tmp_write_user_sharing_per.tabid=9"; + $params = array($current_user->id, $role_seq."::%", $current_user->id); + if (!empty($assigned_user_id)) { + $query .= " OR id=?"; + array_push($params, $assigned_user_id); + } + $query .= " order by user_name ASC"; + $result = $adb->pquery($query, $params, true, "Error filling in user array: "); + while($row = $adb->fetchByAssoc($result)) + { + $temp_result[$row['id']] = $row['user_name']; + } + $user_details = &$temp_result; + unset($user_details[$id]); + } + else + { + $user_details = get_user_array(FALSE, "Active", $id); + unset($user_details[$id]); + } + return $user_details; +} + +/** + * To get hour,minute and format + * @param $starttime -- The date&time :: Type string + * @param $endtime -- The date&time :: Type string + * @param $format -- The format :: Type string + * @returns $timearr :: Type Array +*/ +function getaddEventPopupTime($starttime,$endtime,$format) +{ + $timearr = Array(); + list($sthr,$stmin) = explode(":",$starttime); + list($edhr,$edmin) = explode(":",$endtime); + if($format == 'am/pm') + { + $hr = $sthr+0; + $timearr['startfmt'] = ($hr >= 12) ? "pm" : "am"; + if($hr == 0) $hr = 12; + $timearr['starthour'] = twoDigit(($hr>12)?($hr-12):$hr); + $timearr['startmin'] = $stmin; + + $edhr = $edhr+0; + $timearr['endfmt'] = ($edhr >= 12) ? "pm" : "am"; + if($edhr == 0) $edhr = 12; + $timearr['endhour'] = twoDigit(($edhr>12)?($edhr-12):$edhr); + $timearr['endmin'] = $edmin; + return $timearr; + } + if($format == '24') + { + $timearr['starthour'] = twoDigit($sthr); + $timearr['startmin'] = $stmin; + $timearr['startfmt'] = ''; + $timearr['endhour'] = twoDigit($edhr); + $timearr['endmin'] = $edmin; + $timearr['endfmt'] = ''; + return $timearr; + } +} + +/** + *To construct time select combo box + *@param $format -- the format :: Type string + *@param $bimode -- The mode :: Type string + *constructs html select combo box for time selection + *and returns it in string format. + */ +function getTimeCombo($format,$bimode,$hour='',$min='',$fmt='',$todocheck=false) +{ + global $mod_strings; + $combo = ''; + $min = $min - ($min%5); + if($bimode == 'start' && !$todocheck) + $jsfn = 'onChange="changeEndtime_StartTime(document.EditView.activitytype.value);"'; + else + $jsfn = null; + if($format == 'am/pm') + { + $combo .= ' '; + $combo .= ' '; + $combo .= ''; + } + else + { + $combo .= ''.$mod_strings[LBL_HR].' '; + $combo .= ' '.$mod_strings[LBL_MIN].''; + } + return $combo; +} + +/** + *Function to construct HTML select combo box + *@param $fieldname -- the field name :: Type string + *@param $tablename -- The table name :: Type string + *constructs html select combo box for combo field + *and returns it in string format. + */ + +function getActFieldCombo($fieldname,$tablename) +{ + global $adb, $mod_strings,$current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $combo = ''; + $js_fn = ''; + if($fieldname == 'eventstatus') + $js_fn = 'onChange = "getSelectedStatus();"'; + $combo .= ''; + return $combo; +} + +/*Fuction to get value for Assigned To field + *returns values of Assigned To field in array format +*/ +function getAssignedTo($tabid) +{ + global $current_user,$noof_group_rows,$adb; + $assigned_user_id = $current_user->id; + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[$tabid] == 3 or $defaultOrgSharingPermission[$tabid] == 0)) + { + $result=get_current_user_access_groups('Calendar'); + } + else + { + $result = get_group_options(); + } + if($result) $nameArray = $adb->fetch_array($result); + + if($is_admin==false && $profileGlobalPermission[2] == 1 && ($defaultOrgSharingPermission[$tabid] == 3 or $defaultOrgSharingPermission[$tabid] == 0)) + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id,'private'), $assigned_user_id); + } + else + { + $users_combo = get_select_options_array(get_user_array(FALSE, "Active", $assigned_user_id), $assigned_user_id); + } + if($noof_group_rows!=0) + { + do + { + $groupname=$nameArray["groupname"]; + $group_option[] = array($groupname=>$selected); + + }while($nameArray = $adb->fetch_array($result)); + } + $fieldvalue[]=$users_combo; + $fieldvalue[] = $group_option; + return $fieldvalue; +} + +//Code Added by Minnie -Ends +/** + * Function to get the vtiger_activity details for mail body + * @param string $description - activity description + * @param string $from - to differenciate from notification to invitation. + * return string $list - HTML in string format + */ +function getActivityDetails($description,$user_id,$from='') +{ + global $log,$current_user; + global $adb,$mod_strings; + $log->debug("Entering getActivityDetails(".$description.") method ..."); + + $updated = $mod_strings['LBL_UPDATED']; + $created = $mod_strings['LBL_CREATED']; + $reply = (($description['mode'] == 'edit')?"$updated":"$created"); + if($description['activity_mode'] == "Events") + { + $end_date_lable=$mod_strings['End date and time']; + } + else + { + $end_date_lable=$mod_strings['Due Date']; + } + + $name = getUserName($user_id); + + if($from == "invite") + $msg = getTranslatedString($mod_strings['LBL_ACTIVITY_INVITATION']); + else + $msg = getTranslatedString($mod_strings['LBL_ACTIVITY_NOTIFICATION']); + + $current_username = getUserName($current_user->id); + $status = getTranslatedString($description['status']); + + $list = $name.','; + $list .= '

'.$msg.' '.$reply.'.
'.$mod_strings['LBL_DETAILS_STRING'].':
'; + $list .= '
      '.$mod_strings["LBL_SUBJECT"].' '.$description['subject']; + $list .= '
      '.$mod_strings["Start date and time"].' : '.$description['st_date_time']; + $list .= '
      '.$end_date_lable.' : '.$description['end_date_time']; + $list .= '
      '.$mod_strings["LBL_STATUS"].': '.$status; + $list .= '
      '.$mod_strings["Priority"].': '.getTranslatedString($description['taskpriority']); + $list .= '
      '.$mod_strings["Related To"].': '.getTranslatedString($description['relatedto']); + if(!empty($description['contact_name'])) + { + $list .= '
      '.$mod_strings["LBL_CONTACT_LIST"].' '.$description['contact_name']; + } + else + $list .= '
      '.$mod_strings["Location"].' : '.$description['location']; + + $list .= '
      '.$mod_strings["LBL_APP_DESCRIPTION"].': '.$description['description']; + $list .= '

'.$mod_strings["LBL_REGARDS_STRING"].' ,'; + $list .= '
'.$current_username.'.'; + + $log->debug("Exiting getActivityDetails method ..."); + return $list; +} + +function twoDigit( $no ){ + if($no < 10 && strlen(trim($no)) < 2) return "0".$no; + else return "".$no; +} + +function timeString($datetime,$fmt){ + + if(is_object($datetime)){ + $hr = $datetime->hour; + $min = $datetime->minute; + } else { + $hr = $datetime['hour']; + $min = $datetime['minute']; + } + $timeStr = ""; + if($fmt != 'am/pm'){ + $timeStr .= twoDigit($hr).":".twoDigit($min); + }else{ + $am = ($hr >= 12) ? "pm" : "am"; + if($hr == 0) $hr = 12; + $timeStr .= ($hr>12)?($hr-12):$hr; + $timeStr .= ":".twoDigit($min); + $timeStr .= $am; + } + return $timeStr; +} +//added to fix Ticket#3068 +function getEventNotification($mode,$subject,$desc) +{ + global $current_user,$adb; + require_once("modules/Emails/mail.php"); + $subject = $mode.' : '.$subject; + $crmentity = new CRMEntity(); + if($desc['assingn_type'] == "U") + { + $to_email = getUserEmailId('id',$desc['user_id']); + $description = getActivityDetails($desc,$desc['user_id']); + send_mail('Calendar',$to_email,$current_user->user_name,'',$subject,$description); + } + if($desc['assingn_type'] == "T") + { + $groupid = ''; + $groupname=$desc['group_name']; + // getGroupName API was changed to return array of two elements! + if(is_array($groupname) && !empty($groupname)) { + $groupid = $groupname[1]; + $groupname = $groupname[0]; + } else { + $resultqry=$adb->pquery("select groupid from vtiger_groups where groupname=?", array($groupname)); + $groupid=$adb->query_result($resultqry,0,"groupid"); + } + require_once('include/utils/GetGroupUsers.php'); + $getGroupObj=new GetGroupUsers(); + $getGroupObj->getAllUsersInGroup($groupid); + $userIds=$getGroupObj->group_users; + if (count($userIds) > 0) { + $groupqry="select email1,id from vtiger_users where id in(".generateQuestionMarks($userIds).")"; + $groupqry_res=$adb->pquery($groupqry, array($userIds)); + $noOfRows = $adb->num_rows($groupqry_res); + for($z=0;$z < $noOfRows;$z++) + { + $emailadd = $adb->query_result($groupqry_res,$z,'email1'); + $curr_userid = $adb->query_result($groupqry_res,$z,'id'); + $description = getActivityDetails($desc,$curr_userid); + $mail_status = send_mail('Calendar',$emailadd,getUserName($curr_userid),'',$subject,$description); + + } + } + } +} + +function sendInvitation($inviteesid,$mode,$subject,$desc) +{ + global $current_user,$mod_strings; + require_once("modules/Emails/mail.php"); + $invites=$mod_strings['INVITATION']; + $invitees_array = explode(';',$inviteesid); + $subject = $invites.' : '.$subject; + $record = $focus->id; + foreach($invitees_array as $inviteeid) + { + if($inviteeid != '') + { + $description=getActivityDetails($desc,$inviteeid,"invite"); + $to_email = getUserEmailId('id',$inviteeid); + send_mail('Calendar',$to_email,$current_user->user_name,'',$subject,$description); + } + } + +} + +function getActivityMailInfo($return_id,$status,$activity_type) +{ + $mail_data = Array(); + global $adb; + $qry = "select * from vtiger_activity where activityid=?"; + $ary_res = $adb->pquery($qry, array($return_id)); + $send_notification = $adb->query_result($ary_res,0,"sendnotification"); + $subject = $adb->query_result($ary_res,0,"subject"); + $priority = $adb->query_result($ary_res,0,"priority"); + $st_date = $adb->query_result($ary_res,0,"date_start"); + $st_time = $adb->query_result($ary_res,0,"time_start"); + $end_date = $adb->query_result($ary_res,0,"due_date"); + $end_time = $adb->query_result($ary_res,0,"time_end"); + $location = $adb->query_result($ary_res,0,"location"); + + $owner_qry = "select smownerid from vtiger_crmentity where crmid=?"; + $res = $adb->pquery($owner_qry, array($return_id)); + $owner_id = $adb->query_result($res,0,"smownerid"); + + $usr_res = $adb->pquery("select count(*) as count from vtiger_users where id=?",array($owner_id)); + if($adb->query_result($usr_res, 0, 'count')>0) { + $assignType = "U"; + $usr_id = $owner_id; + } + else { + $assignType = "T"; + $group_qry = "select groupname from vtiger_groups where groupid=?"; + $grp_res = $adb->pquery($group_qry, array($owner_id)); + $grp_name = $adb->query_result($grp_res,0,"groupname"); + } + + $desc_qry = "select description from vtiger_crmentity where crmid=?"; + $des_res = $adb->pquery($desc_qry, array($return_id)); + $description = $adb->query_result($des_res,0,"description"); + + + $rel_qry = "select case vtiger_crmentity.setype when 'Leads' then vtiger_leaddetails.lastname when 'Accounts' then vtiger_account.accountname when 'Potentials' then vtiger_potential.potentialname when 'Quotes' then vtiger_quotes.subject when 'PurchaseOrder' then vtiger_purchaseorder.subject when 'SalesOrder' then vtiger_salesorder.subject when 'Invoice' then vtiger_invoice.subject when 'Campaigns' then vtiger_campaign.campaignname when 'HelpDesk' then vtiger_troubletickets.title end as relname from vtiger_seactivityrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_seactivityrel.crmid left join vtiger_leaddetails on vtiger_leaddetails.leadid = vtiger_seactivityrel.crmid left join vtiger_account on vtiger_account.accountid=vtiger_seactivityrel.crmid left join vtiger_potential on vtiger_potential.potentialid=vtiger_seactivityrel.crmid left join vtiger_quotes on vtiger_quotes.quoteid= vtiger_seactivityrel.crmid left join vtiger_purchaseorder on vtiger_purchaseorder.purchaseorderid = vtiger_seactivityrel.crmid left join vtiger_salesorder on vtiger_salesorder.salesorderid = vtiger_seactivityrel.crmid left join vtiger_invoice on vtiger_invoice.invoiceid = vtiger_seactivityrel.crmid left join vtiger_campaign on vtiger_campaign.campaignid = vtiger_seactivityrel.crmid left join vtiger_troubletickets on vtiger_troubletickets.ticketid = vtiger_seactivityrel.crmid where vtiger_seactivityrel.activityid=?"; + $rel_res = $adb->pquery($rel_qry, array($return_id)); + $rel_name = $adb->query_result($rel_res,0,"relname"); + + + $cont_qry = "select * from vtiger_cntactivityrel where activityid=?"; + $cont_res = $adb->pquery($cont_qry, array($return_id)); + $cont_id = $adb->query_result($cont_res,0,"contactid"); + $cont_name = ''; + if($cont_id != '') + { + $cont_name = getContactName($cont_id); + } + $mail_data['mode'] = "edit"; + $mail_data['activity_mode'] = $activity_type; + $mail_data['sendnotification'] = $send_notification; + $mail_data['user_id'] = $usr_id; + $mail_data['subject'] = $subject; + $mail_data['status'] = $status; + $mail_data['taskpriority'] = $priority; + $mail_data['relatedto'] = $rel_name; + $mail_data['contact_name'] = $cont_name; + $mail_data['description'] = $description; + $mail_data['assingn_type'] = $assignType; + $mail_data['group_name'] = $grp_name; + $value = getaddEventPopupTime($st_time,$end_time,'24'); + $start_hour = $value['starthour'].':'.$value['startmin'].''.$value['startfmt']; + if($activity_type != 'Task' ) + $end_hour = $value['endhour'] .':'.$value['endmin'].''.$value['endfmt']; + $mail_data['st_date_time']=getDisplayDate($st_date)." ".$start_hour; + $mail_data['end_date_time']=getDisplayDate($end_date)." ".$end_hour; + $mail_data['location']=$location; + return $mail_data; + + +} + +// User Select Customization +/** + * Function returns the id of the User selected by current user in the picklist of the ListView or Calendar view of Current User + * return String - Id of the user that the current user has selected + */ +function calendarview_getSelectedUserId() { + global $current_user, $default_charset; + $only_for_user = htmlspecialchars(strip_tags($_REQUEST['onlyforuser']),ENT_QUOTES,$default_charset); + if($only_for_user == '') $only_for_user = $current_user->id; + return $only_for_user; +} + +function calendarview_getSelectedUserFilterQuerySuffix() { + global $current_user, $adb; + $only_for_user = calendarview_getSelectedUserId(); + $qcondition = ''; + if(!empty($only_for_user)) { + if($only_for_user != 'ALL') { + // For logged in user include the group records also. + if($only_for_user == $current_user->id) { + $user_group_ids = fetchUserGroupids($current_user->id); + // User does not belong to any group? Let us reset to non-existent group + if(!empty($user_group_ids)) $user_group_ids .= ','; + else $user_group_ids = ''; + $user_group_ids .= $current_user->id; + $qcondition = " AND vtiger_crmentity.smownerid IN (" . $user_group_ids .")"; + } else { + $qcondition = " AND vtiger_crmentity.smownerid = " . $adb->sql_escape_string($only_for_user); + } + } + } + return $qcondition; +} + +/** + * Function returns the data of the user selected by current user in the picklist of the ListView or Calendar view of Current User + * @param $useridInUse - The Id of the user that the Current User has selected in dropdown picklist in Calendar modules listview or Calendar View + * return string - The array of the events for the user that the current user has selected + */ +function calendarview_getUserSelectOptions($useridInUse) { + global $adb, $app_strings, $current_user, $mod_strings; + $users = $adb->query("SELECT id,user_name FROM vtiger_users WHERE status = 'Active' and deleted = 0"); + $userscount = $adb->num_rows($users); + + $userSelectdata = "" . $app_strings['LBL_LIST_OF'] . " : "; + $userSelectdata .=""; + return $userSelectdata; +} +// END + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/CustomView.php b/oss/vtiger/trunk/modules/Calendar/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Calendar/Date.php b/oss/vtiger/trunk/modules/Calendar/Date.php new file mode 100644 index 00000000..b89bd64f --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Date.php @@ -0,0 +1,511 @@ +setDateTime(null); + } + else if ( isset( $timearr['ts'])) + { + $this->setDateTime($time['ts']); + } + else + { + if(isset($timearr['hour']) && $timearr['hour'] !== '') + { + $this->hour = $timearr['hour']; + } + if(isset($timearr['min']) && $timearr['min'] !== '') + { + $this->minute = $timearr['min']; + } + if(isset($timearr['sec']) && $timearr['sec'] !== '') + { + $this->second = $timearr['sec']; + } + if(isset($timearr['day']) && $timearr['day'] !== '') + { + $this->day = $timearr['day']; + } + if(isset($timearr['week']) && $timearr['week'] !== '') + { + $this->week = $timearr['week']; + } + if(isset($timearr['month']) && $timearr['month'] !== '') + { + $this->month = $timearr['month']; + } + if(isset($timearr['year']) && $timearr['year'] >= 1970) + { + $this->year = $timearr['year']; + } + else + { + return null; + } + } + if ($check) + { + $this->getDateTime(); + } + } + + /** + * function to get date and time using index + * @param integer $index - number between 0 to 23 + * @param string $day - date + * @param string $month - month + * @param string $year - year + * return vt_DateTime obj $datetimevalue + */ + function getTodayDatetimebyIndex($index,$day='', $month='', $year=''){ + if($day === '') + $day = $this->day; + if($month === '') + $month = $this->month; + if($year === '') + $year = $this->year; + $day_array = array(); + + if($index < 0 || $index > 23){ + die("hour is invalid"); + } + + $day_array['hour'] = $index; + $day_array['min'] = 0; + $day_array['day'] = $day; + $day_array['month'] = $month; + $day_array['year'] = $year; + $datetimevalue = new vt_DateTime($day_array,true); + return $datetimevalue; + } + + /** + * function to get days in week using index + * @param integer $index - number between 0 to 6 + * return vt_DateTime obj $datetimevalue + */ + function getThisweekDaysbyIndex($index){ + $week_array = array(); + if($index < 0 || $index > 6){ + die("day is invalid"); + } + $week_array['day'] = $this->day + ($index - $this->dayofweek); + $week_array['month'] = $this->month; + $week_array['year'] = $this->year; + $datetimevalue = new vt_DateTime($week_array,true); + return $datetimevalue; + } + + /** + * function to get days in month using index + * + * This function will be deprecated. + * The newer version is getThisMonthsDayByIndex() and should be used wherever possible + * + * @param integer $index - number between 0 to 42 + * @param string $day - date + * @param string $month - month + * @param string $year - year + * return vt_DateTime obj $datetimevalue + */ + + function getThismonthDaysbyIndex($index,$day='', $month='', $year='') + { + if($day == '') + $day = $index+1; + if($month == '') + $month = $this->month; + if($year == '') + $year = $this->year; + $month_array = array(); + $month_array['day'] = $day; + $month_array['month'] = $month; + $month_array['year'] = $year; + $datetimevalue = new vt_DateTime($month_array,true); + return $datetimevalue; + } + + /** + * function to get months in year using index + * @param integer $index - number between 0 to 11 + * return vt_DateTime obj $datetimevalue + */ + + function getThisyearMonthsbyIndex($index) + { + $year_array = array(); + $year_array['day'] = 1; + if($index < 0 || $index > 11) + { + die("month is invalid"); + } + $year_array['month'] = $index+1; + $year_array['year'] = $this->year; + $datetimevalue = new vt_DateTime($year_array,true); + return $datetimevalue; + } + + /** + * function to get hour end time + * return vt_DateTime obj $datetimevalue + */ + + function getHourendtime() + { + $date_array = array(); + $date_array['hour'] = $this->hour; + $date_array['min'] = 59; + $date_array['day'] = $this->day; + $date_array['sec'] = 59; + $date_array['month'] = $this->month; + $date_array['year'] = $this->year; + $datetimevalue = new vt_DateTime($date_array,true); + return $datetimevalue; + } + + /** + * function to get day end time + * return vt_DateTime obj $datetimevalue + */ + function getDayendtime() + { + $date_array = array(); + $date_array['hour'] = 23; + $date_array['min'] = 59; + $date_array['sec'] = 59; + $date_array['day'] = $this->day; + $date_array['month'] = $this->month; + $date_array['year'] = $this->year; + $datetimevalue = new vt_DateTime($date_array,true); + return $datetimevalue; + } + + /** + * function to get month end time + * return vt_DateTime obj $datetimevalue + */ + function getMonthendtime() + { + $date_array = array(); + $date_array['hour'] = 23; + $date_array['min'] = 59; + $date_array['sec'] = 59; + $date_array['day'] = $this->daysinmonth; + $date_array['month'] = $this->month; + $date_array['year'] = $this->year; + $datetimevalue = new vt_DateTime($date_array,true); + return $datetimevalue; + } + + /** + * function to get day of week + * return string $this->day - day (eg: Monday) + */ + function get_Date() + { + return $this->day; + } + + /** + * function to get month name in short + * return string $this->month_inshort - month name (eg: Jan) + */ + function getmonthName_inshort(){ + return $this->month_inshort; + } + /** + * function to get month name + * return string $this->month - month name + */ + function getMonth(){ + return $this->month; + } + /** + * function to get month name + * return string $this->month_inlong - month name + */ + function getmonthName(){ + return $this->month_inlong; + } + + /** + * function to get day of week + * return string $this->dayofweek_inlong - day of week + */ + function getdayofWeek(){ + return $this->dayofweek_inlong; + } + /** + * function to get day of week in short + * return string $this->dayofweek_inshort - day of week (eg: Mon) + */ + + function getdayofWeek_inshort(){ + return $this->dayofweek_inshort; + } + + /** + * function to set values for vt_DateTime object + * @param integer $ts - Time stamp + */ + function setDateTime($ts){ + global $mod_strings; + if (empty($ts)){ + $ts = time(); + } + + $this->ts = $ts; + $this->ts_def = $this->ts; + $date_string = date('i::G::H::j::d::t::w::z::L::W::n::m::Y::Z::T::s',$ts); + + list($this->minute,$this->hour,$this->z_hour,$this->day,$this->z_day,$this->daysinmonth,$this->dayofweek,$this->dayofyear,$is_leap,$this->week,$this->month,$this->z_month,$this->year,$this->offset,$this->tz,$this->second) = split('::',$date_string); + + $this->dayofweek_inshort =$mod_strings['cal_weekdays_short'][$this->dayofweek]; + $this->dayofweek_inlong=$mod_strings['cal_weekdays_long'][$this->dayofweek]; + $this->month_inshort=$mod_strings['cal_month_short'][$this->month]; + $this->month_inlong=$mod_strings['cal_month_long'][$this->month]; + + $this->daysinyear = 365; + + if ($is_leap == 1){ + $this->daysinyear += 1; + } + } + + /** + * function to get values from vt_DateTime object + */ + function getDateTime() + { + global $mod_strings; + $hour = 0; + $minute = 0; + $second = 0; + $day = 1; + $month = 1; + $year = 1970; + + if ( isset($this->second) && $this->second !== ''){ + $second = $this->second; + } + if ( isset($this->minute) && $this->minute !== ''){ + $minute = $this->minute; + } + if ( isset($this->hour) && $this->hour !== '') + { + $hour = $this->hour; + } + if ( isset($this->day) && $this->day !== ''){ + $day= $this->day; + } + if ( isset($this->month) && $this->month !== ''){ + $month = $this->month; + } + + if ( isset($this->year) && $this->year !== ''){ + $year = $this->year; + }else{ + die("year was not set"); + } + if(empty($hour) && $hour !== 0) $hour = 0; + $this->ts = mktime($hour,$minute,$second,$month,$day,$year); + $this->setDateTime($this->ts); + } + + /** + * function to get mysql formatted date + * return formatted date in string format + */ + function get_formatted_date(){ + return $this->year."-".$this->z_month."-".$this->z_day; + } + /** + * function to get mysql formatted time + * return formatted time in string format + */ + function get_formatted_time(){ + return $this->z_hour.":".$this->min; + } + + /** + * function to get date depends on mode value + * @param string $mode - 'increment' or 'decrement' + * return vt_DateTime obj + */ + function get_changed_day($mode){ + if($mode == 'increment') + $day = $this->day + 1; + else + $day = $this->day - 1; + $date_data = array('day'=>$day, + 'month'=>$this->month, + 'year'=>$this->year + ); + return new vt_DateTime($date_data,true); + } + + /** + * function to get changed week depends on mode value + * @param string $mode - 'increment' or 'decrement' + * return vt_DateTime obj + */ + function get_first_day_of_changed_week($mode){ + $first_day = $this->getThisweekDaysbyIndex(0); + if($mode == 'increment') + $day = $first_day->day + 7; + else + $day = $first_day->day - 7; + $date_data = array('day'=>$day, + 'month'=>$first_day->month, + 'year'=>$first_day->year + ); + return new vt_DateTime($date_data,true); + } + + /** + * function to get month depends on mode value + * @param string $mode - 'increment' or 'decrement' + * return vt_DateTime obj + */ + function get_first_day_of_changed_month($mode){ + $tmpDate['day'] = $this->day; + $tmpDate['month'] = $this->month; + $tmpDate['year'] = $this->year; + + if(is_array($arr) && !empty($arr)){ + $tmpDate['year'] = $arr[0]; + $tmpDate['month'] = $arr[1]; + $tmpDate['day'] = $arr[2]; + } + + if($mode == 'increment'){ + $month = $tmpDate['month'] + 1; + $year = $tmpDate['year'] ; + }else{ + if($tmpDate['month'] == 1){ + $month = 12; + $year = $tmpDate['year'] - 1; + }else{ + $month = $tmpDate['month'] - 1; + $year = $tmpDate['year'] ; + } + } + $date_data = array( + 'day'=>1, + 'month'=>$month, + 'year'=>$year + ); + + return new vt_DateTime($date_data,true); + } + + /** + * function to get year depends on mode value + * @param string $mode - 'increment' or 'decrement' + * return vt_DateTime obj + */ + function get_first_day_of_changed_year($mode){ + if($mode == 'increment'){ + $year = $this->year + 1; + }else{ + $year = $this->year - 1; + } + $date_data = array('day'=>1, + 'month'=>1, + 'year'=>$year + ); + return new vt_DateTime($date_data,true); + } + + /** + * function to get date string + * return date string + */ + function get_date_str(){ + $array = Array(); + if ( isset( $this->hour) && $this->hour != '') + { + array_push( $array, "hour=".$this->hour); + } + if ( isset( $this->day) && $this->day != '') + { + array_push( $array, "day=".$this->day); + } + if ( isset( $this->month) && $this->month) + { + array_push( $array, "month=".$this->month); + } + if ( isset( $this->year) && $this->year != '') + { + array_push( $array, "year=".$this->year); + } + return ("&".implode('&',$array)); + } + + /** + * function to get days in month using index + * + * This is the newer version of the function getThismonthDaysbyIndex(). + * This should be used whereever possible + * + * @param integer $index - number between 0 to 42 + * @param string $day - date + * @param string $month - month + * @param string $year - year + * return vt_DateTime obj $datetimevalue + */ + + function getThisMonthsDayByIndex($index){ + $day = $index; + $month = $this->month; + $year = $this->year; + $month_array = array(); + $month_array['day'] = $day; + $month_array['month'] = $month; + $month_array['year'] = $year; + $datetimevalue = new vt_DateTime($month_array,true); + return $datetimevalue; + } +} +?> diff --git a/oss/vtiger/trunk/modules/Calendar/Delete.php b/oss/vtiger/trunk/modules/Calendar/Delete.php new file mode 100644 index 00000000..e1017d8d --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Delete.php @@ -0,0 +1,36 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/DetailView.php b/oss/vtiger/trunk/modules/Calendar/DetailView.php new file mode 100644 index 00000000..74531d09 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/DetailView.php @@ -0,0 +1,358 @@ +'. $mod_strings{"LBL_NOTIFICATION_ERROR"}.'

'; +} +session_unregister('mail_send_error'); + +$focus = CRMEntity::getInstance($currentModule); +$smarty = new vtigerCRM_Smarty(); +$activity_mode = vtlib_purify($_REQUEST['activity_mode']); +//If activity_mode == null + +if($activity_mode =='' || strlen($activity_mode) < 1) +{ + $query = "select activitytype from vtiger_activity where activityid=?"; + $result = $adb->pquery($query, array($_REQUEST['record'])); + $actType = $adb->query_result($result,0,'activitytype'); + if( $actType == 'Task') + { + $activity_mode = $actType; + } + elseif($actType != 'Emails') + { + $activity_mode = 'Events'; + } +} + +if($activity_mode == 'Task') +{ + $tab_type = 'Calendar'; + $smarty->assign("SINGLE_MOD",$mod_strings['LBL_TODO']); +} +elseif($activity_mode == 'Events') +{ + $tab_type = 'Events'; + $smarty->assign("SINGLE_MOD",$mod_strings['LBL_EVENT']); +} +$tab_id=getTabid($tab_type); + + +if(isset($_REQUEST['record']) && isset($_REQUEST['record'])) { + $focus->retrieve_entity_info($_REQUEST['record'],$tab_type); + $focus->id = $_REQUEST['record']; + $focus->name=$focus->column_fields['subject']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +//needed when creating a new task with default values passed in +if (isset($_REQUEST['contactname']) && is_null($focus->contactname)) { + $focus->contactname = $_REQUEST['contactname']; +} +if (isset($_REQUEST['contact_id']) && is_null($focus->contact_id)) { + $focus->contact_id = $_REQUEST['contact_id']; +} +if (isset($_REQUEST['opportunity_name']) && is_null($focus->parent_name)) { + $focus->parent_name = $_REQUEST['opportunity_name']; +} +if (isset($_REQUEST['opportunity_id']) && is_null($focus->parent_id)) { + $focus->parent_id = $_REQUEST['opportunity_id']; +} +if (isset($_REQUEST['accountname']) && is_null($focus->parent_name)) { + $focus->parent_name = $_REQUEST['accountname']; +} +if (isset($_REQUEST['accountid']) && is_null($focus->parent_id)) { + $focus->parent_id = $_REQUEST['accountid']; +} + +$act_data = getBlocks($tab_type,"detail_view",'',$focus->column_fields); + +foreach($act_data as $block=>$entry) +{ + foreach($entry as $key=>$value) + { + foreach($value as $label=>$field) + { + $fldlabel[$field['fldname']] = $label; + if($field['ui'] == 15 || $field['ui'] == 16) + { + foreach($field['options'] as $index=>$arr_val) + { + if($arr_val[2] == "selected") + $finaldata[$field['fldname']] = $arr_val[0]; + } + } + else + { + $fldvalue = $field['value']; + if($field['fldname'] == 'description') { $fldvalue = nl2br($fldvalue); } + $finaldata[$field['fldname']] = $fldvalue; + } + + $finaldata[$field['fldname'].'link'] = $field['link']; + } + } +} + +//Start +//To set user selected hour format +if($current_user->hour_format == '') + $format = 'am/pm'; +else + $format = $current_user->hour_format; +list($stdate,$sttime) = split(' ',$finaldata['date_start']); +list($enddate,$endtime) = split(' ',$finaldata['due_date']); +$time_arr = getaddEventPopupTime($sttime,$endtime,$format); +$data['starthr'] = $time_arr['starthour']; +$data['startmin'] = $time_arr['startmin']; +$data['startfmt'] = $time_arr['startfmt']; +$data['endhr'] = $time_arr['endhour']; +$data['endmin'] = $time_arr['endmin']; +$data['endfmt'] = $time_arr['endfmt']; +$data['record'] = $focus->id; +if(isset($finaldata['sendnotification']) && $finaldata['sendnotification'] == 'yes') + $data['sendnotification'] = $mod_strings['LBL_YES']; +else + $data['sendnotification'] = $mod_strings['LBL_NO']; +$data['subject'] = $finaldata['subject']; +$data['date_start'] = $stdate; +$data['due_date'] = $enddate; +$data['assigned_user_id'] = $finaldata['assigned_user_id']; +if($mod_strings[$finaldata['taskpriority']] != '') + $data['taskpriority'] = $mod_strings[$finaldata['taskpriority']]; +else + $data['taskpriority'] = $finaldata['taskpriority']; +$data['modifiedtime'] = $finaldata['modifiedtime']; +$data['createdtime'] = $finaldata['createdtime']; +$data['parent_name'] = $finaldata['parent_id']; +$data['description'] = $finaldata['description']; +if($activity_mode == 'Task') +{ + if($mod_strings[$finaldata['taskstatus']] != '') + $data['taskstatus'] = $mod_strings[$finaldata['taskstatus']]; + else + $data['taskstatus'] = $finaldata['taskstatus']; + $data['activitytype'] = $activity_mode; + $data['contact_id'] = $finaldata['contact_id']; + $data['contact_idlink'] = $finaldata['contact_idlink']; +} +elseif($activity_mode == 'Events') +{ + $data['visibility'] = $finaldata['visibility']; + if($mod_strings[$finaldata['eventstatus']] != '') + $data['eventstatus'] = $mod_strings[$finaldata['eventstatus']]; + else + $data['eventstatus'] = $finaldata['eventstatus']; + $data['activitytype'] = $finaldata['activitytype']; + $data['location'] = $finaldata['location']; + //Calculating reminder time + $rem_days = 0; + $rem_hrs = 0; + $rem_min = 0; + if(!empty($focus->column_fields['reminder_time'])) + { + $data['set_reminder'] = $mod_strings['LBL_YES']; + $data['reminder_str'] = $finaldata['reminder_time']; + } + else + $data['set_reminder'] = $mod_strings['LBL_NO']; + //To set recurring details + $query = 'select vtiger_recurringevents.recurringfreq,vtiger_recurringevents.recurringinfo from vtiger_recurringevents where vtiger_recurringevents.activityid = ?'; + $res = $adb->pquery($query, array($focus->id)); + $rows = $adb->num_rows($res); + if($rows != 0) + { + $data['recurringcheck'] = $mod_strings['LBL_YES']; + $data['repeat_frequency'] = $adb->query_result($res,0,'recurringfreq'); + $recurringinfo = explode("::",$adb->query_result($res,0,'recurringinfo')); + $data['recurringtype'] = $recurringinfo[0]; + if($recurringinfo[0] == 'Weekly') + { + $weekrpt_str = ''; + if(count($recurringinfo) > 1) + { + $weekrpt_str .= 'on '; + for($i=1;$ipquery($sql, array($focus->id)); + $num_rows=$adb->num_rows($result); + $invited_users=Array(); + for($i=0;$i<$num_rows;$i++) + { + $userid=$adb->query_result($result,$i,'inviteeid'); + $username=$adb->query_result($result,$i,'user_name'); + $invited_users[$userid]=$username; + } + $smarty->assign("INVITEDUSERS",$invited_users); + $related_array = getRelatedLists("Calendar", $focus); + $smarty->assign("CONTACTS",$related_array['Contacts']['entries']); + + $is_fname_permitted = getFieldVisibilityPermission("Contacts", $current_user->id, 'firstname'); + $smarty->assign("IS_PERMITTED_CNT_FNAME",$is_fname_permitted); + + +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Calendar-Activities detail view"); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("ACTIVITY_MODE", $activity_mode); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string'].'&activity_mode='.$activity_mode); +$smarty->assign("ID", $focus->id); +$smarty->assign("NAME", $focus->name); +$smarty->assign("BLOCKS", $act_data); +$smarty->assign("LABEL", $fldlabel); +$smarty->assign("VIEWTYPE", vtlib_purify($_REQUEST['viewtype'])); +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("ACTIVITYDATA", $data); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +//get Description Information +if(isPermitted("Calendar","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("Calendar","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + + $tabid = getTabid($tab_type); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data2 = split_validationdataArray($validationData); + + $smarty->assign("VALIDATION_DATA_FIELDNAME",$data2['fieldname']); + $smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data2['datatype']); + $smarty->assign("VALIDATION_DATA_FIELDLABEL",$data2['fieldlabel']); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// 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), 'DETAILVIEW', $customlink_params)); +// END + +$custom_fields_data = getCalendarCustomFields($tabid,'detail_view',$focus->column_fields); +$smarty->assign("CUSTOM_FIELDS_DATA", $custom_fields_data); + +$smarty->display("ActivityDetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/EditView.php b/oss/vtiger/trunk/modules/Calendar/EditView.php new file mode 100644 index 00000000..671ad994 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/EditView.php @@ -0,0 +1,297 @@ +assign("SEARCH", $searchurl); +//4600 ends + +$activity_mode = vtlib_purify($_REQUEST['activity_mode']); +if($activity_mode == 'Task') +{ + $tab_type = 'Calendar'; + $taskcheck = true; + $smarty->assign("SINGLE_MOD",$mod_strings['LBL_TODO']); +} +elseif($activity_mode == 'Events') +{ + $tab_type = 'Events'; + $taskcheck = false; + $smarty->assign("SINGLE_MOD",$mod_strings['LBL_EVENT']); +} + +if(isset($_REQUEST['record']) && $_REQUEST['record']!='') { + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],$tab_type); + $focus->name=$focus->column_fields['subject']; + $sql = 'select vtiger_users.user_name,vtiger_invitees.* from vtiger_invitees left join vtiger_users on vtiger_invitees.inviteeid=vtiger_users.id where activityid=?'; + $result = $adb->pquery($sql, array($focus->id)); + $num_rows=$adb->num_rows($result); + $invited_users=Array(); + for($i=0;$i<$num_rows;$i++) + { + $userid=$adb->query_result($result,$i,'inviteeid'); + $username=$adb->query_result($result,$i,'user_name'); + $invited_users[$userid]=$username; + } + $smarty->assign("INVITEDUSERS",$invited_users); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $related_array = getRelatedLists("Calendar", $focus); + $cntlist = $related_array['Contacts']['entries']; + $is_fname_permitted = getFieldVisibilityPermission("Contacts", $current_user->id, 'firstname'); + $cnt_idlist = ''; + $cnt_namelist = ''; + if($cntlist != '') + { + $i = 0; + foreach($cntlist as $key=>$cntvalue) + { + if($i != 0) + { + $cnt_idlist .= ';'; + $cnt_namelist .= "\n"; + } + $cnt_idlist .= $key; + $contName = eregi_replace("(]*>)(.*)()", "\\2", $cntvalue[0]); + if ($is_fname_permitted == '0') $contName .= ' '.eregi_replace("(]*>)(.*)()", "\\2", $cntvalue[1]); + $cnt_namelist .= ''; + $i++; + } + } + $smarty->assign("CONTACTSID",$cnt_idlist); + $smarty->assign("CONTACTSNAME",$cnt_namelist); + $query = 'select vtiger_recurringevents.recurringfreq,vtiger_recurringevents.recurringinfo from vtiger_recurringevents where vtiger_recurringevents.activityid = ?'; + $res = $adb->pquery($query, array($focus->id)); + $rows = $adb->num_rows($res); + if($rows != 0) + { + $value['recurringcheck'] = 'Yes'; + $value['repeat_frequency'] = $adb->query_result($res,0,'recurringfreq'); + $recurringinfo = explode("::",$adb->query_result($res,0,'recurringinfo')); + $value['eventrecurringtype'] = $recurringinfo[0]; + if($recurringinfo[0] == 'Weekly') + { + for($i=0;$i<6;$i++) + { + $label = 'week'.$recurringinfo[$i+1]; + $value[$label] = 'checked'; + } + } + elseif($recurringinfo[0] == 'Monthly') + { + $value['repeatMonth'] = $recurringinfo[1]; + if($recurringinfo[1] == 'date') + { + $value['repeatMonth_date'] = $recurringinfo[2]; + } + else + { + $value['repeatMonth_daytype'] = $recurringinfo[2]; + $value['repeatMonth_day'] = $recurringinfo[3]; + } + } + } + else + { + $value['recurringcheck'] = 'No'; + } + +}else +{ + if(isset($_REQUEST['contact_id']) && $_REQUEST['contact_id']!=''){ + $smarty->assign("CONTACTSID",$_REQUEST['contact_id']); + $contact_name = ""; + $smarty->assign("CONTACTSNAME",$contact_name); + $account_id = $_REQUEST['account_id']; + $account_name = getAccountName($account_id); + } +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} +$userDetails=getOtherUserName($current_user->id); +$to_email = getUserEmailId('id',$current_user->id); +$smarty->assign("CURRENTUSERID",$current_user->id); + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') +{ + $act_data = getBlocks($tab_type,$disp_view,$mode,$focus->column_fields); +} +else +{ + $act_data = getBlocks($tab_type,$disp_view,$mode,$focus->column_fields,'BAS'); +} +$smarty->assign("BLOCKS",$act_data); +foreach($act_data as $header=>$blockitem) +{ + foreach($blockitem as $row=>$data) + { + foreach($data as $key=>$maindata) + { + $uitype[$maindata[2][0]] = $maindata[0][0]; + $fldlabel[$maindata[2][0]] = $maindata[1][0]; + $fldlabel_sel[$maindata[2][0]] = $maindata[1][1]; + $fldlabel_combo[$maindata[2][0]] = $maindata[1][2]; + $value[$maindata[2][0]] = $maindata[3][0]; + $secondvalue[$maindata[2][0]] = $maindata[3][1]; + $thirdvalue[$maindata[2][0]] = $maindata[3][2]; + } + } +} +// jread.topik. patch account_id for create contact +if (strlen($account_name) > 0) +{ + $fldlabel_sel['parent_id'][1]='selected'; + $secondvalue['parent_id'] = $account_id; + $value['parent_id'] = $account_name; +} + +$format = ($current_user->hour_format == '')?'am/pm':$current_user->hour_format; +$stdate = key($value['date_start']); +$enddate = key($value['due_date']); +$sttime = $value['date_start'][$stdate]; +$endtime = $value['due_date'][$enddate]; +$time_arr = getaddEventPopupTime($sttime,$endtime,$format); +$value['starthr'] = $time_arr['starthour']; +$value['startmin'] = $time_arr['startmin']; +$value['startfmt'] = $time_arr['startfmt']; +$value['endhr'] = $time_arr['endhour']; +$value['endmin'] = $time_arr['endmin']; +$value['endfmt'] = $time_arr['endfmt']; +$smarty->assign("STARTHOUR",getTimeCombo($format,'start',$time_arr['starthour'],$time_arr['startmin'],$time_arr['startfmt'],$taskcheck)); +$smarty->assign("ENDHOUR",getTimeCombo($format,'end',$time_arr['endhour'],$time_arr['endmin'],$time_arr['endfmt'])); +$smarty->assign("FOLLOWUP",getTimeCombo($format,'followup_start',$time_arr['endhour'],$time_arr['endmin'],$time_arr['endfmt'])); +$smarty->assign("ACTIVITYDATA",$value); +$smarty->assign("LABEL",$fldlabel); +$smarty->assign("secondvalue",$secondvalue); +$smarty->assign("thirdvalue",$thirdvalue); +$smarty->assign("fldlabel_combo",$fldlabel_combo); +$smarty->assign("fldlabel_sel",$fldlabel_sel); +$smarty->assign("OP_MODE",$disp_view); +$smarty->assign("ACTIVITY_MODE",$activity_mode); +$smarty->assign("HOURFORMAT",$format); +$smarty->assign("USERSLIST",$userDetails); +$smarty->assign("USEREMAILID",$to_email); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("DATEFORMAT",parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Activity edit view"); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); + +if($focus->mode == 'edit') +{ + $smarty->assign("MODE", $focus->mode); +} + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +// Unimplemented until jscalendar language vtiger_files are fixed +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +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['ticket_id'])) + $smarty->assign("TICKETID", $_REQUEST['ticket_id']); +if (isset($_REQUEST['product_id'])) + $smarty->assign("PRODUCTID", $_REQUEST['product_id']); +if (isset($_REQUEST['return_viewname'])) + $smarty->assign("RETURN_VIEWNAME", vtlib_purify($_REQUEST['return_viewname'])); +if(isset($_REQUEST['view']) && $_REQUEST['view']!='') + $smarty->assign("view",vtlib_purify($_REQUEST['view'])); +if(isset($_REQUEST['hour']) && $_REQUEST['hour']!='') + $smarty->assign("hour",vtlib_purify($_REQUEST['hour'])); +if(isset($_REQUEST['day']) && $_REQUEST['day']!='') + $smarty->assign("day",vtlib_purify($_REQUEST['day'])); +if(isset($_REQUEST['month']) && $_REQUEST['month']!='') + $smarty->assign("month",vtlib_purify($_REQUEST['month'])); +if(isset($_REQUEST['year']) && $_REQUEST['year']!='') + $smarty->assign("year",vtlib_purify($_REQUEST['year'])); +if(isset($_REQUEST['viewOption']) && $_REQUEST['viewOption']!='') + $smarty->assign("viewOption",vtlib_purify($_REQUEST['viewOption'])); +if(isset($_REQUEST['subtab']) && $_REQUEST['subtab']!='') + $smarty->assign("subtab",vtlib_purify($_REQUEST['subtab'])); +if(isset($_REQUEST['maintab']) && $_REQUEST['maintab']!='') + $smarty->assign("maintab",vtlib_purify($_REQUEST['maintab'])); + + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); + + $tabid = getTabid($tab_type); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data = split_validationdataArray($validationData); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +if ($activity_mode == 'Task') { + $custom_fields_data = getCalendarCustomFields(getTabid('Calendar'),'edit',$focus->column_fields); +} else { + $custom_fields_data = getCalendarCustomFields(getTabid('Events'),'edit',$focus->column_fields); +} +$smarty->assign("CUSTOM_FIELDS_DATA", $custom_fields_data); + +$smarty->assign("REPEAT_LIMIT_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +$smarty->display("ActivityEditView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/ListView.php b/oss/vtiger/trunk/modules/Calendar/ListView.php new file mode 100644 index 00000000..2ac99415 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/ListView.php @@ -0,0 +1,276 @@ +initSortbyField('Calendar'); +// END +$smarty = new vtigerCRM_Smarty; +$other_text = Array(); + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR",$mod_strings["SHARED_EVENT_DEL_MSG"]); +}else +{ + $smarty->assign("ERROR",""); +} +//<<<<<<< sort ordering >>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['ACTIVITIES_ORDER_BY'] = $order_by; +$_SESSION['ACTIVITIES_SORT_ORDER'] = $sorder; +//<<<<<<< sort ordering >>>>>>>>>>>>> + + +//<<<>>>>>> +$oCustomView = new CustomView($currentModule); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//<<<<>>>> +if($viewid == 0 ) +{ + echo "
"; + echo "
+ + + + + + + + + +
'> + $app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} + +$changeOwner = getAssignedTo(16); +$userList = $changeOwner[0]; +$groupList = $changeOwner[1]; + +$smarty->assign("CHANGE_USER",$userList); +$smarty->assign("CHANGE_GROUP",$groupList); +$smarty->assign("CHANGE_OWNER",getUserslist()); +$smarty->assign("CHANGE_GROUP_OWNER",getGroupslist()); +$where = ""; + +$url_string = ''; // assigning http url string + +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); +} + + +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +if(isPermitted("Calendar","Delete",$_REQUEST['record']) == 'yes') +{ + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +} +if(isPermitted('Calendar','EditView','') == 'yes') +{ + $other_text['c_owner'] = $app_strings[LBL_CHANGE_OWNER]; +} +global $task_title; +$title_display = $current_module_strings['LBL_LIST_FORM_TITLE']; +if ($task_title) $title_display= $task_title; + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Calendar"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Calendar"); +}else +{ + $list_query = getListQuery("Calendar"); +} +//<<<<<<<>>>>>>>> + +if(isset($where) && $where != '') +{ + if(isset($_REQUEST['from_homepagedb']) && $_REQUEST['from_homepagedb'] == 'true') + $list_query .= " and ((vtiger_activity.status!='Completed' and vtiger_activity.status!='Deferred') or vtiger_activity.status is null) and ((vtiger_activity.eventstatus!='Held' and vtiger_activity.eventstatus!='Not Held') or vtiger_activity.eventstatus is null) AND ".$where; + else + $list_query .= " AND " .$where; +} +if (isset($_REQUEST['from_homepage'])) { + $today = date("Y-m-d", time()); + if ($_REQUEST['from_homepage'] == 'upcoming_activities') + $list_query .= " AND (vtiger_activity.status is NULL OR vtiger_activity.status not in ('Completed','Deferred')) and (vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus not in ('Held','Not Held')) AND (date_start >= '$today' OR vtiger_recurringevents.recurringdate >= '$today')"; + elseif ($_REQUEST['from_homepage'] == 'pending_activities') + $list_query .= " AND (vtiger_activity.status is NULL OR vtiger_activity.status not in ('Completed','Deferred')) and (vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus not in ('Held','Not Held')) AND (due_date <= '$today' OR vtiger_recurringevents.recurringdate <= '$today')"; +} + +if(isset($order_by) && $order_by != '') { + if($order_by == 'smownerid') { + $list_query .= ' ORDER BY user_name '.$sorder; + } else { + $tablename = getTableNameForField('Calendar',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if($order_by == 'lastname') + $list_query .= ' ORDER BY vtiger_contactdetails.lastname '.$sorder; + else + $list_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } +} + +//Constructing the list view +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Activity'); +$smarty->assign("BUTTONS",$other_text); +$smarty->assign("NEW_EVENT",$app_strings['LNK_NEW_EVENT']); +$smarty->assign("NEW_TASK",$app_strings['LNK_NEW_TASK']); + +//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); + +//Retreive the List View Table Header +if($viewid !='') +$url_string .="&viewname=".$viewid; + +//Cambiado code to add close button in custom vtiger_field +if (($viewid!=0)&&($viewid!="")){ + if (!isset($oCustomView->list_fields['Close'])) $oCustomView->list_fields['Close']=array ( 'vtiger_activity' => 'eventstatus' ); + if (!isset($oCustomView->list_fields_name['Close'])) $oCustomView->list_fields_name['Close']='eventstatus'; +} +$listview_header = getListViewHeader($focus,"Calendar",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search=getSearchListHeaderValues($focus,"Calendar",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER", $listview_header_search); + +$listview_entries = getListViewEntries($focus,"Calendar",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array,$url_string,"Calendar","ListView",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'ListView','subject','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ActivityListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/ListViewPagging.php b/oss/vtiger/trunk/modules/Calendar/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/OpenListView.php b/oss/vtiger/trunk/modules/Calendar/OpenListView.php new file mode 100644 index 00000000..4910f09d --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/OpenListView.php @@ -0,0 +1,201 @@ +debug("Entering getPendingActivities() method ..."); + require_once('data/Tracker.php'); + require_once('include/utils/utils.php'); + require_once('user_privileges/default_module_view.php'); + + global $currentModule; + global $singlepane_view; + global $theme; + global $focus; + global $action; + global $adb; + global $app_strings; + global $current_language; + global $current_user; + $current_module_strings = return_module_language($current_language, 'Calendar'); + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + if($_REQUEST['activity_view']==''){ + $activity_view='today'; + }else{ + $activity_view=vtlib_purify($_REQUEST['activity_view']); + } + + $today = date("Y-m-d", time()); + if($view == 'today'){ + $upcoming_condition = " AND (date_start = '$today' OR vtiger_recurringevents.recurringdate = '$today')"; + $pending_condition = " AND (due_date = '$today' OR vtiger_recurringevents.recurringdate = '$today')"; + }else if($view == 'all'){ + $upcoming_condition = " AND (date_start >= '$today' OR vtiger_recurringevents.recurringdate >= '$today')"; + $pending_condition = " AND (due_date <= '$today' OR vtiger_recurringevents.recurringdate <= '$today')"; + } + + if($mode != 1){ + $list_query = " select vtiger_crmentity.crmid,vtiger_crmentity.smownerid,vtiger_crmentity.setype, vtiger_recurringevents.recurringdate, + vtiger_activity.activityid, vtiger_activity.activitytype, vtiger_activity.date_start, vtiger_activity.due_date, + from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid left outer join vtiger_recurringevents on vtiger_recurringevents.activityid=vtiger_activity.activityid WHERE vtiger_crmentity.deleted=0 and vtiger_activity.activitytype not in ('Emails') AND ( vtiger_activity.status is NULL OR vtiger_activity.status not in ('Completed','Deferred')) and ( vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus not in ('Held','Not Held') )".$upcoming_condition; + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3){ + $sec_parameter=getListViewSecurityParameter('Calendar'); + $list_query .= $sec_parameter; + } + }else{ + $list_query = "select vtiger_crmentity.crmid,vtiger_crmentity.smownerid,vtiger_crmentity.setype, vtiger_recurringevents.recurringdate, + vtiger_activity.activityid, vtiger_activity.activitytype, vtiger_activity.date_start, vtiger_activity.due_date, + from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid left outer join vtiger_recurringevents on vtiger_recurringevents.activityid=vtiger_activity.activityid WHERE vtiger_crmentity.deleted=0 and (vtiger_activity.activitytype not in ('Emails')) AND (vtiger_activity.status is NULL OR vtiger_activity.status not in ('Completed','Deferred')) and (vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus not in ('Held','Not Held')) ".$pending_condition; + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3){ + $sec_parameter=getListViewSecurityParameter('Calendar'); + $list_query .= $sec_parameter; + } + + $list_query.= " GROUP BY vtiger_activity.activityid"; + $list_query.= " ORDER BY date_start,time_start ASC"; + $res = $adb->query($list_query); + $noofrecords = $adb->num_rows($res); + $open_activity_list = array(); + $noofrows = $adb->num_rows($res); + if (count($res)>0){ + for($i=0;$i<$noofrows;$i++){ + $open_activity_list[] = Array('name' => $adb->query_result($res,$i,'subject'), + 'id' => $adb->query_result($res,$i,'activityid'), + 'type' => $adb->query_result($res,$i,'activitytype'), + 'module' => $adb->query_result($res,$i,'setype'), + 'date_start' => getDisplayDate($adb->query_result($res,$i,'date_start')), + 'due_date' => getDisplayDate($adb->query_result($res,$i,'due_date')), + 'recurringdate' => getDisplayDate($adb->query_result($res,$i,'recurringdate')), + 'priority' => $adb->query_result($res,$i,'priority'), // Armando L�scher 04.07.2005 -> �priority -> Desc: Get vtiger_priority from db + ); + } + } + + $title=array(); + $title[]=$view; + $title[]='myUpcoPendAct.gif'; + $title[]='home_myact'; + $title[]='showActivityView'; + $title[]='MyUpcumingFrm'; + $title[]='activity_view'; + + $header=array(); + $header[] =$current_module_strings['LBL_LIST_SUBJECT']; + $header[] ='Type'; + + $return_url="&return_module=$currentModule&return_action=DetailView&return_id=" . ((is_object($focus)) ? $focus->id : ""); + $oddRow = true; + $entries=array(); + + foreach($open_activity_list as $event){ + $recur_date=ereg_replace('--','',$event['recurringdate']); + if($recur_date!=""){ + $event['date_start']=$event['recurringdate']; + } + $font_color_high = "color:#00DD00;"; + $font_color_medium = "color:#DD00DD;"; + + switch ($event['priority']){ + case 'High': + $font_color=$font_color_high; + break; + case 'Medium': + $font_color=$font_color_medium; + break; + default: + $font_color=''; + } + + if($event['type'] != 'Task' && $event['type'] != 'Emails' && $event['type'] != ''){ + $activity_type = 'Events'; + }else{ + $activity_type = 'Task'; + } + } + $entries[$event['id']] = array( + '0' => ''.$event["name"].'', + 'IMAGE' => '', + ); + } + $values=Array('noofactivities'=>$noofrecords,'Title'=>$title,'Header'=>$header,'Entries'=>$entries); + $log->debug("Exiting getPendingActivities method ..."); + return $values; +} + +/** + * Function creates HTML to display ActivityView selection box + * @param string $activity_view - activity view + * return string $ACTIVITY_VIEW_SELECT_OPTION - HTML selection box + */ +function getActivityview($activity_view) +{ + global $log; + $log->debug("Entering getActivityview(".$activity_view.") method ..."); + $today = date("Y-m-d", time()); + + if($activity_view == 'Today') + { + $selected1 = 'selected'; + } + else if($activity_view == 'This Week') + { + $selected2 = 'selected'; + } + else if($activity_view == 'This Month') + { + $selected3 = 'selected'; + } + else if($activity_view == 'This Year') + { + $selected4 = 'selected'; + } + + //constructing the combo values for activities + $ACTIVITY_VIEW_SELECT_OPTION = ''; + + $log->debug("Exiting getActivityview method ..."); + return $ACTIVITY_VIEW_SELECT_OPTION; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/QuickCreate.php b/oss/vtiger/trunk/modules/Calendar/QuickCreate.php new file mode 100644 index 00000000..fbe0170b --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/QuickCreate.php @@ -0,0 +1,19 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/RenderRelatedListUI.php b/oss/vtiger/trunk/modules/Calendar/RenderRelatedListUI.php new file mode 100644 index 00000000..7d2d0ccc --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/RenderRelatedListUI.php @@ -0,0 +1,164 @@ +debug("Entering get_duration(".$time_start.",".$duration_hours.",".$duration_minutes.") method ..."); + $time=explode(":",$time_start); + $time_mins = $time[1]; + $time_hrs = $time[0]; + $mins = ($time_mins + $duration_minutes) % 60; + $hrs_min = floor(($time_mins + $duration_minutes) / 60); + if(!isset($hrs)) + $hrs=0; + $hrs = $duration_hours + $hrs_min + $time_hrs; + if($hrs<10) + $hrs=$hrs; + if($mins<10) + $mins="0".$mins; + + $end_time = $hrs .$mins; + $log->debug("Exiting get_duration method ..."); + return $end_time; + } + + /** + * Function to convert time to number + * @param string $time_start - activity start time + * return integer $start_time - time + */ + function time_to_number($time_start) + { + global $log; + $log->debug("Entering time_to_number(".$time_start.") method ..."); + $start_time_array = explode(":",$time_start); + if(ereg("^[0]",$start_time_array[0])) + { + $time_start_hrs=str_replace('0',"",$start_time_array[0]); + } + else + { + $time_start_hrs=$start_time_array[0]; + } + $start_time= $time_start_hrs .$start_time_array[1]; + $log->debug("Exiting time_to_number method ..."); + return $start_time; + } + + /** + * Function to status availability of user + * @param string $owner - ownername + * @param integer $userid - userid + * @param integer $activity_id - activityid + * @param string $avail_date - date in string format + * @param string $activity_start_time - time string + * @param string $activity_end_time - time string + * return string $availability - html img tag in string + */ + function status_availability($owner,$userid,$activity_id,$avail_date,$activity_start_time,$activity_end_time) + { + global $adb,$image_path,$log,$theme; + $log->debug("Entering status_availability(".$owner,$userid.",".$activity_id.",".$avail_date.",".$activity_start_time.",".$activity_end_time.") method ..."); + $avail_flag="false"; + $avail_date=getDBInsertDateValue($avail_date); + if( $owner != $userid) + { + + $usr_query="select activityid,vtiger_activity.date_start,vtiger_activity.due_date, vtiger_activity.time_start,vtiger_activity.duration_hours,vtiger_activity.duration_minutes,vtiger_crmentity.smownerid from vtiger_activity,vtiger_crmentity where vtiger_crmentity.crmid=vtiger_activity.activityid and ('".$avail_date."' like date_start) and vtiger_crmentity.smownerid=? and vtiger_activity.activityid !=? and vtiger_crmentity.deleted=0"; + } + else + { + $usr_query="select activityid,vtiger_activity.date_start,vtiger_activity.due_date, vtiger_activity.time_start,vtiger_activity.duration_hours,vtiger_activity.duration_minutes,vtiger_crmentity.smownerid from vtiger_activity,vtiger_crmentity where vtiger_crmentity.crmid=vtiger_activity.activityid and ('".$avail_date."' like date_start) and vtiger_crmentity.smownerid=? and vtiger_activity.activityid !=? and vtiger_crmentity.deleted=0"; + } + $result_cal=$adb->pquery($usr_query, array($userid, $activity_id)); + $noofrows_cal = $adb->num_rows($result_cal); + $avail_flag="false"; + + if($noofrows_cal!=0) + { + while($row_cal = $adb->fetch_array($result_cal)) + { + $usr_date_start=$row_cal['date_start']; + $usr_due_date=$row_cal['due_date']; + $usr_time_start=$row_cal['time_start']; + $usr_hour_dur=$row_cal['duration_hours']; + $usr_mins_dur=$row_cal['duration_minutes']; + $user_start_time=time_to_number($usr_time_start); + $user_end_time=get_duration($usr_time_start,$usr_hour_dur,$usr_mins_dur); + + if( ( ($user_start_time > $activity_start_time) && ( $user_start_time < $activity_end_time) ) || ( ( $user_end_time > $activity_start_time) && ( $user_end_time < $activity_end_time) ) || ( ( $activity_start_time == $user_start_time ) || ($activity_end_time == $user_end_time) ) ) + { + $availability= 'busy'; + $avail_flag="true"; + $log->info("user start time-- ".$user_start_time."user end time".$user_end_time); + $log->info("Availability ".$availability); + + } + } + } + if($avail_flag!="true") + { + $recur_query="SELECT vtiger_activity.activityid, vtiger_activity.time_start, vtiger_activity.duration_hours, vtiger_activity.duration_minutes , vtiger_crmentity.smownerid, vtiger_recurringevents.recurringid, vtiger_recurringevents.recurringdate as date_start from vtiger_activity inner join vtiger_crmentity on vtiger_activity.activityid = vtiger_crmentity.crmid inner join vtiger_recurringevents on vtiger_activity.activityid=vtiger_recurringevents.activityid where ('".$avail_date."' like vtiger_recurringevents.recurringdate) and vtiger_crmentity.smownerid=? and vtiger_activity.activityid !=? and vtiger_crmentity.deleted=0"; + $result_cal=$adb->pquery($recur_query, array($userid, $activity_id)); + $noofrows_cal = $adb->num_rows($result_cal); + $avail_flag="false"; + + if($noofrows_cal!=0) + { + while($row_cal = $adb->fetch_array($result_cal)) + { + $usr_date_start=$row_cal['date_start']; + $usr_time_start=$row_cal['time_start']; + $usr_hour_dur=$row_cal['duration_hours']; + $usr_mins_dur=$row_cal['duration_minutes']; + $user_start_time=time_to_number($usr_time_start); + $user_end_time=get_duration($usr_time_start,$usr_hour_dur,$usr_mins_dur); + + if( ( ($user_start_time > $activity_start_time) && ( $user_start_time < $activity_end_time) ) || ( ( $user_end_time > $activity_start_time) && ( $user_end_time < $activity_end_time) ) || ( ( $activity_start_time == $user_start_time ) || ($activity_end_time == $user_end_time) ) ) + { + $availability= 'busy'; + $avail_flag="true"; + $log->info("Recurring Events:: user start time-- ".$user_start_time."user end time".$user_end_time); + $log->info("Recurring Events:: Availability ".$availability); + } + } + } + + + } + if($avail_flag == "true") + { + $availability=' '; + } + else + { + $availability=' '; + } + $log->debug("Exiting status_availability method ..."); + return $availability; + + } + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/RepeatEvents.php b/oss/vtiger/trunk/modules/Calendar/RepeatEvents.php new file mode 100644 index 00000000..d41b1587 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/RepeatEvents.php @@ -0,0 +1,182 @@ +date_format) { + case 'dd-mm-yyyy': $format_string = 'd-m-Y H:i'; break; + case 'mm-dd-yyyy': $format_string = 'm-d-Y H:i'; break; + case 'yyyy-mm-dd': $format_string = 'Y-m-d H:i'; break; + } + return date($format_string, self::mktime($timeInYMDHIS)); + } + /** + * Split full timing into date and time part. + */ + static function splittime($fulltiming) { + return split(' ', $fulltiming); + } + /** + * Calculate the time interval to create repeated event entries. + */ + static function getRepeatInterval($type, $frequency, $recurringInfo, $start_date, $limit_date) { + $repeatInterval = Array(); + $starting = self::mktime($start_date); + $limiting = self::mktime($limit_date); + + if($type == 'Daily') { + $count = 0; + while(true) { + ++$count; + $interval = ($count * $frequency); + if(self::mktime(self::nexttime($starting, "+$interval days")) > $limiting) { + break; + } + $repeatInterval[] = $interval; + } + } else if($type == 'Weekly') { + if($recurringInfo->dayofweek_to_rpt == null) { + $count = 0; + $weekcount = 7; + while(true) { + ++$count; + $interval = $count * $weekcount; + if(self::mktime(self::nexttime($starting, "+$interval days")) > $limiting) { + break; + } + $repeatInterval[] = $interval; + } + } else { + $count = 0; + while(true) { + ++$count; + $interval = $count; + $new_timing = self::mktime(self::nexttime($starting, "+$interval days")); + $new_timing_dayofweek = date('N', $new_timing); + if($new_timing > $limiting) { + break; + } + if(in_array($new_timing_dayofweek-1, $recurringInfo->dayofweek_to_rpt)) { + $repeatInterval[] = $interval; + } + } + } + } else if($type == 'Monthly') { + $count = 0; + $avg_monthcount = 30; // TODO: We need to handle month increments precisely! + while(true) { + ++$count; + $interval = $count * $avg_monthcount; + if(self::mktime(self::nexttime($starting, "+$interval days")) > $limiting) { + break; + } + $repeatInterval[] = $interval; + } + } else if($type == 'Yearly') { + $count = 0; + $avg_monthcount = 30; + while(true) { + ++$count; + $interval = $count * $avg_monthcount; + if(self::mktime(self::nexttime($starting, "+$interval days")) > $limiting) { + break; + } + $repeatInterval[] = $interval; + } + } + return $repeatInterval; + } + + /** + * Repeat Activity instance till given limit. + */ + static function repeat($focus) { + + global $log; + $repeat = getrecurringObjValue(); + $frequency = $repeat->recur_freq; + $repeattype= $repeat->recur_type; + + $base_focus = new Activity(); + $base_focus->retrieve_entity_info($focus->id,'Events'); + $base_focus->id = $_REQUEST['record']; + + $base_focus_start = $base_focus->column_fields['date_start'].' '.$base_focus->column_fields['time_start']; + $base_focus_end = $base_focus->column_fields['due_date'].' '.$base_focus->column_fields['time_end']; + + $repeat_limit = getDBInsertDateValue($_REQUEST['calendar_repeat_limit_date']).' '.$base_focus->column_fields['time_start']; + + $repeatIntervals = self::getRepeatInterval($repeattype, $frequency, $repeat, $base_focus_start, $repeat_limit); + + $base_focus_start = self::mktime($base_focus_start); + $base_focus_end = self::mktime($base_focus_end); + + $skip_focus_fields = Array ('record_id', 'createdtime', 'modifiedtime', 'recurringtype'); + + /** Create instance before and reuse */ + $new_focus = new Activity(); + + foreach($repeatIntervals as $interval) { + $new_focus_start_timing = self::nexttime($base_focus_start, "+$interval days"); + $new_focus_start_timing = self::splittime(self::formattime($new_focus_start_timing)); + + $new_focus_end_timing = self::nexttime($base_focus_end, "+$interval days"); + $new_focus_end_timing = self::splittime(self::formattime($new_focus_end_timing)); + + // Reset the new_focus and prepare for reuse + if(isset($new_focus->id)) unset($new_focus->id); + foreach($new_focus->column_fields as $key=>$value) $new_focus->column_fields[$key] = ''; + + foreach($base_focus->column_fields as $key=>$value) { + if(in_array($key, $skip_focus_fields)) { + // skip copying few fields + } else if($key == 'date_start') { + $new_focus->column_fields['date_start'] = $new_focus_start_timing[0]; + } else if($key == 'time_start') { + $new_focus->column_fields['time_start'] = $new_focus_start_timing[1]; + } else if($key == 'time_end') { + $new_focus->column_fields['time_end'] = $new_focus_end_timing[1]; + } else if($key == 'due_date') { + $new_focus->column_fields['due_date'] = $new_focus_end_timing[0]; + } else { + $new_focus->column_fields[$key] = $value; + } + } + $new_focus->save('Calendar'); + } + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/Save.php b/oss/vtiger/trunk/modules/Calendar/Save.php new file mode 100644 index 00000000..d9e73830 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Save.php @@ -0,0 +1,306 @@ +column_fields["activitytype"] = 'Task'; +if(isset($_REQUEST['record'])) +{ + $focus->id = $_REQUEST['record']; + $local_log->debug("id is ".$id); +} +if(isset($_REQUEST['mode'])) +{ + $focus->mode = $_REQUEST['mode']; +} + +if((isset($_REQUEST['change_status']) && $_REQUEST['change_status']) && ($_REQUEST['status']!='' || $_REQUEST['eventstatus']!='')) +{ + $status =''; + $activity_type=''; + $return_id = $focus->id; + if(isset($_REQUEST['status'])) + { + $status = $_REQUEST['status']; + $activity_type = "Task"; + } + elseif(isset($_REQUEST['eventstatus'])) + { + $status = $_REQUEST['eventstatus']; + $activity_type = "Events"; + } + if(isPermitted("Calendar","EditView",$_REQUEST['record']) == 'yes') + { + ChangeStatus($status,$return_id,$activity_type); + } + else + { + echo ""; + echo "
"; + echo "
+ + + + + + + + + +
' >$app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
"; + echo "
";die; + } + $mail_data = getActivityMailInfo($return_id,$status,$activity_type); + if($mail_data['sendnotification'] == 1) + { + getEventNotification($activity_type,$mail_data['subject'],$mail_data); + } + $invitee_qry = "select * from vtiger_invitees where activityid=?"; + $invitee_res = $adb->pquery($invitee_qry, array($return_id)); + $count = $adb->num_rows($invitee_res); + if($count != 0) + { + for($j = 0; $j < $count; $j++) + { + $invitees_ids[]= $adb->query_result($invitee_res,$j,"inviteeid"); + + } + $invitees_ids_string = implode(';',$invitees_ids); + sendInvitation($invitees_ids_string,$activity_type,$mail_data['subject'],$mail_data); + } + + +} +else +{ + foreach($focus->column_fields as $fieldname => $val) + { + if(isset($_REQUEST[$fieldname])) + { + if(is_array($_REQUEST[$fieldname])) + $value = $_REQUEST[$fieldname]; + else + $value = trim($_REQUEST[$fieldname]); + $focus->column_fields[$fieldname] = $value; + if(($fieldname == 'notime') && ($focus->column_fields[$fieldname])) + { + $focus->column_fields['time_start'] = ''; + $focus->column_fields['duration_hours'] = ''; + $focus->column_fields['duration_minutes'] = ''; + } + if(($fieldname == 'recurringtype') && ! isset($_REQUEST['recurringcheck'])) + $focus->column_fields['recurringtype'] = '--None--'; + } + } + if(isset($_REQUEST['visibility']) && $_REQUEST['visibility']!= '') + $focus->column_fields['visibility'] = $_REQUEST['visibility']; + else + $focus->column_fields['visibility'] = 'Private'; + + 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($tab_type); + /* For Followup START -- by Minnie */ + if(isset($_REQUEST['followup']) && $_REQUEST['followup'] == 'on' && $activity_mode == 'Events' && isset($_REQUEST['followup_time_start']) && $_REQUEST['followup_time_start'] != '') + { + $heldevent_id = $focus->id; + $focus->column_fields['subject'] = '[Followup] '.$focus->column_fields['subject']; + $focus->column_fields['date_start'] = $_REQUEST['followup_date']; + $focus->column_fields['due_date'] = $_REQUEST['followup_due_date']; + $focus->column_fields['time_start'] = $_REQUEST['followup_time_start']; + $focus->column_fields['time_end'] = $_REQUEST['followup_time_end']; + $focus->column_fields['eventstatus'] = 'Planned'; + $focus->mode = 'create'; + $focus->save($tab_type); + } + /* For Followup END -- by Minnie */ + $return_id = $focus->id; +} + +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") + $return_module = vtlib_purify($_REQUEST['return_module']); +else + $return_module = "Calendar"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") + $return_action = vtlib_purify($_REQUEST['return_action']); +else + $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") + $return_id = vtlib_purify($_REQUEST['return_id']); + +$activemode = ""; +if($activity_mode != '') + $activemode = "&activity_mode=".$activity_mode; + +function getRequestData($return_id) +{ + global $adb; + $cont_qry = "select * from vtiger_cntactivityrel where activityid=?"; + $cont_res = $adb->pquery($cont_qry, array($return_id)); + $noofrows = $adb->num_rows($cont_res); + $cont_id = array(); + if($noofrows > 0) { + for($i=0; $i<$noofrows; $i++) { + $cont_id[] = $adb->query_result($cont_res,$i,"contactid"); + } + } + $cont_name = ''; + foreach($cont_id as $key=>$id) { + if($id != '') { + $cont_name .= getContactName($id).', '; + } + } + $cont_name = trim($cont_name,', '); + $mail_data = Array(); + $mail_data['user_id'] = $_REQUEST['assigned_user_id']; + $mail_data['subject'] = $_REQUEST['subject']; + $mail_data['status'] = (($_REQUEST['activity_mode']=='Task')?($_REQUEST['taskstatus']):($_REQUEST['eventstatus'])); + $mail_data['activity_mode'] = $_REQUEST['activity_mode']; + $mail_data['taskpriority'] = $_REQUEST['taskpriority']; + $mail_data['relatedto'] = $_REQUEST['parent_name']; + $mail_data['contact_name'] = $cont_name; + $mail_data['description'] = $_REQUEST['description']; + $mail_data['assingn_type'] = $_REQUEST['assigntype']; + $mail_data['group_name'] = getGroupName($_REQUEST['assigned_group_id']); + $mail_data['mode'] = $_REQUEST['mode']; + $value = getaddEventPopupTime($_REQUEST['time_start'],$_REQUEST['time_end'],'24'); + $start_hour = $value['starthour'].':'.$value['startmin'].''.$value['startfmt']; + if($_REQUEST['activity_mode']!='Task') + $end_hour = $value['endhour'] .':'.$value['endmin'].''.$value['endfmt']; + $mail_data['st_date_time'] = getDisplayDate($_REQUEST['date_start'])." ".$start_hour; + $mail_data['end_date_time']=getDisplayDate($_REQUEST['due_date'])." ".$end_hour; + $mail_data['location']=vtlib_purify($_REQUEST['location']); + return $mail_data; +} + +if(isset($_REQUEST['contactidlist']) && $_REQUEST['contactidlist'] != '') +{ + //split the string and store in an array + $storearray = explode (";",$_REQUEST['contactidlist']); + $del_sql = "delete from vtiger_cntactivityrel where activityid=?"; + $adb->pquery($del_sql, array($record)); + foreach($storearray as $id) + { + if($id != '') + { + $record = $focus->id; + $sql = "insert into vtiger_cntactivityrel values (?,?)"; + $adb->pquery($sql, array($id, $record)); + if(!empty($heldevent_id)) { + $sql = "insert into vtiger_cntactivityrel values (?,?)"; + $adb->pquery($sql, array($id, $heldevent_id)); + } + } + } +} + +//Added code to send mail to the assigned to user about the details of the vtiger_activity if sendnotification = on and assigned to user +if($_REQUEST['sendnotification'] == 'on') +{ + $mail_contents = getRequestData($return_id); + getEventNotification($_REQUEST['activity_mode'],$_REQUEST['subject'],$mail_contents); +} + +//code added to send mail to the vtiger_invitees +if(isset($_REQUEST['inviteesid']) && $_REQUEST['inviteesid']!='') +{ + $mail_contents = getRequestData($return_id); + sendInvitation($_REQUEST['inviteesid'],$_REQUEST['activity_mode'],$_REQUEST['subject'],$mail_contents); +} + +//to delete contact account relation while editing event +if(isset($_REQUEST['deletecntlist']) && $_REQUEST['deletecntlist'] != '' && $_REQUEST['mode'] == 'edit') +{ + //split the string and store it in an array + $storearray = explode (";",$_REQUEST['deletecntlist']); + foreach($storearray as $id) + { + if($id != '') + { + $record = $focus->id; + $sql = "delete from vtiger_cntactivityrel where contactid=? and activityid=?"; + $adb->pquery($sql, array($id, $record)); + } + } + +} + +//to delete activity and its parent table relation +if(isset($_REQUEST['del_actparent_rel']) && $_REQUEST['del_actparent_rel'] != '' && $_REQUEST['mode'] == 'edit') +{ + $parnt_id = $_REQUEST['del_actparent_rel']; + $sql= 'delete from vtiger_seactivityrel where crmid=? and activityid=?'; + $adb->pquery($sql, array($parnt_id, $record)); +} + +if(isset($_REQUEST['view']) && $_REQUEST['view']!='') + $view=vtlib_purify($_REQUEST['view']); +if(isset($_REQUEST['hour']) && $_REQUEST['hour']!='') + $hour=vtlib_purify($_REQUEST['hour']); +if(isset($_REQUEST['day']) && $_REQUEST['day']!='') + $day=vtlib_purify($_REQUEST['day']); +if(isset($_REQUEST['month']) && $_REQUEST['month']!='') + $month=vtlib_purify($_REQUEST['month']); +if(isset($_REQUEST['year']) && $_REQUEST['year']!='') + $year=vtlib_purify($_REQUEST['year']); +if(isset($_REQUEST['viewOption']) && $_REQUEST['viewOption']!='') + $viewOption=vtlib_purify($_REQUEST['viewOption']); +if(isset($_REQUEST['subtab']) && $_REQUEST['subtab']!='') + $subtab=vtlib_purify($_REQUEST['subtab']); + +if($_REQUEST['recurringcheck']) { + include_once dirname(__FILE__) . '/RepeatEvents.php'; + Calendar_RepeatEvents::repeat($focus); +} + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') + $return_viewname='0'; +if($_REQUEST['return_viewname'] != '') + $return_viewname=vtlib_purify($_REQUEST['return_viewname']); + +$parenttab=getParentTab(); + +if($_REQUEST['start'] !='') + $page='&start='.vtlib_purify($_REQUEST['start']); +if($_REQUEST['maintab'] == 'Calendar') + header("Location: index.php?action=".$return_action."&module=".$return_module."&view=".$view."&hour=".$hour."&day=".$day."&month=".$month."&year=".$year."&record=".$return_id."&viewOption=".$viewOption."&subtab=".$subtab."&parenttab=$parenttab"); +else + header("Location: index.php?action=$return_action&module=$return_module$view$hour$day$month$year&record=$return_id$activemode&viewname=$return_viewname$page&parenttab=$parenttab&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/SendReminder.bat b/oss/vtiger/trunk/modules/Calendar/SendReminder.bat new file mode 100644 index 00000000..e148ff49 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/SendReminder.bat @@ -0,0 +1,3 @@ +@echo off +cd ..\..\ +..\..\..\php\php.exe SendReminder.php diff --git a/oss/vtiger/trunk/modules/Calendar/Settings.php b/oss/vtiger/trunk/modules/Calendar/Settings.php new file mode 100644 index 00000000..eaf1e900 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/Settings.php @@ -0,0 +1,42 @@ +0) { + for($i=0;$i<3-$count;$i++) { + $menu_array[] = array(); + } +} + +$smarty->assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("IMAGE_PATH", "themes/$theme/images/"); +$smarty->assign('MODULE',$module); +$smarty->assign('MODULE_LBL',getTranslatedString($module)); +$smarty->assign('MENU_ARRAY', $menu_array); + +$smarty->display(vtlib_getModuleTemplate('Vtiger','Settings.tpl')); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/TagCloud.php b/oss/vtiger/trunk/modules/Calendar/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Calendar/TodoSave.php b/oss/vtiger/trunk/modules/Calendar/TodoSave.php new file mode 100644 index 00000000..03282363 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/TodoSave.php @@ -0,0 +1,88 @@ +column_fields["activitytype"] = 'Task'; +} + +if(isset($_REQUEST['record'])) +{ + $focus->id = $_REQUEST['record']; +} +if(isset($_REQUEST['mode'])) +{ + $focus->mode = $_REQUEST['mode']; +} +foreach($focus->column_fields as $fieldname => $val) +{ + if(isset($_REQUEST[$fieldname])) + { + if(is_array($_REQUEST[$fieldname])) + $value = $_REQUEST[$fieldname]; + else + $value = trim($_REQUEST[$fieldname]); + $focus->column_fields[$fieldname] = $value; + } +} + $focus->column_fields["subject"] = $_REQUEST["task_subject"]; + $focus->column_fields["time_start"] = $_REQUEST["task_time_start"]; + $focus->column_fields["assigned_user_id"] = $_REQUEST["task_assigned_user_id"]; + $_REQUEST["assigned_group_id"] = $_REQUEST['task_assigned_group_id']; + $_REQUEST['assigntype'] = $_REQUEST['task_assigntype']; + $focus->column_fields["taskstatus"] = $_REQUEST["taskstatus"]; + $focus->column_fields["date_start"] = $_REQUEST["task_date_start"]; + $focus->column_fields["due_date"] = $_REQUEST["task_due_date"]; + $focus->column_fields["taskpriority"] = $_REQUEST["taskpriority"]; + $focus->column_fields["parent_id"] = $_REQUEST["task_parent_id"]; + $focus->column_fields["contact_id"] = $_REQUEST["task_contact_id"]; + $focus->column_fields["description"] = $_REQUEST["task_description"]; + if(isset($_REQUEST['task_sendnotification']) && $_REQUEST['task_sendnotification'] != null) + $focus->column_fields["sendnotification"] = $_REQUEST["task_sendnotification"]; + + $focus->save($tab_type); + if($_REQUEST["task_sendnotification"]=='on') + { + $mail_contents = getRequestedToData(); + getEventNotification($_REQUEST['activity_mode'],$_REQUEST['task_subject'],$mail_contents); + + } +function getRequestedToData() +{ + $mail_data = Array(); + $mail_data['user_id'] = $_REQUEST["task_assigned_user_id"]; + $mail_data['subject'] = $_REQUEST['task_subject']; + $mail_data['status'] = (($_REQUEST['activity_mode']=='Task')?($_REQUEST['taskstatus']):($_REQUEST['eventstatus'])); + $mail_data['activity_mode'] = $_REQUEST['activity_mode']; + $mail_data['taskpriority'] = $_REQUEST['taskpriority']; + $mail_data['relatedto'] = $_REQUEST['task_parent_name']; + $mail_data['contact_name'] = $_REQUEST['task_contact_name']; + $mail_data['description'] = $_REQUEST['task_description']; + $mail_data['assingn_type'] = $_REQUEST['task_assigntype']; + $mail_data['group_name'] = getGroupName($_REQUEST['task_assigned_group_id']); + $mail_data['mode'] = $_REQUEST['task_mode']; + $value = getaddEventPopupTime($_REQUEST['task_time_start'],$_REQUEST['task_time_end'],'24'); + $start_hour = $value['starthour'].':'.$value['startmin'].''.$value['startfmt']; + $mail_data['st_date_time'] = getDisplayDate($_REQUEST['task_date_start'])." ".$start_hour; + $mail_data['end_date_time']=getDisplayDate($_REQUEST['task_due_date']); + return $mail_data; +} + + header("Location: index.php?action=index&module=Calendar&view=".vtlib_purify($_REQUEST['view'])."&hour=".vtlib_purify($_REQUEST['hour'])."&day=".vtlib_purify($_REQUEST['day'])."&month=".vtlib_purify($_REQUEST['month'])."&year=".vtlib_purify($_REQUEST['year'])."&viewOption=".vtlib_purify($_REQUEST['viewOption'])."&subtab=todo&parenttab=".getParentTab()); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/UnifiedSearch.php b/oss/vtiger/trunk/modules/Calendar/UnifiedSearch.php new file mode 100644 index 00000000..14e4cbfa --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/UnifiedSearch.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/Calendar/addEventUI.php b/oss/vtiger/trunk/modules/Calendar/addEventUI.php new file mode 100644 index 00000000..5d508bb0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/addEventUI.php @@ -0,0 +1,1106 @@ +id,true); + $to_email = getUserEmailId('id',$current_user->id); + $date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + $taskassignedto = getAssignedTo(9); + $eventassignedto = getAssignedTo(16); +$mysel= vtlib_purify($_REQUEST['view']); +$calendar_arr = Array(); +$calendar_arr['IMAGE_PATH'] = $image_path; +if(empty($mysel)){ + if($current_user->activity_view == "This Year"){ + $mysel = 'year'; + }else if($current_user->activity_view == "This Month"){ + $mysel = 'month'; + }else if($current_user->activity_view == "This Week"){ + $mysel = 'week'; + }else{ + $mysel = 'day'; + } +} +$date_data = array(); +if ( isset($_REQUEST['day'])) +{ + + $date_data['day'] = $_REQUEST['day']; +} + +if ( isset($_REQUEST['month'])) +{ + $date_data['month'] = $_REQUEST['month']; +} + +if ( isset($_REQUEST['week'])) +{ + $date_data['week'] = $_REQUEST['week']; +} + +if ( isset($_REQUEST['year'])) +{ + if ($_REQUEST['year'] > 2037 || $_REQUEST['year'] < 1970) + { + print("".$app_strings['LBL_CAL_LIMIT_MSG'].""); + exit; + } + $date_data['year'] = $_REQUEST['year']; +} + + +if(empty($date_data)) +{ + $data_value=date('Y-m-d H:i:s'); + preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$data_value,$value); + $date_data = Array( + 'day'=>$value[3], + 'month'=>$value[2], + 'year'=>$value[1], + 'hour'=>$value[4], + 'min'=>$value[5], + ); + +} +$calendar_arr['calendar'] = new Calendar($mysel,$date_data); +$calendar_arr['view'] = $mysel; +if($current_user->hour_format == '') + $calendar_arr['calendar']->hour_format = 'am/pm'; +else + $calendar_arr['calendar']->hour_format = $current_user->hour_format; + +/** Function to construct HTML code for Assigned To field + * @param $assignedto -- Assigned To values :: Type array + * @param $toggletype -- String to different event and task :: Type string + * return $htmlStr -- HTML code in string forat :: Type string + */ +function getAssignedToHTML($assignedto,$toggletype) +{ + global $app_strings; + $userlist = $assignedto[0]; + if(isset($assignedto[1]) && $assignedto[1] != null) + $grouplist = $assignedto[1]; + $htmlStr = ''; + $check = 1; + foreach($userlist as $key_one=>$arr) + { + foreach($arr as $sel_value=>$value) + { + if($value != '') + $check=$check*0; + else + $check=$check*1; + } + } + if($check == 0) + { + $select_user='checked'; + $style_user='display:block'; + $style_group='display:none'; + } + else + { + $select_group='checked'; + $style_user='display:none'; + $style_group='display:block'; + } + if($toggletype == 'task') + $htmlStr .= ' '.$app_strings['LBL_USER']; + else + $htmlStr .= ' '.$app_strings['LBL_USER']; + if($grouplist != '') + { + if($toggletype == 'task') + $htmlStr .= ' '.$app_strings['LBL_GROUP']; + else + $htmlStr .= ' '.$app_strings['LBL_GROUP']; + } + if($toggletype == 'task') + { + $htmlStr .= ' + '; + } + $htmlStr .= getUserslist(); + $htmlStr .= ' + '; + if($grouplist != '') + { + if($toggletype == 'task') + { + $htmlStr .= ' + '; + } + $htmlStr .= getGroupslist(); + $htmlStr .= ' + '; + } + return $htmlStr; +} + +?> + + + + + + + + + + + +
+ + + + +
+ + id,'eventstatus') == '0') { ?> + - + - + + + - + - + + - + +
+
+ + +
+ +column_fields['is_admin']=='on') + $Res = $adb->pquery("select * from vtiger_activitytype",array()); + else + { + $role_id=$current_user->roleid; + $subrole = getRoleSubordinates($role_id); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $role_id); + } + else + { + $roleids = $role_id; + } + + if (count($roleids) > 1) { + $Res=$adb->pquery("select distinct activitytype from vtiger_activitytype inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_activitytype.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_activitytype) order by sortid asc",array($roleids)); + } else { + $Res=$adb->pquery("select distinct activitytype from vtiger_activitytype inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_activitytype.picklist_valueid where roleid = ? and picklistid in (select picklistid from vtiger_activitytype) order by sortid asc",array($role_id)); + } + } + $eventlist=''; + for($i=0; $i<$adb->num_rows($Res);$i++) + { + $eventlist = $adb->query_result($Res,$i,'activitytype'); +?> + + + +
+
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
 
: + + + onclick=checkgroup(); checked>  + +
+ + + +
 
+    + + +
+
+
+ + +
+ + + + +
+ + id,'taskstatus') == '0') { ?> + - + - + + + + - + - + + - + + +
+
+ diff --git a/oss/vtiger/trunk/modules/Calendar/calendarLayout.php b/oss/vtiger/trunk/modules/Calendar/calendarLayout.php new file mode 100644 index 00000000..658df3d5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/calendarLayout.php @@ -0,0 +1,2196 @@ +debug("Entering calendar_layout() method"); + $cal_header = array (); + if (isset($param_arr['size']) && $param_arr['size'] == 'small') + $param_arr['calendar']->show_events = false; + + $cal_header['view'] = $param_arr['view']; + $cal_header['IMAGE_PATH'] = $param_arr['IMAGE_PATH']; + $cal_header['calendar'] = $param_arr['calendar']; + $eventlabel = $mod_strings['LBL_EVENTS']; + $todolabel = $mod_strings['LBL_TODOS']; + //if $param_arr['size'] is set to 'small', get small(mini) calendar + if(isset($param_arr['size']) && $param_arr['size'] == 'small') + { + get_mini_calendar($param_arr); + } + else + { + // User Select Customization + $onlyForUserParam = "onlyforuser=" . calendarview_getSelectedUserId(); + // END + + //To differentiate selected subtab from unselected one - Starts + if($subtab == 'event') + { + $eventtab_class = 'dvtSelectedCell'; + $todotab_class = 'dvtUnSelectedCell'; + $event_anchor = $eventlabel; + // Added for User Based CustomView for Calendar module + $todo_anchor = "date_time->get_date_str()."&viewOption=".$viewBox."&subtab=todo&parenttab=".$category."&$onlyForUserParam'>".$todolabel.""; + + } + elseif($subtab == 'todo') + { + $eventtab_class = 'dvtUnSelectedCell'; + $todotab_class = 'dvtSelectedCell'; + // Added User Based CustomView for Calendar module + $event_anchor = "date_time->get_date_str()."&viewOption=".$viewBox."&subtab=event&parenttab=".$category."&$onlyForUserParam'>".$eventlabel.""; + $todo_anchor = $todolabel; + } + //Ends + //To get calendar header and its links(like Day,Week,Month,Year and etc.) + get_cal_header_tab($cal_header,$viewBox,$subtab); + $subheader = ""; + $subheader .=<< + + + + + + +
+ + + + + + + + + +
 $event_anchor $todo_anchor 
+
+EOQ; + echo $subheader; + if($viewBox == 'hourview' && $subtab == 'event') + { + get_cal_header_data($param_arr,$viewBox,$subtab); + getHourView($param_arr); + } + elseif($viewBox == 'listview' && $subtab == 'event') + { + get_cal_header_data($param_arr,$viewBox,$subtab); + getEventListView($param_arr); + } + elseif($subtab == 'todo') + { + $todo_list = ""; + $todo_list .= getTodosListView($param_arr,'',$subtab); + $todo_list .= '

'; + echo $todo_list; + } + } + + $cal_log->debug("Exiting calendar_layout() method"); + +} + +/** + * Function creates HTML to display small(mini) Calendar + * @param array $cal - collection of objects and strings + */ +function get_mini_calendar(& $cal){ + global $current_user,$adb,$cal_log,$mod_strings,$theme; + $category = getParentTab(); + $cal_log->debug('Entering get_mini_calendar() method...'); + $count = 0; + //To decide number of rows(weeks) in a month + if ($cal['calendar']->month_array[$cal['calendar']->slices[35]]->start_time->month != $cal['calendar']->date_time->month) { + $rows = 5; + } else { + $rows = 6; + } + $minical = ""; + $minical .= " + + + "; + $minical .= ""; + $minical .= ""; + //To display days in week + $minical .= ''; + for ($i = 0; $i < 7; $i ++){ + $weekday = $mod_strings['cal_weekdays_short'][$i]; + $minical .= ''; + } + $minical .= ""; + $event_class = ''; + $class = ''; + for ($i = 0; $i < $rows; $i++){ + $minical .= ""; + + //calculate blank days for first week + for ($j = 0; $j < 7; $j ++){ + $cal['slice'] = $cal['calendar']->month_array[$cal['calendar']->slices[$count]]; + $class = dateCheck($cal['slice']->start_time->get_formatted_date()); + if($j == 0){ + $minical .= ""; + } + + //To differentiate day having events from other days + if(count($cal['slice']->activities) != 0 && ($cal['slice']->start_time->get_formatted_date() == $cal['slice']->activities[0]->start_time->get_formatted_date())){ + $event_class = 'class="eventDay"'; + }else{ + $event_class = ''; + } + //To differentiate current day from other days + if($class != '' ){ + $class = 'class="'.$class.'"'; + }else{ + $class = $event_class; + } + + //To display month dates + if ($cal['slice']->start_time->getMonth() == $cal['calendar']->date_time->getMonth()){ + $minical .= ""; + }else{ + $minical .= ""; + } + $count++; + } + $minical .= ''; + } + $minical .= "
 ".get_previous_cal($cal)." "; + $minical .= "date_time->get_date_str()."&parenttab=".$category."'>".display_date($cal['view'],$cal['calendar']->date_time)." ".get_next_cal($cal)." +
'.$mod_strings['LBL_WEEK'].''.$weekday.'
start_time->get_date_str()."&parenttab=".$category."'>".$cal['slice']->start_time->week.""; + $minical .= "getView()."".$cal['slice']->start_time->get_date_str()."&parenttab=".$category."'>"; + $minical .= $cal['slice']->start_time->get_Date()."
"; + echo $minical; + $cal_log->debug("Exiting get_mini_calendar() method..."); +} + +/** + * Function creates HTML to display Calendar Header and its Links + * @param array $header - collection of objects and strings + * @param string $viewBox - string 'listview' or 'hourview' or may be empty. if 'listview' means Events ListView.if 'hourview' means Events HourView. if empty means get Todos ListView + * @param string $subtab - string 'todo' or 'event'. if 'todo' means Todos View else Events View + */ +function get_cal_header_tab(& $header,$viewBox,$subtab) +{ + global $mod_strings,$cal_log; + $category = getParentTab(); + $cal_log->debug("Entering get_cal_header_tab() method..."); + $tabhtml = ""; + $count = 1; + include_once 'modules/Calendar/addEventUI.php'; + include_once 'modules/Calendar/header.php'; + $eventlabel = $mod_strings['LBL_EVENTS']; + $todolabel = $mod_strings['LBL_TODOS']; + $div = " + +
+ "; + echo $div; + $tabhtml .= ""; + $links = array ('day','week','month','year'); + //To differentiate the selected link from unselected links + foreach ($links as $link) + { + if ($header['view'] == $link) + { + $class = 'calSel'; + $anchor = $mod_strings["LBL_".$header['calendar']->getCalendarView($link)]; + } + else + { + $class = 'calUnSel'; + $anchor = "date_time->get_date_str()."&viewOption=".$viewBox."&subtab=".$subtab."&parenttab=".$category."'>".$mod_strings["LBL_".$header['calendar']->getCalendarView($link)].""; + } + + if($count == 1) + $tabhtml .= ""; + else + $tabhtml .= ""; + $count++; + } + //To get Navigation(next&previous) links and display Date info + $tabhtml .= ""; + $tabhtml .= ""; + $tabhtml .= ""; + $tabhtml .= ""; + $tabhtml .= ""; + echo $tabhtml; + $cal_log->debug("Exiting get_cal_header_tab() method..."); +} + +/** + * Function creates HTML to display number of Events, Todos and pending list in calendar under header(Eg:Total Events : 5, 2 Pending / Total To Dos: 4, 1 Pending) + * @param array $cal_arr - collection of objects and strings + * @param string $viewBox - string 'listview' or 'hourview'. if 'listview' means Events ListView.if 'hourview' means Events HourView. + */ +function get_cal_header_data(& $cal_arr,$viewBox,$subtab) +{ + global $mod_strings,$cal_log,$current_user,$adb,$theme; + $cal_log->debug("Entering get_cal_header_data() method..."); + global $current_user,$app_strings; + $date_format = $current_user->date_format; + $format = $cal_arr['calendar']->hour_format; + $hour_startat = timeString(array('hour'=>date('H:i',(time()+(5*60))),'minute'=>0),'24'); + $hour_endat = timeString(array('hour'=>date('H:i',(time() + (60 * 60))),'minute'=>0),'24'); + $time_arr = getaddEventPopupTime($hour_startat,$hour_endat,$format); + $temp_ts = $cal_arr['calendar']->date_time->ts; + //To get date in user selected format + $temp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$temp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$temp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $temp_ts)):('')))); + + if($current_user->column_fields['is_admin']=='on') + $Res = $adb->pquery("select * from vtiger_activitytype",array()); + else + { + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + + if (count($roleids) > 1) { + $Res=$adb->pquery("select distinct activitytype from vtiger_activitytype inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_activitytype.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_activitytype) order by sortid asc", array($roleids)); + } else { + $Res=$adb->pquery("select distinct activitytype from vtiger_activitytype inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_activitytype.picklist_valueid where roleid = ? and picklistid in (select picklistid from vtiger_activitytype) order by sortid asc", array($roleid)); + } + } + + $eventlist=''; + for($i=0; $i<$adb->num_rows($Res);$i++) + { + $eventlist .= $adb->query_result($Res,$i,'activitytype').";"; + } + + $headerdata = ""; + $headerdata .=" +
+
+ +
".$anchor."".$anchor." + + + "; + $tabhtml .= ""; + $tabhtml .= " +
".get_previous_cal($header,$viewBox,$subtab)." + ".display_date($header['view'],$header['calendar']->date_time)."".get_next_cal($header,$viewBox,$subtab)." +
+
view."".$header['calendar']->date_time->get_date_str()."&viewOption=".$viewBox."&subtab=".$subtab."&parenttab=".$category."\");' src='".$header['IMAGE_PATH']."btnL3Calendar.gif' alt='".$mod_strings['LBL_OPENCAL']."...' title='".$mod_strings['LBL_OPENCAL']."...' align='absmiddle' border='0'>view."".$header['calendar']->date_time->get_date_str()."&viewOption=".$viewBox."&subtab=".$subtab."&parenttab=".$category."\");' src='".$header['IMAGE_PATH']."tbarSettings.gif' alt='".$mod_strings['LBL_SETTINGS']."' title='".$mod_strings['LBL_SETTINGS']."' align='absmiddle' border='0'>".$app_strings['Calendar']."
+ "; + if(isPermitted("Calendar","EditView") == "yes") + { + $headerdata .=" + "; + } + else + { + $headerdata .=""; + } + $headerdata .=" + + +
 
+
+ ".$mod_strings['LBL_ADD']." + +
 ";//USER SELECT CUSTOMIZATION + $headerdata .= getEventInfo($cal_arr,'listcnt'); + $headerdata .= "
".$mod_strings['LBL_VIEW']." : ";//USER SELECT CUSTOMIZATION + $view_options = getEventViewOption($cal_arr,$viewBox); + + // User Select Customization + $view_options .= calendarview_getUserSelectOptions( calendarview_getSelectedUserId() ); + // END + + $headerdata .=$view_options."
+
"; + echo $headerdata; + $cal_log->debug("Exiting get_cal_header_data() method..."); +} + +/** + * Function creates HTML select statement to display View selection box + * @param array $cal - collection of objects and strings + * @param string $viewBox - string 'listview' or 'hourview'. if 'listview' means get Events ListView.if 'hourview' means get Events HourView. + * return string $view - html selection box + */ +function getEventViewOption(& $cal,$viewBox) +{ + global $mod_strings,$cal_log; + $category = getParentTab(); + if($viewBox == 'listview') + { + $list_sel = 'selected'; + $hr_sel = ''; + } + else + { + $list_sel = ''; + $hr_sel = 'selected'; + } + $cal_log->debug("Entering getEventViewOption() method..."); + $view = "view."'> + date_time->hour."'> + date_time->day."'> + date_time->week."'> + date_time->month."'> + date_time->year."'> + + + + + + + "; + $cal_log->debug("Exiting getEventViewOption() method..."); + return $view; +} + +/** + * Function creates HTML anchor tag to get previous-day/week/month/year view + * @param array $cal - collection of objects and strings + * @param string $viewBox - string 'listview' or 'hourview' or may be empty. if 'listview' means previous link in Events ListView.if 'hourview' means previous link in Events HourView. if empty means previous link in Todos ListView + * @param string $subtab - string 'todo' or 'event' or may be empty. if 'todo' means Todos View. if 'event' means Events View. if empty means small calendar view. + * return string $link - html tags in string format + */ +function get_previous_cal(& $cal,$viewBox='',$subtab='') +{ + global $mod_strings,$cal_log,$theme; + $category = getParentTab(); + $cal_log->debug("Entering get_previous_cal() method..."); + if(isset($cal['size']) && $cal['size'] == 'small') + { + $link = "view."".$cal['calendar']->get_datechange_info('prev')."&parenttab=".$category."\")'>"; + } + else + { + $link = "view."".$cal['calendar']->get_datechange_info('prev')."&viewOption=".$viewBox."&subtab=".$subtab."&parenttab=".$category."&onlyforuser=".calendarview_getSelectedUserId()."' onclick='VtigerJS_DialogBox.block();return true;'>"; + } + $cal_log->debug("Exiting get_previous_cal() method..."); + return $link; +} + +/** + * Function creates HTML anchor tag to get next-day/week/month/year view + * @param array $cal - collection of objects and strings + * @param string $viewBox - string 'listview' or 'hourview' or may be empty. if 'listview' means next link in Events ListView.if 'hourview' means next link in Events HourView. if empty means next link in Todos ListView + * @param string $subtab - string 'todo' or 'event' or may be empty. if 'todo' means Todos View. if 'event' means Events View. if empty means small calendar view. + * return string $link - html tags in string format + */ +function get_next_cal(& $cal,$viewBox='',$subtab='') +{ + global $mod_strings,$cal_log,$theme; + $category = getParentTab(); + $cal_log->debug("Entering get_next_cal() method..."); + if(isset($cal['size']) && $cal['size'] == 'small') + { + $link = "view."".$cal['calendar']->get_datechange_info('next')."&parenttab=".$category."\")' >"; + } + else + { + $link = "view."".$cal['calendar']->get_datechange_info('next')."&viewOption=".$viewBox."&subtab=".$subtab."&parenttab=".$category."&onlyforuser=".calendarview_getSelectedUserId()."' onclick='VtigerJS_DialogBox.block();return true;'>"; + } + $cal_log->debug("Exiting get_next_cal() method..."); + return $link; + +} + +/** + * Function to get date info depending upon on the calendar view(Eg: 21 July 2000) + * @param string $view - calendar view(day/week/month/year) + * @param array $date_time - contains DateTime object + * return string $label - date info(Eg for dayview : 13 July 2000) + */ +function display_date($view,$date_time) +{ + global $cal_log; + $cal_log->debug("Entering display_date() method..."); + if ($view == 'day') + { + //$label = $date_time->getdayofWeek()." "; + $label = $date_time->get_Date()." "; + $label .= $date_time->getmonthName()." "; + $label .= $date_time->year; + $cal_log->debug("Exiting display_date() method..."); + return $label; + } + elseif ($view == 'week') + { + $week_start = $date_time->getThisweekDaysbyIndex(0); + $week_end = $date_time->getThisweekDaysbyIndex(6); + $label = $week_start->get_Date()." "; + $label .= $week_start->getmonthName()." "; + $label .= $week_start->year; + $label .= " - "; + $label .= $week_end->get_Date()." "; + $label .= $week_end->getmonthName()." "; + $label .= $week_end->year; + $cal_log->debug("Exiting display_date() method..."); + return $label; + } + + elseif ($view == 'month') + { + $label = $date_time->getmonthName()." "; + $label .= $date_time->year; + $cal_log->debug("Exiting display_date() method..."); + return $label; + } + elseif ($view == 'year') + { + $cal_log->debug("Exiting display_date() method..."); + return $date_time->year; + } + +} +/** + * Function to get css class name for date + * @param string $slice_date - date + * returns string - css class name or empty string + */ +function dateCheck($slice_date) +{ + global $cal_log; + $cal_log->debug("Entering dateCheck() method..."); + $today = date('Y-m-d'); + if($today == $slice_date) + { + $cal_log->debug("Exiting dateCheck() method..."); + //css class for day having event(s) + return 'currDay'; + } + else + { + $cal_log->debug("Exiting dateCheck() method..."); + return ''; + } +} + +/** + * Function to construct respective calendar layout depends on the calendar view + * @param array $view - collection of objects and strings + */ +function getHourView(& $view) +{ + global $cal_log,$theme; + $hourview_layout = ''; + $cal_log->debug("Entering getHourView() method..."); + $hourview_layout .= '
+
'; + + if($view['view'] == 'day') + $hourview_layout .= getDayViewLayout($view); + elseif($view['view'] == 'week') + $hourview_layout .= getWeekViewLayout($view); + elseif($view['view'] == 'month') + $hourview_layout .= getMonthViewLayout($view); + elseif($view['view'] == 'year') + $hourview_layout .= getYearViewLayout($view); + else + die("view:".$view['view']." is not defined"); + + $hourview_layout .= '
+ '; + $hourview_layout .= '
+ + + + + + + + +
'; + echo $hourview_layout; + $cal_log->debug("Exiting getHourView() method..."); +} + +/** + * Fuction constructs Events ListView depends on the view + * @param array $cal - collection of objects and strings + * @param string $mode - string 'listcnt' or empty. if empty means get Events ListView else get total no. of events and no. of pending events Info. + * returns string $activity_list - total no. of events and no. of pending events Info(Eg: Total Events : 2, 1 Pending). + */ +function getEventListView(& $cal,$mode='') +{ + global $cal_log,$theme; + $list_view = ""; + $cal_log->debug("Entering getEventListView() method..."); + if($cal['calendar']->view == 'day') + { + $start_date = $end_date = $cal['calendar']->date_time->get_formatted_date(); + } + elseif($cal['calendar']->view == 'week') + { + $start_date = $cal['calendar']->slices[0]; + $end_date = $cal['calendar']->slices[6]; + } + elseif($cal['calendar']->view == 'month') + { + $start_date = $cal['calendar']->date_time->getThismonthDaysbyIndex(0); + $end_date = $cal['calendar']->date_time->getThismonthDaysbyIndex($cal['calendar']->date_time->daysinmonth - 1); + $start_date = $start_date->get_formatted_date(); + $end_date = $end_date->get_formatted_date(); + } + elseif($cal['calendar']->view == 'year') + { + $start_date = $cal['calendar']->date_time->getThisyearMonthsbyIndex(0); + $end_date = $cal['calendar']->date_time->get_first_day_of_changed_year('increment'); + $start_date = $start_date->get_formatted_date(); + $end_date = $end_date->get_formatted_date(); + } + else + { + die("view:".$cal['calendar']->view." is not defined"); + } + //if $mode value is empty means get Events list in array format else get the count of total events and pending events in array format. + if($mode != '') + { + $activity_list = getEventList($cal, $start_date, $end_date,$mode); + $cal_log->debug("Exiting getEventListView() method..."); + return $activity_list; + } + else + { + $ret_arr = getEventList($cal, $start_date, $end_date,$mode); + $activity_list = $ret_arr[0]; + $navigation_array = $ret_arr[1]; + } + //To get Events listView + $list_view .="
"; + $list_view .=constructEventListView($cal,$activity_list,$navigation_array); + $list_view .="
+ "; + $list_view .="
+ + + + + + + + +
"; + echo $list_view; + $cal_log->debug("Exiting getEventListView() method..."); +} + + +/** + * Fuction constructs Todos ListView depends on the view + * @param array $cal - collection of objects and strings + * @param string $check - string 'listcnt' or empty. if empty means get Todos ListView else get total no. of Todos and no. of pending todos Info. + * returns string $todo_list - total no. of todos and no. of pending todos Info(Eg: Total Todos : 2, 1 Pending). + */ +function getTodosListView($cal, $check='',$subtab='') +{ + global $cal_log,$theme; + $list_view = ""; + $cal_log->debug("Entering getTodosListView() method..."); + if($cal['calendar']->view == 'day') + { + $start_date = $end_date = $cal['calendar']->date_time->get_formatted_date(); + } + elseif($cal['calendar']->view == 'week') + { + $start_date = $cal['calendar']->slices[0]; + $end_date = $cal['calendar']->slices[6]; + } + elseif($cal['calendar']->view == 'month') + { + $start_date = $cal['calendar']->date_time->getThismonthDaysbyIndex(0); + $end_date = $cal['calendar']->date_time->getThismonthDaysbyIndex($cal['calendar']->date_time->daysinmonth - 1); + $start_date = $start_date->get_formatted_date(); + $end_date = $end_date->get_formatted_date(); + } + elseif($cal['calendar']->view == 'year') + { + $start_date = $cal['calendar']->date_time->getThisyearMonthsbyIndex(0); + $end_date = $cal['calendar']->date_time->get_first_day_of_changed_year('increment'); + $start_date = $start_date->get_formatted_date(); + $end_date = $end_date->get_formatted_date(); + } + else + { + die("view:".$cal['calendar']->view." is not defined"); + } + //if $check value is empty means get Todos list in array format else get the count of total todos and pending todos in array format. + if($check != '') + { + $todo_list = getTodoList($cal, $start_date, $end_date,$check); + $cal_log->debug("Exiting getTodosListView() method..."); + return $todo_list; + } + else + { + $ret_arr = getTodoList($cal, $start_date, $end_date,$check); + $todo_list = $ret_arr[0]; + $navigation_arr = $ret_arr[1]; + } + $cal_log->debug("Exiting getTodosListView() method..."); + $list_view .="
"; + //To get Todos listView + $list_view .= constructTodoListView($todo_list,$cal,$subtab,$navigation_arr); + $list_view .="
+ + + + + + + + + + "; + echo $list_view; +} + +/** + * Function creates HTML to display Calendar DayView + * @param array $cal - collections of objects and strings. + * return string $dayview_layout - html tags in string format + */ +function getDayViewLayout(& $cal) +{ + global $current_user,$app_strings,$cal_log,$adb; + $no_of_rows = 1; + $cal_log->debug("Entering getDayViewLayout() method..."); + $date_format = $current_user->date_format; + $day_start_hour = $cal['calendar']->day_start_hour; + $day_end_hour = $cal['calendar']->day_end_hour; + $format = $cal['calendar']->hour_format; + $show_complete_view = false; + if(!empty($_REQUEST['complete_view'])){ + $show_complete_view =true; + } + $dayview_layout = ''; + $dayview_layout .= ' '; + $dayview_layout .= ' +
+ '; + if(!empty($show_complete_view)) { + $dayview_layout .= ''; + $day_start_hour = 0; + $day_end_hour = 23; + } else { + $dayview_layout .= ''; + } + for($j=0;$j<24;$j++) + { + $slice = $cal['calendar']->slices[$j]; + $act = $cal['calendar']->day_slice[$slice]->activities; + if(!empty($act)) + { + $temprows = count($act); + $no_of_rows = ($no_of_rows>$temprows)?$no_of_rows:$temprows; + } + } + for($i=$day_start_hour;$i<=$day_end_hour;$i++) + { + $time = array('hour'=>$i,'minute'=>0); + $sub_str = timeString($time,$format); + $y = $i+1; + $hour_startat = timeString(array('hour'=>$i,'minute'=>0),'24'); + $hour_endat = timeString(array('hour'=>$y,'minute'=>0),'24'); + $time_arr = getaddEventPopupTime($hour_startat,$hour_endat,$format); + $temp_ts = $cal['calendar']->date_time->ts; + $sttemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$temp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$temp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $temp_ts)):('')))); + if($i != 23) + { + $endtemp_date = $sttemp_date; + } + else + { + $addday = $temp_ts + (1 * 24 * 60 * 60); + $endtemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$addday)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$addday)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $addday)):('')))); + } + + $js_string = ""; + if(isPermitted("Calendar","EditView") == "yes") + $js_string = 'onClick="fnvshobj(this,\'addEvent\'); gshow(\'addEvent\',\'Call\',\''.$sttemp_date.'\',\''.$endtemp_date.'\',\''.$time_arr['starthour'].'\',\''.$time_arr['startmin'].'\',\''.$time_arr['startfmt'].'\',\''.$time_arr['endhour'].'\',\''.$time_arr['endmin'].'\',\''.$time_arr['endfmt'].'\',\'hourview\',\'event\')"'; + $dayview_layout .= ' + '; + //To display events in Dayview + $dayview_layout .= getdayEventLayer($cal,$cal['calendar']->slices[$i],$no_of_rows); + $dayview_layout .= ''; + } + $dayview_layout .= '
  
  
'.$sub_str.'
+
'; + $cal_log->debug("Exiting getDayViewLayout() method..."); + return $dayview_layout; +} + +/** + * Function creates HTML to display Calendar WeekView + * @param array $cal - collections of objects and strings. + * return string $weekview_layout - html tags in string format + */ +function getWeekViewLayout(& $cal) +{ + global $current_user,$app_strings,$cal_log,$theme; + $category = getParentTab(); + $cal_log->debug("Entering getWeekViewLayout() method..."); + $date_format = $current_user->date_format; + $day_start_hour = $cal['calendar']->day_start_hour; + $day_end_hour = $cal['calendar']->day_end_hour; + $format = $cal['calendar']->hour_format; + $show_complete_view = false; + if(!empty($_REQUEST['complete_view'])){ + $show_complete_view =true; + } + $weekview_layout = ''; + $weekview_layout .= ''; + for ($col=0;$col<=7;$col++) + { + if($col==0) { + $weekview_layout .= ''; + if(!empty($show_complete_view)) { + $weekview_layout .= ''; + $day_start_hour = 0; + $day_end_hour = 23; + } else { + $weekview_layout .= ''; + } + } else { + //To display Days in Week + $cal['slice'] = $cal['calendar']->week_array[$cal['calendar']->slices[$col-1]]; + $date = $cal['calendar']->date_time->getThisweekDaysbyIndex($col-1); + $day = $date->getdayofWeek_inshort(); + $weekview_layout .= ''; + } + } + $weekview_layout .= '
'; + $weekview_layout .= ''; + $weekview_layout .= $date->get_Date().' - '.$day; + $weekview_layout .= ""; + $weekview_layout .= '
'; + $weekview_layout .= ''; + //To display Hours in User selected format + for($i=$day_start_hour;$i<=$day_end_hour;$i++) + { + $count = $i; + $hour_startat = timeString(array('hour'=>$i,'minute'=>0),'24'); + $hour_endat = timeString(array('hour'=>($i+1),'minute'=>0),'24'); + $time_arr = getaddEventPopupTime($hour_startat,$hour_endat,$format); + $weekview_layout .= ''; + for ($column=1;$column<=1;$column++) + { + $time = array('hour'=>$i,'minute'=>0); + $sub_str = timeString($time,$format); + + $weekview_layout .= ''; + } + for ($column=0;$column<=6;$column++) + { + $temp_ts = $cal['calendar']->week_array[$cal['calendar']->slices[$column]]->start_time->ts; + $sttemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$temp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$temp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $temp_ts)):('')))); + if($i != 23) + $endtemp_date = $sttemp_date; + else + { + $endtemp_ts = $cal['calendar']->week_array[$cal['calendar']->slices[$column+1]]->start_time->ts; + $endtemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$endtemp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$endtemp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $endtemp_ts)):('')))); + } + + $weekview_layout .= ''; + $count = $count+24; + } + $weekview_layout .= ''; + } + $weekview_layout .= '
'; + $weekview_layout .=$sub_str; + $weekview_layout .= ''; + $weekview_layout .= ''; + //To display events in WeekView + $weekview_layout .=getweekEventLayer($cal,$cal['calendar']->week_hour_slices[$count]); + $weekview_layout .= '
'; + return $weekview_layout; + $cal_log->debug("Exiting getWeekViewLayout() method..."); + +} + +/** + * Function creates HTML to display Calendar MonthView + * @param array $cal - collections of objects and strings. + * return string $monthview_layout - html tags in string format + */ +function getMonthViewLayout(& $cal) +{ + global $current_user,$app_strings,$cal_log,$theme; + $category = getParentTab(); + $cal_log->debug("Entering getMonthViewLayout() method..."); + $date_format = $current_user->date_format; + $count = 0; + //To get no. of rows(weeks) in month + if ($cal['calendar']->month_array[$cal['calendar']->slices[35]]->start_time->month != $cal['calendar']->date_time->month) { + $rows = 5; + } else { + $rows = 6; + } + $format = $cal['calendar']->hour_format; + $hour_startat = timeString(array('hour'=>date('H:i'),'minute'=>0),'24'); + $hour_endat = timeString(array('hour'=>date('H:i',(time() + (60 * 60))),'minute'=>0),'24'); + $time_arr = getaddEventPopupTime($hour_startat,$hour_endat,$format); + $monthview_layout = ''; + $monthview_layout .= ''; + //To display days in week + for ($i = 0; $i < 7; $i ++) + { + $first_row = $cal['calendar']->month_array[$cal['calendar']->slices[$i]]; + $weekday = $first_row->start_time->getdayofWeek(); + $monthview_layout .= ''; + } + $monthview_layout .= '
'.$weekday.'
'; + $monthview_layout .= ' '; + $cnt = 0; + for ($i = 0; $i < $rows; $i ++) + { + $monthview_layout .= ''; + for ($j = 0; $j < 7; $j ++) + { + $temp_ts = $cal['calendar']->month_array[$cal['calendar']->slices[$count]]->start_time->ts; + $temp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$temp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$temp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $temp_ts)):('')))); + if($cal['calendar']->day_start_hour != 23) + $endtemp_date = $temp_date; + else + { + $endtemp_ts = $cal['calendar']->month_array[$cal['calendar']->slices[$count+1]]->start_time->ts; + $endtemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$endtemp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$endtemp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $endtemp_ts)):('')))); + } + $cal['slice'] = $cal['calendar']->month_array[$cal['calendar']->slices[$count]]; + $monthclass = dateCheck($cal['slice']->start_time->get_formatted_date()); + if($monthclass != '') + $monthclass = 'calSel'; + else + $monthclass = 'dvtCellLabel'; + //to display dates in month + if ($cal['slice']->start_time->getMonth() == $cal['calendar']->date_time->getMonth()) + { + $monthview_layout .= ''; + } + else + { + $monthview_layout .= ''; + } + $count++; + } + $monthview_layout .= ''; + $monthview_layout .= ''; + for ($j = 0; $j < 7; $j ++) + { + $monthview_layout .= ''; + $cnt++; + } + $monthview_layout .= ''; + } + $monthview_layout .= '
'; + $monthview_layout .= ''; + $monthview_layout .= $cal['slice']->start_time->get_Date(); + $monthview_layout .= ''; + $monthview_layout .= ' 
'; + $monthview_layout .= getmonthEventLayer($cal,$cal['calendar']->slices[$cnt]); + $monthview_layout .= '
'; + return $monthview_layout; + $cal_log->debug("Exiting getMonthViewLayout() method..."); + +} + +/** + * Function creates HTML to display Calendar YearView + * @param array $cal - collections of objects and strings. + * return string $yearview_layout - html tags in string format + */ +function getYearViewLayout(& $cal) +{ + global $mod_strings,$cal_log; + $category = getParentTab(); + $cal_log->debug("Entering getYearViewLayout() method..."); + $yearview_layout = ''; + $yearview_layout .= ''; + $count = 0; + //year view divided as 4 rows and 3 columns + for($i=0;$i<4;$i++) + { + $yearview_layout .= ''; + for($j=0;$j<3;$j++) + { + $cal['slice'] = $cal['calendar']->year_array[$cal['calendar']->slices[$count]]; + $yearview_layout .= ''; + } + $yearview_layout .= '
+ + + + '; + for($w=0;$w<7;$w++) + { + $yearview_layout .= ''; + } + $yearview_layout .= ''; + list($_3rdyear,$_3rdmonth,$_3rddate) = explode("-",$cal['calendar']->month_day_slices[$count][35]); + list($_2ndyear,$_2ndmonth,$_2nddate) = explode("-",$cal['calendar']->month_day_slices[$count][6]); + //to get no. of rows(weeks) in month + if ($_3rdmonth != $_2ndmonth) { + $rows = 5; + } else { + $rows = 6; + } + $cnt = 0; + $date_stack = Array(); + for ($k = 0; $k < 5; $k ++) + { + $yearview_layout .= ''; + for ($mr = 0; $mr < 7; $mr ++) + { + list($_1styear,$_1stmonth,$_1stdate) = explode("-",$cal['calendar']->month_day_slices[$count][$cnt]); + if(count($cal['slice']->activities) != 0) + { + for($act_count = 0;$act_countactivities);$act_count++) + { + array_push($date_stack,$cal['slice']->activities[$act_count]->start_time->get_formatted_date()); + } + } + if(in_array($cal['calendar']->month_day_slices[$count][$cnt],$date_stack)) + $event_class = 'class="eventDay"'; + else + $event_class = ''; + if($_1stmonth == $_2ndmonth) + $curclass = dateCheck($cal['calendar']->month_day_slices[$count][$cnt]); + if($curclass != '') + { + $class = 'class="'.$curclass.'"'; + $curclass = ''; + } + else + { + $class = $event_class; + $event_class = ''; + } + $date = $_1stdate + 0; + $month = $_1stmonth + 0; + $yearview_layout .= ''; + $cnt++; + } + $yearview_layout .= ''; + } + $yearview_layout .= ' +
+ + '.$cal['slice']->start_time->month_inlong.' + +
'.$mod_strings['cal_weekdays_short'][$w].'
'; + if($rows == 6 && $k==0) + { + list($tempyear,$tempmonth,$tempdate) = explode("-",$cal['calendar']->month_day_slices[$count][35+$mr]); + if($tempmonth == $_2ndmonth) + $yearview_layout .= ''.$tempdate; + } + if($_1stmonth == $_2ndmonth) + { + $yearview_layout .= ''.$date; + } + $yearview_layout .= '
+ + + '; + $count++; + } + $yearview_layout .= '
'; + return $yearview_layout; + $cal_log->debug("Exiting getYearViewLayout() method..."); + + +} + +/** + * Function creates HTML To display events in day view + * @param array $cal - collection of objects and strings + * @param string $slice - date:time(eg: 2006-07-13:10) + * returns string $eventlayer - hmtl in string format + */ +function getdayEventLayer(& $cal,$slice,$rows) +{ + global $mod_strings,$cal_log,$listview_max_textlength,$adb,$current_user,$theme; + $category = getParentTab(); + $cal_log->debug("Entering getdayEventLayer() method..."); + $eventlayer = ''; + $arrow_img_name = ''; + $rows = $rows + 1; + $last_colwidth = 100 / $rows; + $width = 100 / $rows ; + $act = $cal['calendar']->day_slice[$slice]->activities; + if(!empty($act)) + { + for($i=0;$iday_slice[$slice]->start_time->hour.'_'.$i; + $subject = $act[$i]->subject; + $id = $act[$i]->record; + if($listview_max_textlength && (strlen($subject)>$listview_max_textlength)) + $subject = substr($subject,0,$listview_max_textlength)."..."; + $format = $cal['calendar']->hour_format; + $duration_hour = $act[$i]->duration_hour; + $duration_min =$act[$i]->duration_minute; + $user = $act[$i]->owner; + $priority = $act[$i]->priority; + if($duration_min != '00') + $rowspan = $duration_hour+$rowspan; + elseif($duration_hour != '0') + { + $rowspan = $duration_hour; + } + $row_cnt = $rowspan; + $start_hour = timeString($act[$i]->start_time,$format); + $end_hour = timeString($act[$i]->end_time,$format); + $account_name = $act[$i]->accountname; + $eventstatus = $act[$i]->eventstatus; + $color = $act[$i]->color; + $image = vtiger_imageurl($act[$i]->image_name, $theme); + if($act[$i]->recurring) + $recurring = ''; + else + $recurring = ' '; + $height = $rowspan * 75; + $javacript_str = ''; + $idShared = "normal"; if($act[$i]->shared) $idShared = "shared"; + /*if($eventstatus != 'Held') + {*/ + if($idShared == "normal") + { + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete") == "yes") + $javacript_str = 'onMouseOver="cal_show(\''.$arrow_img_name.'\');" onMouseOut="fnHide_Event(\''.$arrow_img_name.'\');"'; + $action_str = ''; + } + else + { + $javacript_str = ''; + $eventlayer .= ' '; + } + $eventlayer .= ''; + + $visibility_query=$adb->pquery('SELECT visibility from vtiger_activity where activityid=?',array($id)); + $visibility = $adb->query_result($visibility_query,0,'visibility'); + $user_query = $adb->pquery("SELECT vtiger_crmentity.smownerid,vtiger_users.user_name from vtiger_crmentity,vtiger_users where crmid=? and vtiger_crmentity.smownerid=vtiger_users.id", array($id)); + $userid = $adb->query_result($user_query,0,"smownerid"); + $assigned_role_query=$adb->pquery("select roleid from vtiger_user2role where userid=?",array($userid)); + $assigned_role_id = $adb->query_result($assigned_role_query,0,"roleid"); + $role_list = $adb->pquery("SELECT * from vtiger_role WHERE parentrole LIKE '". formatForSqlLike($current_user->column_fields['roleid']) . formatForSqlLike($assigned_role_id) ."'",array()); + $is_shared = $adb->pquery("SELECT * from vtiger_sharedcalendar where userid=? and sharedid=?",array($userid,$current_user->id)); + if(($current_user->column_fields['is_admin']!='on' && $adb->num_rows($role_list)==0 && (($adb->num_rows($is_shared)==0 && ($visibility=='Public' || $visibility=='Private')) || $visibility=='Private')) && $current_user->column_fields['user_name']!=$user) + { + $eventlayer .= '
'; + } + else{ + $eventlayer .= '
'; + } + $eventlayer .= ' + + + '; + $eventlayer .= ''; + + if(($current_user->column_fields['is_admin']!='on' && $adb->num_rows($role_list)==0 && (($adb->num_rows($is_shared)==0 && ($visibility=='Public' || $visibility=='Private')) || $visibility=='Private')) && $current_user->column_fields['user_name']!=$user) + { + $eventlayer .= ''; + }else{ + $eventlayer .= ' + + '; + } $eventlayer .= '
'.$start_hour.' - '.$end_hour.'
'.$recurring.''.$user.' - '.$mod_strings['LBL_BUSY'].''.$subject.'
'; + if($act[$i]->shared) + $eventlayer .= ''; + else + $eventlayer .= ' '; + $eventlayer .= '('.$user.' | '.getTranslatedString($eventstatus).' | '.getTranslatedString($priority).')
'.$action_str.' 
'; + } + $eventlayer .= ' '; + } + else + { + $eventlayer .= ' '; + $eventlayer .= ' '; + } + $cal_log->debug("Exiting getdayEventLayer() method..."); + return $eventlayer; +} + +/** + * Function creates HTML To display events in week view + * @param array $cal - collection of objects and strings + * @param string $slice - date:time(eg: 2006-07-13:10) + * returns string $eventlayer - hmtl in string format + */ +function getweekEventLayer(& $cal,$slice) +{ + global $mod_strings,$cal_log,$listview_max_textlength,$adb,$current_user,$theme; + $category = getParentTab(); + $cal_log->debug("Entering getweekEventLayer() method..."); + $eventlayer = ''; + $arrow_img_name = ''; + $act = $cal['calendar']->week_slice[$slice]->activities; + if(!empty($act)) + { + for($i=0;$iweek_slice[$slice]->start_time->get_formatted_date().'_'.$act[$i]->start_time->hour.'_'.$i; + /* fix given by dartagnanlaf END --integrated by Minnie */ + $id = $act[$i]->record; + $subject = $act[$i]->subject; + if($listview_max_textlength && (strlen($subject)>$listview_max_textlength)) + $subject = substr($subject,0,$listview_max_textlength)."..."; + $format = $cal['calendar']->hour_format; + $start_hour = timeString($act[$i]->start_time,$format); + $end_hour = timeString($act[$i]->end_time,$format); + $account_name = $act[$i]->accountname; + $eventstatus = $act[$i]->eventstatus; + $user = $act[$i]->owner; + $priority = $act[$i]->priority; + $image = vtiger_imageurl($act[$i]->image_name, $theme); + $idShared = "normal"; if($act[$i]->shared) $idShared = "shared"; + if($act[$i]->recurring) + $recurring = ''; + else + $recurring = ' '; + $color = $act[$i]->color; + if($idShared == "normal") + { + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete") == "yes") + $javacript_str = 'onMouseOver="cal_show(\''.$arrow_img_name.'\');" onMouseOut="fnHide_Event(\''.$arrow_img_name.'\');"'; + $action_str = ''; + } + else + { + $javacript_str = ''; + $eventlayer .= ' '; + } + + $visibility_query=$adb->pquery('SELECT visibility from vtiger_activity where activityid=?',array($id)); + $visibility = $adb->query_result($visibility_query,0,'visibility'); + $user_query = $adb->pquery("SELECT vtiger_crmentity.smownerid,vtiger_users.user_name from vtiger_crmentity,vtiger_users where crmid=? and vtiger_crmentity.smownerid=vtiger_users.id", array($id)); + $userid = $adb->query_result($user_query,0,"smownerid"); + $assigned_role_query=$adb->pquery("select roleid from vtiger_user2role where userid=?",array($userid)); + $assigned_role_id = $adb->query_result($assigned_role_query,0,"roleid"); + $role_list = $adb->pquery("SELECT * from vtiger_role WHERE parentrole LIKE '". formatForSqlLike($current_user->column_fields['roleid']) . formatForSqlLike($assigned_role_id) ."'",array()); + $is_shared = $adb->pquery("SELECT * from vtiger_sharedcalendar where userid=? and sharedid=?",array($userid,$current_user->id)); + if(($current_user->column_fields['is_admin']!='on' && $adb->num_rows($role_list)==0 && (($adb->num_rows($is_shared)==0 && ($visibility=='Public' || $visibility=='Private')) || $visibility=='Private')) && $current_user->column_fields['user_name']!=$user) + { + $eventlayer .= '
'; + } + else{ + $eventlayer .= '
'; + } + + $eventlayer .=' + + + + + + '; + if(($current_user->column_fields['is_admin']!='on' && $adb->num_rows($role_list)==0 && (($adb->num_rows($is_shared)==0 && ($visibility=='Public' || $visibility=='Private')) || $visibility=='Private')) && $current_user->column_fields['user_name']!=$user) + { + $eventlayer .= ''; + }else{//CALUSER CUST END + $eventlayer .= ' + + '; + } + $eventlayer .= '
'.$start_hour.' - '.$end_hour.'
'.$recurring.''.$user.'-'.$mod_strings['LBL_BUSY'].''.$subject.'
'; + if($act[$i]->shared) + $eventlayer .= ''; + else + $eventlayer .= ' '; + $eventlayer .= '('.$user.' | '.getTranslatedString($eventstatus).' | '.getTranslatedString($priority).')
'.$action_str.' 

'; + } + $cal_log->debug("Exiting getweekEventLayer() method..."); + return $eventlayer; + } + +} + +/** + * Function creates HTML To display events in month view + * @param array $cal - collection of objects and strings + * @param string $slice - date(eg: 2006-07-13) + * returns string $eventlayer - hmtl in string format + */ +function getmonthEventLayer(& $cal,$slice) +{ + global $mod_strings,$cal_log,$adb,$current_user,$theme; + $category = getParentTab(); + $cal_log->debug("Entering getmonthEventLayer() method..."); + $eventlayer = ''; + $arrow_img_name = ''; + $act = $cal['calendar']->month_array[$slice]->activities; + if(!empty($act)) + { + $no_of_act = count($act); + if($no_of_act>2) + { + $act_row = 2; + $remin_list = $no_of_act - $act_row; + } + else + { + $act_row = $no_of_act; + $remin_list = null; + } + for($i=0;$i<$act_row;$i++) + { + $arrow_img_name = 'event'.$cal['calendar']->month_array[$slice]->start_time->hour.'_'.$i; + $id = $act[$i]->record; + $subject = $act[$i]->subject; + if(strlen($subject)>10) + $subject = substr($subject,0,10)."..."; + $format = $cal['calendar']->hour_format; + $start_hour = timeString($act[$i]->start_time,$format); + $end_hour = timeString($act[$i]->end_time,$format); + $account_name = $act[$i]->accountname; + $image = vtiger_imageurl($act[$i]->image_name, $theme); + $color = $act[$i]->color; + //Added for User Based Customview for Calendar Module + $visibility_query=$adb->pquery('SELECT visibility from vtiger_activity where activityid=?',array($id)); + $visibility = $adb->query_result($visibility_query,0,'visibility'); + $user_query = $adb->pquery("SELECT vtiger_crmentity.smownerid,vtiger_users.user_name from vtiger_crmentity,vtiger_users where crmid=? and vtiger_crmentity.smownerid=vtiger_users.id", array($id)); + $userid = $adb->query_result($user_query,0,"smownerid"); + $username = $adb->query_result($user_query,0,"user_name"); + $assigned_role_query=$adb->pquery("select roleid from vtiger_user2role where userid=?",array($userid)); + $assinged_role_id = $adb->query_result($assigned_role_query,0,"roleid"); + $role_list = $adb->pquery("SELECT * from vtiger_role WHERE parentrole LIKE '". formatForSqlLike($current_user->column_fields['roleid']) . formatForSqlLike($assinged_role_id) ."'",array()); + $is_shared = $adb->pquery("SELECT * from vtiger_sharedcalendar where userid=? and sharedid=?",array($userid,$current_user->id)); + + if(($current_user->column_fields['is_admin']!='on' && $adb->num_rows($role_list)==0 && (($adb->num_rows($is_shared)==0 && ($visibility=='Public' || $visibility=='Private')) || $visibility=='Private')) && $current_user->id != $userid) + { + $eventlayer .='
+  '.$username.' - '.$mod_strings["LBL_BUSY"].' +

'; + }else{ + $eventlayer .='
'; + } + } + + if($remin_list != null) + { + $eventlayer .=''; + } + $cal_log->debug("Exiting getmonthEventLayer() method..."); + return $eventlayer; + } +} + +/** + * Function to get events list scheduled between specified dates + * @param array $calendar - collection of objects and strings + * @param string $start_date - date string + * @param string $end_date - date string + * @param string $info - string 'listcnt' or empty string. if 'listcnt' means it returns no. of events and no. of pending events in array format else it returns events list in array format + * return array $Entries - eventslists in array format + */ +function getEventList(& $calendar,$start_date,$end_date,$info='') +{ + global $log,$theme; + $Entries = Array(); + $category = getParentTab(); + global $adb,$current_user,$mod_strings,$app_strings,$cal_log,$listview_max_textlength,$list_max_entries_per_page; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $cal_log->debug("Entering getEventList() method..."); + + //modified query to fix the ticket #5014 & #5180 + $and = "AND ((((vtiger_activity.date_start between ? AND ?) + OR (vtiger_activity.date_start < ? AND vtiger_activity.due_date > ?) + OR (vtiger_activity.due_date between ? AND ?)) + AND (vtiger_recurringevents.activityid is NULL)) + OR (vtiger_recurringevents.recurringdate BETWEEN ? AND ?))"; + + $count_qry = "SELECT count(*) as count FROM vtiger_activity + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_activity.activityid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT OUTER JOIN vtiger_recurringevents + ON vtiger_recurringevents.activityid = vtiger_activity.activityid + WHERE vtiger_crmentity.deleted = 0 + AND (vtiger_activity.activitytype not in ('Emails','Task')) $and "; + + $query = "SELECT vtiger_groups.groupname, vtiger_users.user_name,vtiger_crmentity.smownerid, vtiger_crmentity.crmid, + vtiger_activity.* FROM vtiger_activity + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_activity.activityid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT OUTER JOIN vtiger_recurringevents + ON vtiger_recurringevents.activityid = vtiger_activity.activityid + WHERE vtiger_crmentity.deleted = 0 + AND (vtiger_activity.activitytype not in ('Emails','Task')) $and "; + $list_query = $query." AND vtiger_crmentity.smownerid = " . $current_user->id; + + // User Select Customization: Changes should made also in (Appointment::readAppointment) + $query_filter_prefix = calendarview_getSelectedUserFilterQuerySuffix(); + $query .= $query_filter_prefix; + $count_query .= $query_filter_prefix; + // END + + $params = $info_params = array($start_date, $end_date, $start_date, $end_date, $start_date, $end_date, $start_date, $end_date); + if($info != '') + { + $groupids = explode(",", fetchUserGroupids($current_user->id)); // Explode can be removed, once implode is removed from fetchUserGroupids + if (count($groupids) > 0) { + + $com_q = " AND (vtiger_crmentity.smownerid = ? + OR vtiger_groups.groupid in (". generateQuestionMarks($groupids) .")) + GROUP BY vtiger_activity.activityid"; + } else { + $com_q = " AND vtiger_crmentity.smownerid = ? + GROUP BY vtiger_activity.activityid"; + } + + $pending_query = $query." AND (vtiger_activity.eventstatus = 'Planned')".$com_q; + $total_q = $query."".$com_q; + array_push($info_params, $current_user->id); + + if (count($groupids) > 0) { + array_push($info_params, $groupids); + } + + $total_res = $adb->pquery($total_q, $info_params); + $total = $adb->num_rows($total_res); + + $res = $adb->pquery($pending_query, $info_params); + $pending_rows = $adb->num_rows($res); + $cal_log->debug("Exiting getEventList() method..."); + return Array('totalevent'=>$total,'pendingevent'=>$pending_rows); + } + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3) + { + $sec_parameter=getCalendarViewSecurityParameter(); + $query .= $sec_parameter; + $list_query .= $sec_parameter; + $count_qry .= $sec_parameter; + } + if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'search') + { + $search_where = calendar_search_where($_REQUEST['field_name'],$_REQUEST['search_option'],$_REQUEST['search_text']); + $group_cond .= $search_where; + $count_qry .= $search_where; + } + $group_cond .= " GROUP BY vtiger_activity.activityid ORDER BY vtiger_activity.date_start,vtiger_activity.time_start ASC"; + $count_qry .= ' GROUP BY vtiger_activity.activityid '; + $count_res = $adb->pquery($count_qry, $params); + $total_rec_count = $adb->num_rows($count_res); + if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') + $start = vtlib_purify($_REQUEST['start']); + else + $start = 1; + $navigation_array = getNavigationValues($start, $total_rec_count, $list_max_entries_per_page); + $start_rec = $navigation_array['start']; + $end_rec = $navigation_array['end_val']; + if($start_rec <= 1) + $start_rec = 0; + else + $start_rec = $start_rec-1; + $query .= $group_cond." limit $start_rec,$list_max_entries_per_page"; + $list_query .= $group_cond; + + if( $adb->dbType == "pgsql"){ + $query = fixPostgresQuery( $query, $log, 0); + $list_query = fixPostgresQuery( $list_query, $log, 0); + } + $list_query = $adb->convert2Sql($list_query, $params); + $_SESSION['Calendar_listquery'] = $list_query; + + $result = $adb->pquery($query, $params); + $rows = $adb->num_rows($result); + $c = 0; + if($start > 1) + $c = ($start-1) * $list_max_entries_per_page; + for($i=0;$i<$rows;$i++) + { + $element = Array(); + $element['no'] = $c+1; + $image_tag = ""; + $contact_data = ""; + $more_link = ""; + $start_time = $adb->query_result($result,$i,"time_start"); + $end_time = $adb->query_result($result,$i,"time_end"); + $format = $calendar['calendar']->hour_format; + $value = getaddEventPopupTime($start_time,$end_time,$format); + $start_hour = $value['starthour'].':'.$value['startmin'].''.$value['startfmt']; + $end_hour = $value['endhour'] .':'.$value['endmin'].''.$value['endfmt']; + $date_start = $adb->query_result($result,$i,"date_start"); + $due_date = $adb->query_result($result,$i,"due_date"); + $element['starttime'] = getDisplayDate($date_start).' '.$start_hour; + $element['endtime'] = getDisplayDate($due_date).' '.$end_hour; + $contact_id = $adb->query_result($result,$i,"contactid"); + $id = $adb->query_result($result,$i,"activityid"); + $subject = $adb->query_result($result,$i,"subject"); + $eventstatus = $adb->query_result($result,$i,"eventstatus"); + $assignedto = $adb->query_result($result,$i,"user_name"); + $userid = $adb->query_result($result,$i,"smownerid"); + $idShared = "normal"; + if(!empty($assignedto) && $userid != $current_user->id && $adb->query_result($result,$i,"visibility") == "Public") + { + $que = "select * from vtiger_sharedcalendar where sharedid=? and userid=?"; + $row = $adb->pquery($que, array($current_user->id, $userid)); + $no = $adb->getRowCount($row); + if($no > 0) $idShared = "shared"; + else $idShared = "normal"; + + + } + if($listview_max_textlength && (strlen($subject)>$listview_max_textlength)) + $subject = substr($subject,0,$listview_max_textlength)."..."; + if($contact_id != '') + { + $contactname = getContactName($contact_id); + $contact_data = "".$contactname.","; + } + $more_link = "[".$mod_strings['LBL_MORE']."...]"; + $type = $adb->query_result($result,$i,"activitytype"); + if($type == 'Call') + $image_tag = " ".$app_strings['Call']; + else if($type == 'Meeting') + $image_tag = " ".$app_strings['Meeting']; + else + $image_tag = " ".getTranslatedString($type); + $element['eventtype'] = $image_tag; + $element['eventdetail'] = $contact_data." ".$subject." ".$more_link; + /*if(getFieldVisibilityPermission('Events',$current_user->id,'parent_id') == '0') + { + $element['relatedto']= getRelatedTo('Calendar',$result,$i); + }*/ + if($idShared == "normal") + { + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete")=="yes") + $element['action'] ="date_time->hour."\",\"".$calendar['calendar']->date_time->get_formatted_date()."\",\"event\");' src='" . vtiger_imageurl('cal_event.jpg', $theme). "' border='0'>"; + } + else + { + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete")=="yes") + $element['action']=""; + } + if(getFieldVisibilityPermission('Events',$current_user->id,'eventstatus') == '0') + { + if(!$is_admin && $eventstatus != '') + { + $roleid=$current_user->roleid; + $roleids = Array(); + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + $roleids = $subrole; + array_push($roleids, $roleid); + + //here we are checking wheather the table contains the sortorder column .If sortorder is present in the main picklist table, then the role2picklist will be applicable for this table... + + $sql="select * from vtiger_eventstatus where eventstatus=?"; + $res = $adb->pquery($sql,array(decode_html($eventstatus))); + $picklistvalueid = $adb->query_result($res,0,'picklist_valueid'); + if ($picklistvalueid != null) { + $pick_query="select * from vtiger_role2picklist where picklistvalueid=$picklistvalueid and roleid in (". generateQuestionMarks($roleids) .")"; + $res_val=$adb->pquery($pick_query,array($roleids)); + $num_val = $adb->num_rows($res_val); + } + if($num_val > 0) + $element['status'] = getTranslatedString(decode_html($eventstatus)); + else + $element['status'] = "".$app_strings['LBL_NOT_ACCESSIBLE'].""; + + + }else + $element['status'] = getTranslatedString(decode_html($eventstatus)); + } + if(!empty($assignedto)) + $element['assignedto'] = $assignedto; + else + $element['assignedto'] = $adb->query_result($result,$i,"groupname"); + $element['visibility'] = $adb->query_result($result,$i,"visibility"); + $c++; + $Entries[] = $element; + } + $ret_arr[0] = $Entries; + $ret_arr[1] = $navigation_array; + $cal_log->debug("Exiting getEventList() method..."); + return $ret_arr; +} + +/** + * Function to get todos list scheduled between specified dates + * @param array $calendar - collection of objects and strings + * @param string $start_date - date string + * @param string $end_date - date string + * @param string $info - string 'listcnt' or empty string. if 'listcnt' means it returns no. of todos and no. of pending todos in array format else it returns todos list in array format + * return array $Entries - todolists in array format + */ +function getTodoList(& $calendar,$start_date,$end_date,$info='') +{ + global $log,$app_strings,$theme; + $Entries = Array(); + $category = getParentTab(); + global $adb,$current_user,$mod_strings,$cal_log,$list_max_entries_per_page; + $cal_log->debug("Entering getTodoList() method..."); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $count_qry = "SELECT count(*) as count FROM vtiger_activity + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_activity.activityid + LEFT JOIN vtiger_cntactivityrel + ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted = 0 + AND vtiger_activity.activitytype = 'Task' + AND (vtiger_activity.date_start BETWEEN ? AND ?) AND vtiger_crmentity.smownerid = " . $current_user->id; + + $query = "SELECT vtiger_groups.groupname, vtiger_users.user_name, vtiger_crmentity.crmid, vtiger_cntactivityrel.contactid, + vtiger_activity.* FROM vtiger_activity + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_activity.activityid + LEFT JOIN vtiger_cntactivityrel + ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted = 0 + AND vtiger_activity.activitytype = 'Task' + AND (vtiger_activity.date_start BETWEEN ? AND ?) AND vtiger_crmentity.smownerid = " . $current_user->id; + + $list_query = $query; + + // User Select Customization + /*$only_for_user = calendarview_getSelectedUserId(); + if($only_for_user != 'ALL') { + $query .= " AND vtiger_crmentity.smownerid = " . $only_for_user; + $count_qry .= " AND vtiger_crmentity.smownerid = " . $only_for_user; + }*/ + // END + $params = $info_params = array($start_date, $end_date); + if($info != '') + { + //added to fix #4816 + $groupids = explode(",", fetchUserGroupids($current_user->id)); + if (count($groupids) > 0) { + $com_q = " AND (vtiger_crmentity.smownerid = ? + OR vtiger_groups.groupid in (". generateQuestionMarks($groupids) ."))"; + } else { + $com_q = " AND vtiger_crmentity.smownerid = ?"; + } + //end + + $pending_query = $query." AND (vtiger_activity.status != 'Completed')".$com_q; + $total_q = $query."".$com_q; + array_push($info_params, $current_user->id); + + if (count($groupids) > 0) { + array_push($info_params, $groupids); + } + + if( $adb->dbType == "pgsql") + { + $pending_query = fixPostgresQuery( $pending_query, $log, 0); + $total_q = fixPostgresQuery( $total_q, $log, 0); + } + $total_res = $adb->pquery($total_q, $info_params); + $total = $adb->num_rows($total_res); + + $res = $adb->pquery($pending_query, $info_params); + $pending_rows = $adb->num_rows($res); + + $cal_log->debug("Exiting getTodoList() method..."); + return Array('totaltodo'=>$total,'pendingtodo'=>$pending_rows); + } + + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[9] == 3) + { + $sec_parameter=getListViewSecurityParameter('Calendar'); + $query .= $sec_parameter; + $list_query .= $sec_parameter; + $count_qry .= $sec_parameter; + } + $group_cond = ''; + $count_res = $adb->pquery($count_qry, $params); + $total_rec_count = $adb->query_result($count_res,0,'count'); + $group_cond .= " ORDER BY vtiger_activity.date_start,vtiger_activity.time_start ASC"; + if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') + $start = vtlib_purify($_REQUEST['start']); + else + $start = 1; + $navigation_array = getNavigationValues($start, $total_rec_count, $list_max_entries_per_page); + + $start_rec = $navigation_array['start']; + $end_rec = $navigation_array['end_val']; + if($start_rec <= 1) + $start_rec = 0; + else + $start_rec = $start_rec-1; + $query .= $group_cond." limit $start_rec,$list_max_entries_per_page"; + $list_query .= $group_cond; + + if( $adb->dbType == "pgsql"){ + $query = fixPostgresQuery( $query, $log, 0); + $list_query = fixPostgresQuery( $list_query, $log, 0); + } + + $list_query = $adb->convert2Sql($list_query, $params); + $_SESSION['Calendar_listquery'] = $list_query; + + $result = $adb->pquery($query, $params); + $rows = $adb->num_rows($result); + $c=0; + if($start > 1) + $c = ($start-1) * $list_max_entries_per_page; + for($i=0;$i<$rows;$i++) + { + + $element = Array(); + $contact_name = ''; + $element['no'] = $c+1; + $more_link = ""; + $start_time = $adb->query_result($result,$i,"time_start"); + $format = $calendar['calendar']->hour_format; + $value = getaddEventPopupTime($start_time,$start_time,$format); + $element['starttime'] = $value['starthour'].':'.$value['startmin'].''.$value['startfmt']; + $date_start = $adb->query_result($result,$i,"date_start"); + $due_date = $adb->query_result($result,$i,"due_date"); + if($calendar['view'] != 'day') + $element['startdate'] = getDisplayDate($date_start); + $element['duedate'] = getDisplayDate($due_date); + + $id = $adb->query_result($result,$i,"activityid"); + $subject = $adb->query_result($result,$i,"subject"); + //CHANGE : TO IMPROVE PERFORMANCE + /*$contact_id = $adb->query_result($result,$i,"contactid"); + if($contact_id!='') + { + $contact_name = getContactName($contact_id); + }*/ + + $more_link = "".$subject.""; + $element['tododetail'] = $more_link; + /*if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id') == '0') + { + $element['task_relatedto'] = getRelatedTo('Calendar',$result,$i); + } + if(getFieldVisibilityPermission('Calendar',$current_user->id,'contact_id') == '0') + { + $element['task_contact'] = "".$contact_name.""; + }*/ + if(getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0') + { + $taskstatus = $adb->query_result($result,$i,"status"); + + if(!$is_admin && $taskstatus != '') + { + $roleid=$current_user->roleid; + $roleids = Array(); + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + $roleids = $subrole; + array_push($roleids, $roleid); + + //here we are checking wheather the table contains the sortorder column .If sortorder is present in the main picklist table, then the role2picklist will be applicable for this table... + + $sql="select * from vtiger_taskstatus where taskstatus=?"; + $res = $adb->pquery($sql,array(decode_html($taskstatus))); + $picklistvalueid = $adb->query_result($res,0,'picklist_valueid'); + if ($picklistvalueid != null) { + $pick_query="select * from vtiger_role2picklist where picklistvalueid=$picklistvalueid and roleid in (". generateQuestionMarks($roleids) .")"; + $res_val=$adb->pquery($pick_query,array($roleids)); + $num_val = $adb->num_rows($res_val); + } + if($num_val > 0) + $element['status'] = getTranslatedString(decode_html($taskstatus)); + else + $element['status'] = "".$app_strings['LBL_NOT_ACCESSIBLE'].""; + + + }else + $element['status'] = getTranslatedString(decode_html($taskstatus)); + + + } + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete") == "yes") + $element['action'] ="date_time->hour."\",\"".$calendar['calendar']->date_time->get_formatted_date()."\",\"todo\");' src='" . vtiger_imageurl('cal_event.jpg', $theme). "' border='0'>"; + $assignedto = $adb->query_result($result,$i,"user_name"); + if(!empty($assignedto)) + $element['assignedto'] = $assignedto; + else + $element['assignedto'] = $adb->query_result($result,$i,"groupname"); + $c++; + $Entries[] = $element; + } + $ret_arr[0] = $Entries; + $ret_arr[1] = $navigation_array; + $cal_log->debug("Exiting getTodoList() method..."); + return $ret_arr; +} + +/** + * Function to get number of Events and Todos Info + * @param array $cal - collection of objects and strings + * @param string $mode - string 'listcnt' or may be empty. if empty means get Events/Todos ListView else get total events/todos and no. of pending events/todos Info. + * return array $event_todo_info - collection of events/todos info. + */ +function getEventInfo(& $cal, $mode) +{ + global $mod_strings,$cal_log; + $cal_log->debug("Entering getEventInfo() method..."); + $event = Array(); + $event['event']=getEventListView($cal, $mode); + $event_info = ""; + $event_info .= $mod_strings['LBL_TOTALEVENTS']." ".$event['event']['totalevent']; + if($event['event']['pendingevent'] != null) + $event_info .= ", ".$event['event']['pendingevent']." ".$mod_strings['LBL_PENDING']; + $cal_log->debug("Exiting getEventInfo() method..."); + + return $event_info; +} + +function getTodoInfo(& $cal, $mode) +{ + global $mod_strings,$cal_log; + $cal_log->debug("Entering getTodoInfo() method..."); + $todo = Array(); + $todo['todo'] = getTodosListView($cal, $mode); + $todo_info = ""; + $todo_info .=$mod_strings['LBL_TOTALTODOS']." ".$todo['todo']['totaltodo']; + if($todo['todo']['pendingtodo'] != null) + $todo_info .= ", ".$todo['todo']['pendingtodo']." ".$mod_strings['LBL_PENDING']; + $cal_log->debug("Exiting getTodoInfo() method..."); + + return $todo_info; +} + + +/** + * Function creates HTML to display Events ListView + * @param array $entry_list - collection of strings(Event Information) + * return string $list_view - html tags in string format + */ +function constructEventListView(& $cal,$entry_list,$navigation_array='') +{ + global $mod_strings,$app_strings,$adb,$cal_log,$current_user,$theme; + $cal_log->debug("Entering constructEventListView() method..."); + $format = $cal['calendar']->hour_format; + $date_format = $current_user->date_format; + $hour_startat = timeString(array('hour'=>date('H:i'),'minute'=>0),'24'); + $hour_endat = timeString(array('hour'=>date('H:i',(time() + (60 * 60))),'minute'=>0),'24'); + $time_arr = getaddEventPopupTime($hour_startat,$hour_endat,$format); + $temp_ts = $cal['calendar']->date_time->ts; + //to get date in user selected date format + $temp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$temp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$temp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $temp_ts)):('')))); + if($cal['calendar']->day_start_hour != 23) + $endtemp_date = $temp_date; + else + { + $endtemp_ts = $temp_ts + (1 * 24 * 60 * 60); + $endtemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$endtemp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$endtemp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $endtemp_ts)):('')))); + } + $list_view = ""; + $start_datetime = $app_strings['LBL_START_DATE_TIME']; + $end_datetime = $app_strings['LBL_END_DATE_TIME']; + //Events listview header labels + $header = Array('0'=>'#', + '1'=>$start_datetime, + '2'=>$end_datetime, + '3'=>$mod_strings['LBL_EVENTTYPE'], + '4'=>$mod_strings['LBL_EVENTDETAILS'] + ); + $header_width = Array('0'=>'5%', + '1'=>'15%', + '2'=>'15%', + '3'=>'10%', + '4'=>'33%' + ); + /*if(getFieldVisibilityPermission('Events',$current_user->id,'parent_id') == '0') + { + array_push($header,$mod_strings['LBL_RELATEDTO']); + array_push($header_width,'15%'); + }*/ + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete") == "yes") + { + array_push($header,$mod_strings['LBL_ACTION']); + array_push($header_width,'10%'); + } + if(getFieldVisibilityPermission('Events',$current_user->id,'eventstatus') == '0') + { + array_push($header,$mod_strings['LBL_STATUS']); + array_push($header_width,'$10%'); + } + array_push($header,$mod_strings['LBL_ASSINGEDTO']); + array_push($header_width,'15%'); + + $list_view .=" + "; + $header_rows = count($header); + $navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Calendar","index"); + if($navigationOutput != '') + { + $list_view .= ""; + } + $list_view .= ""; + for($i=0;$i<$header_rows;$i++) + { + $list_view .=""; + } + $list_view .=""; + $rows = count($entry_list); + if($rows != 0) + { + for($i=0;$i"; + + foreach($entry_list[$i] as $key=>$entry) + { + $assigned_role_query=$adb->pquery("select vtiger_user2role.roleid,vtiger_user2role.userid from vtiger_user2role INNER JOIN vtiger_users where vtiger_users.id=vtiger_user2role.userid and vtiger_users.user_name=?",array($entry_list[$i]['assignedto'])); + $assigned_user_role_id = $adb->query_result($assigned_role_query,0,"roleid"); + $assigned_user_id = $adb->query_result($assigned_role_query,0,"userid"); + $role_list = $adb->pquery("SELECT * from vtiger_role WHERE parentrole LIKE '". formatForSqlLike($current_user->column_fields['roleid']) . formatForSqlLike($assigned_user_role_id) ."'",array()); + $is_shared = $adb->pquery("SELECT * from vtiger_sharedcalendar where userid=? and sharedid=?",array($assigned_user_id,$current_user->id)); + if($key!='visibility'){ + if(($key=='eventdetail'|| $key=='action') && ($current_user->column_fields['is_admin']!='on' && $adb->num_rows($role_list)==0 && (($adb->num_rows($is_shared)==0 && ($entry_list[$i]['visibility']=='Public' || $entry_list[$i]['visibility']=='Private')) || $entry_list[$i]['visibility']=='Private')) && $current_user->column_fields['user_name']!=$entry_list[$i]['assignedto']){ + if($key=='eventdetail') + $list_view .=""; + else + $list_view .=""; + }else + $list_view .=""; + } + } + $list_view .=""; + } + } + else + { + $list_view .=""; + } + $list_view .="
"; + $list_view .= "".$navigationOutput."
".$header[$i]."
".$entry_list[$i]['assignedto']." - ".$mod_strings['LBL_BUSY']."".$app_strings['LBL_NOT_ACCESSIBLE']."$entry
+ "; + $list_view .="
+ + + + + + "; + //checking permission for Create/Edit Operation + if(isPermitted("Calendar","EditView") == "yes") + { + $list_view .=""; + } + else + { + $list_view .=""; + } + $list_view .=" +
+ ".$app_strings['LBL_NO']." ".$app_strings['Events']." ".$app_strings['LBL_FOUND']." !
".$app_strings['LBL_YOU_CAN_CREATE']." ".$app_strings['LBL_AN']." ".$app_strings['Event']." ".$app_strings['LBL_NOW'].".
+   -".$app_strings['LBL_CREATE']." ".$app_strings['LBL_AN']." ".$app_strings['Event']."
+
".$app_strings['LBL_YOU_ARE_NOT_ALLOWED_TO_CREATE']." ".$app_strings['LBL_AN']." ".$app_strings['Event']."
+
"; + $list_view .="
"; + $cal_log->debug("Exiting constructEventListView() method..."); + return $list_view; +} + +/** + * Function creates HTML to display Todos ListView + * @param array $todo_list - collection of strings(Todo Information) + * @param array $cal - collection of objects and strings + * return string $list_view - html tags in string format + */ +function constructTodoListView($todo_list,$cal,$subtab,$navigation_array='') +{ + global $mod_strings,$cal_log,$adb,$theme; + $cal_log->debug("Entering constructTodoListView() method..."); + global $current_user,$app_strings; + $date_format = $current_user->date_format; + $format = $cal['calendar']->hour_format; + $hour_startat = timeString(array('hour'=>date('H:i'),'minute'=>0),'24'); + $hour_endat = timeString(array('hour'=>date('H:i',(time() + (60 * 60))),'minute'=>0),'24'); + $time_arr = getaddEventPopupTime($hour_startat,$hour_endat,$format); + $temp_ts = $cal['calendar']->date_time->ts; + //to get date in user selected date format + $temp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$temp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$temp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $temp_ts)):('')))); + if($cal['calendar']->day_start_hour != 23) + $endtemp_date = $temp_date; + else + { + $endtemp_ts = $temp_ts + (1 * 24 * 60 * 60); + $endtemp_date = (($date_format == 'dd-mm-yyyy')?(date('d-m-Y',$endtemp_ts)):(($date_format== 'mm-dd-yyyy')?(date('m-d-Y',$endtemp_ts)):(($date_format == 'yyyy-mm-dd')?(date('Y-m-d', $endtemp_ts)):('')))); + } + $list_view = ""; + //labels of listview header + if($cal['view'] == 'day') + { + $colspan = 9; + $header = Array('0'=>'#','1'=>$mod_strings['LBL_TIME'],'2'=>$mod_strings['LBL_LIST_DUE_DATE'], + '3'=>$mod_strings['LBL_TODO']); + $header_width = Array('0'=>'5%','1'=>'10%','2'=>'10%','3'=>'38%',); + /*if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id') == '0') + { + array_push($header,$mod_strings['LBL_RELATEDTO']); + array_push($header_width,'15%'); + } + if(getFieldVisibilityPermission('Calendar',$current_user->id,'contact_id') == '0') + { + array_push($header,$mod_strings['LBL_CONTACT_NAME']); + array_push($header_width,'15%'); + }*/ + if(getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0') + { + array_push($header,$mod_strings['LBL_STATUS']); + array_push($header_width,'10%'); + } + + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete") == "yes") + { + array_push($header,$mod_strings['LBL_ACTION']); + array_push($header_width,'10%'); + } + array_push($header,$mod_strings['LBL_ASSINGEDTO']); + array_push($header_width,'15%'); + } + else + { + $colspan = 10; + $header = Array('0'=>'#', + '1'=>$mod_strings['LBL_TIME'], + '2'=>$mod_strings['LBL_START_DATE'], + '3'=>$mod_strings['LBL_DUE_DATE'], + '4'=>$mod_strings['LBL_TODO'] + ); + $header_width = Array('0'=>'5%', + '1'=>'10%', + '2'=>'10%', + '3'=>'10%', + '4'=>'28%' + ); + /*if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id') == '0') + { + array_push($header,$mod_strings['LBL_RELATEDTO']); + array_push($header_width,'15%'); + } + if(getFieldVisibilityPermission('Calendar',$current_user->id,'contact_id') == '0') + { + array_push($header,$mod_strings['LBL_CONTACT_NAME']); + array_push($header_width,'15%'); + }*/ + if(getFieldVisibilityPermission('Calendar',$current_user->id,'taskstatus') == '0') + { + array_push($header,$mod_strings['LBL_STATUS']); + array_push($header_width,'10%'); + } + if(isPermitted("Calendar","EditView") == "yes" || isPermitted("Calendar","Delete") == "yes") + { + array_push($header,$mod_strings['LBL_ACTION']); + } + array_push($header,$mod_strings['LBL_ASSINGEDTO']); + array_push($header_width,'15%'); + + } + if($current_user->column_fields['is_admin']=='on') + $Res = $adb->pquery("select * from vtiger_activitytype",array()); + else + { + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + + if (count($roleids) > 1) { + $Res=$adb->pquery("select distinct activitytype from vtiger_activitytype inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_activitytype.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_activitytype) order by sortid asc",array($roleids)); + } else { + $Res=$adb->pquery("select distinct activitytype from vtiger_activitytype inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_activitytype.picklist_valueid where roleid = ? and picklistid in (select picklistid from vtiger_activitytype) order by sortid asc",array($roleid)); + } + } + $eventlist=''; + for($i=0; $i<$adb->num_rows($Res);$i++) + { + $eventlist .= $adb->query_result($Res,$i,'activitytype').";"; + } + + $list_view .=" + "; + //checking permission for Create/Edit Operation + if(isPermitted("Calendar","EditView") == "yes") + { + $list_view .=" + "; + } + else + { + $list_view .=""; + } + $list_view .=" + + +
 
+ ".$mod_strings['LBL_ADD']." +
 ".getTodoInfo($cal,'listcnt')."  
+ +
+ "; + $header_rows = count($header); + $navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Calendar","index"); + if($navigationOutput != '') + { + $list_view .= ""; + } + $list_view .= ""; + for($i=0;$i<$header_rows;$i++) + { + $list_view .=""; + } + $list_view .=""; + $rows = count($todo_list); + if($rows != 0) + { + for($i=0;$i$entry) + { + $list_view .=""; + } + $list_view .=""; + } + } + else + { + $list_view .=""; + } + $list_view .="
"; + $list_view .= "".$navigationOutput."
".$header[$i]."
".$entry."
"; + $list_view .="
+ + + + + + "; + //checking permission for Create/Edit Operation + if(isPermitted("Calendar","EditView") == "yes") + { + $list_view .=""; + } + else + { + $list_view .=""; + } + + $list_view .=" +
+ ".$app_strings['LBL_NO']." ".$app_strings['Todos']." ".$app_strings['LBL_FOUND']." !
".$app_strings['LBL_YOU_CAN_CREATE']." ".$app_strings['LBL_A']." ".$app_strings['Todo']." ".$app_strings['LBL_NOW'].". ".$app_strings['LBL_CLICK_THE_LINK']." :
+   -".$app_strings['LBL_CREATE']." ".$app_strings['LBL_A']." ".$app_strings['Todo']." +
".$app_strings['LBL_YOU_ARE_NOT_ALLOWED_TO_CREATE']." ".$app_strings['LBL_A']." ".$app_strings['Todo']."
+
"; + $list_view .="

"; + $cal_log->debug("Exiting constructTodoListView() method..."); + return $list_view; +} + +/** + * Function returns the list of privileges and permissions of the events that the current user can view the details of. + * return string - query that is used as secondary parameter to fetch the events that the user can view and the schedule of the users + */ +function getCalendarViewSecurityParameter() +{ + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + require_once('modules/Calendar/CalendarCommon.php'); + $shared_ids = getSharedCalendarId($current_user->id); + if(isset($shared_ids) && $shared_ids != '') + $condition = " or (vtiger_crmentity.smownerid in($shared_ids)) or (vtiger_crmentity.smownerid NOT LIKE ($current_user->id))";// and vtiger_activity.visibility = 'Public')"; + else + $condition = "or (vtiger_crmentity.smownerid NOT LIKE ($current_user->id))"; + $sec_query .= " and (vtiger_crmentity.smownerid in($current_user->id) $condition 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."::%')"; + + if(sizeof($current_user_groups) > 0) + { + $sec_query .= " or (vtiger_groups.groupid in (". implode(",", $current_user_groups) ."))"; + } + $sec_query .= ")"; + return $sec_query; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/calendar_share.php b/oss/vtiger/trunk/modules/Calendar/calendar_share.php new file mode 100644 index 00000000..f6cc7d37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/calendar_share.php @@ -0,0 +1,169 @@ +id); + $shareduser_ids = getSharedUserId($current_user->id); +?> + + + + + +
+ +
+
+ + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+
+ start_hour != ''){?> checked onClick="enableCalstarttime();">  +
+ hour_format == '24'){?> checked value="24">  +
+
+

+ +
+ + + + +
+ + + + + + + + + + + + + +
+
    +
  • +
  • +
+
 
+ + + +
+ +
+ + + + + +
+ + +
+ +
+
+
+ + + + +
+    + +
+
+ diff --git a/oss/vtiger/trunk/modules/Calendar/disable_sharing.php b/oss/vtiger/trunk/modules/Calendar/disable_sharing.php new file mode 100644 index 00000000..6b73acb2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/disable_sharing.php @@ -0,0 +1,22 @@ +pquery($sql, array($id)); +} +header("Location:index.php?module=".$returnmodule."&action=".$returnaction); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/header.php b/oss/vtiger/trunk/modules/Calendar/header.php new file mode 100644 index 00000000..dbe3e5e2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/header.php @@ -0,0 +1,120 @@ + + + + + '.$app_strings[$category].' > '.$app_strings["Calendar"].' + + + + + + + +
+ + + + + +
+
+ +   + + + + + '; + + + if($CALENDAR_DISPLAY == 'true') + $html_string .= ' '; + if($WORLD_CLOCK_DISPLAY == 'true') + $html_string .= ' '; + if($CALCULATOR_DISPLAY == 'true') + $html_string .= ' '; + if($CHAT_DISPLAY == 'true') + $html_string .= ' '; + + $html_string .= ' + + +
'.$app_strings['LBL_CALENDAR_ALT'].''.$app_strings['LBL_CLOCK_ALT'].''.$app_strings['LBL_CALCULATOR_ALT'].''.$app_strings['LBL_CHAT_ALT'].''.$app_strings['LBL_LAST_VIEWED'].'
+ +   + + + + + + + +
+ +   + + + + '; + if((isPermitted('Settings','index') == 'yes')) + $html_string .= ''; + $html_string .= ' +
'.$app_strings['LBL_ALL_MENU_ALT'].''.$app_strings['LBL_SETTINGS'].'
+ + + + + + + + + + + \ + \ + \ + \ + ', fieldName, fieldLabel, expression.replace("\n","
"), editLink, deleteLink); + $('#expressionlist').append(row); + $(format('#expressionlist_deletelink_%s', fieldName)).click(function(){ + if(confirm(strings.LBL_DELETE_EXPRESSION_CONFIRM)) { + $('#status').show(); + + jsonget('deleteexpressionjson', + {modulename:moduleName, fieldname:fieldName}, + function(result){ + $('#status').hide(); + + if(result.status=='success'){ + $(format('#expressionlistrow_%s', fieldName)).remove(); + }else{ + errorDialog(result.message); + } + } + ); + } + }); + $(format('#expressionlist_editlink_%s', fieldName)).click(function(){ + ep.edit(fieldName, expression); + }); + } + + format = fn.format; + var moduleName; + function editpopup(){ + function close(){ + $('#editpopup').css('display', 'none'); + $('#editpopup_expression').text(''); + } + + function show(module){ + $('#editpopup').css('display', 'block'); + center($('#editpopup')); + } + + function center(el){ + el.css({position: 'absolute'}); + el.width("650px"); + el.height("310px"); + placeAtCenter(el.get(0)); + } + + $('#editpopup_close').bind('click', close); + $('#editpopup_save').bind('click', function(){ + var expression = $('#editpopup_expression').attr('value'); + var fieldName = $('#editpopup_field').attr('value'); + var fieldLabel = getfieldlabel(fieldName); + var moduleName = $('#pick_module').attr('value'); + + if(expression == '') return false; + + VtigerJS_DialogBox.block(); + $.get('index.php', { + module:'FieldFormulas', + action:'FieldFormulasAjax', + file:'saveexpressionjson', ajax:'true', + modulename: moduleName, fieldname:fieldName, + expression:expression + }, + function(result){ + VtigerJS_DialogBox.unblock(); + try { + var parsed = JSON.parse(result); + if(parsed.status=='success'){ + $("#expressionlistrow_"+fieldName).remove(); + addFieldExpression(moduleName, fieldName, fieldLabel, expression); + close(); + }else{ + errorDialog('save failed because '+parsed.message); + } + } catch(error) { + alert(error); + } + }); + }); + + $('#editpopup_cancel').bind('click', close); + + $('#editpopup_fieldnames').bind('change', function(){ + var textarea = $('#editpopup_expression').get(0); + var value = $(this).attr('value'); + if(value != '') value += ' '; + //http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript + if (document.selection) { + textarea.focus(); + var sel = document.selection.createRange(); + sel.text = value; + textarea.focus(); + }else if (textarea.selectionStart || textarea.selectionStart == '0') { + var startPos = textarea.selectionStart; + var endPos = textarea.selectionEnd; + var scrollTop = textarea.scrollTop; + textarea.value = textarea.value.substring(0, startPos) + + value + + textarea.value.substring(endPos, + textarea.value.length); + textarea.focus(); + textarea.selectionStart = startPos + value.length; + textarea.selectionEnd = startPos + value.length; + textarea.scrollTop = scrollTop; + } else { + textarea.value += value; + textarea.focus(); + } + // Reset the selected option (to enable next selection) + this.value = ''; + + }); + + + jsonget('getfunctionsjson', + {modulename:moduleName}, + function(result){ + var functions = $('#editpopup_functions'); + $.each(result, function(label, template){ + functions.append(format('', template, label)); + }); + $('#editpopup_functions').bind('change', function(){ + var textarea = $('#editpopup_expression').get(0); + var value = $(this).attr('value'); + //http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript + if (document.selection) { + textarea.focus(); + var sel = document.selection.createRange(); + sel.text = value; + textarea.focus(); + }else if (textarea.selectionStart || textarea.selectionStart == '0') { + var startPos = textarea.selectionStart; + var endPos = textarea.selectionEnd; + var scrollTop = textarea.scrollTop; + textarea.value = textarea.value.substring(0, startPos) + + value + + textarea.value.substring(endPos, + textarea.value.length); + textarea.focus(); + textarea.selectionStart = startPos + value.length; + textarea.selectionEnd = startPos + value.length; + textarea.scrollTop = scrollTop; + }else { + textarea.value += value; + textarea.focus(); + } + // Reset the selected option (to enable next selection) + this.value = ''; + + }); + + } + ); + + + return { + create: show, + edit: function(field, expression){ + $("#editpopup_field").attr('value', field); + $("#editpopup_expression").attr('value', expression); + show(); + }, + close:close, + changeModule: function(moduleName, exprFields, moduleFields){ + var field = $('#editpopup_field'); + field.children().remove(); + $.each(exprFields, function(fieldName, fieldLabel){ + field.append(format('', fieldName, fieldLabel)); + }); + + var fieldNames = $('#editpopup_fieldnames'); + fieldNames.children().remove(); + fieldNames.append(format('', fieldName, fieldLabel)); + }); + } + }; + } + + $(document).ready( + function(){ + Drag.init(document.getElementById('editpopup_draghandle'), document.getElementById('editpopup')); + toExec(); + } + ); + + function toExec(){ + ep = editpopup(); + function setModule(moduleName){ + $.get('index.php', { + module:'FieldFormulas', + action:'FieldFormulasAjax', + file:'getfieldsjson', ajax:'true', + modulename:moduleName}, + function(result){ + var parsed = JSON.parse(result); + ep.changeModule($(this).attr("value"), parsed['exprFields'], parsed['moduleFields']); + + $('#new_field_expression_busyicon').hide(); + $('#new_field_expression').show(); + + if(parsed['exprFields'].length!=0){ + $('#new_field_expression').attr('disabled', false); + $('#new_field_expression').attr('class', 'crmButton create small'); + $('#new_field_expression').bind('click', function(){ + ep.create(); + }); + $('#status_message').html(''); + $('#status_message').hide(); + }else{ + $('#new_field_expression').hide(); + $('#status_message').show(); + $('#status_message').html(strings.NEED_TO_ADD_A + ' ' + strings.CUSTOM_FIELD +''); + } + + jsonget('getexpressionlistjson', + {modulename:moduleName}, + function(result){ + $('#expressionlist_busyicon').hide(); + + var exprFields = parsed['exprFields']; + $('.expressionlistrow').remove(); + $.each(result, function(fieldName, expression){ + var fieldLabel = getfieldlabel(fieldName); + if(exprFields[fieldName]){ + addFieldExpression(moduleName, fieldName, fieldLabel, expression); + }else{ + jsonget('deleteexpressionjson', + {modulename:moduleName, fieldname:fieldName}, + function(){}); + } + + }); + } + ); + }); + ep.close(); + + + } + + $('#pick_module').bind('change', function(){ + var moduleName = $(this).attr("value"); + setModule(moduleName); + }); + setModule($('#pick_module').attr('value')); + + + + }; +} +editexpressionscript(jQuery); diff --git a/oss/vtiger/trunk/modules/FieldFormulas/resources/functional.js b/oss/vtiger/trunk/modules/FieldFormulas/resources/functional.js new file mode 100644 index 00000000..70579941 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/resources/functional.js @@ -0,0 +1,142 @@ +/*+******************************************************************************* + * 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. + ******************************************************************************/ +function functional(){} + +functional.prototype = { + + /** + * Test: + * fn.format("Hello %s", "world") == "Hello world" + */ + format: function(){ + var i=1; + var fmtStr = arguments[0]; + var args = arguments; + return fmtStr.replace(/%s/g,function(){return args[i++];}) + }, + + + + + + addStylesheet: function(url){ + /*From: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS*/ + var headID = document.getElementsByTagName("head")[0]; + var cssNode = document.createElement('link'); + cssNode.type = 'text/css'; + cssNode.rel = 'stylesheet'; + cssNode.href = url; + cssNode.media = 'screen'; + headID.appendChild(cssNode); + }, + + /* + *Convert the last parameter into a list argument + */ + + + /** + * Internal function for handling function arguments + * + * Test: + * fn.args("a","b","*c")(function(args){return args;})(1,2,3,4)=={"a":1,"b":2,"c":[3,4]}; + */ + /* + args: function(){ + if(arguments[arguments.length-1][0]=="*"){ + args = arguments[0,-1]; + larg = arguments[arguments.length-1].slice(1); + }else{ + args = arguments; + larg = null; + } + return function(callable){ + return { + arr=new Object(); + for(var i =1;iarguments.length){ + nparams = arguments.length; + } + + var args = []; + for(var i=0;i)[^>]*$|^#(\w+)$/, + +// Is it a simple selector + isSimple = /^.[^:#\[\.]*$/, + +// Will speed up references to undefined, and allows munging its name. + undefined; + +jQuery.fn = jQuery.prototype = { + init: function( selector, context ) { + // Make sure that a selection was provided + selector = selector || document; + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this[0] = selector; + this.length = 1; + return this; + } + // Handle HTML strings + if ( typeof selector == "string" ) { + // Are we dealing with HTML string or an ID? + var match = quickExpr.exec( selector ); + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) + selector = jQuery.clean( [ match[1] ], context ); + + // HANDLE: $("#id") + else { + var elem = document.getElementById( match[3] ); + + // Make sure an element was located + if ( elem ){ + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id != match[3] ) + return jQuery().find( selector ); + + // Otherwise, we inject the element directly into the jQuery object + return jQuery( elem ); + } + selector = []; + } + + // HANDLE: $(expr, [context]) + // (which is just equivalent to: $(content).find(expr) + } else + return jQuery( context ).find( selector ); + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) + return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector ); + + return this.setArray(jQuery.makeArray(selector)); + }, + + // The current version of jQuery being used + jquery: "1.2.6", + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + // The number of elements contained in the matched element set + length: 0, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == undefined ? + + // Return a 'clean' array + jQuery.makeArray( this ) : + + // Return just the object + this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + // Build a new jQuery matched element set + var ret = jQuery( elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Force the current matched set of elements to become + // the specified array of elements (destroying the stack in the process) + // You should use pushStack() in order to do this, but maintain the stack + setArray: function( elems ) { + // Resetting the length to 0, then using the native Array push + // is a super-fast way to populate an object with array-like properties + this.length = 0; + Array.prototype.push.apply( this, elems ); + + return this; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + var ret = -1; + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem && elem.jquery ? elem[0] : elem + , this ); + }, + + attr: function( name, value, type ) { + var options = name; + + // Look for the case where we're accessing a style value + if ( name.constructor == String ) + if ( value === undefined ) + return this[0] && jQuery[ type || "attr" ]( this[0], name ); + + else { + options = {}; + options[ name ] = value; + } + + // Check to see if we're setting style values + return this.each(function(i){ + // Set all the styles + for ( name in options ) + jQuery.attr( + type ? + this.style : + this, + name, jQuery.prop( this, options[ name ], type, i, name ) + ); + }); + }, + + css: function( key, value ) { + // ignore negative width and height values + if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 ) + value = undefined; + return this.attr( key, value, "curCSS" ); + }, + + text: function( text ) { + if ( typeof text != "object" && text != null ) + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + + var ret = ""; + + jQuery.each( text || this, function(){ + jQuery.each( this.childNodes, function(){ + if ( this.nodeType != 8 ) + ret += this.nodeType != 1 ? + this.nodeValue : + jQuery.fn.text( [ this ] ); + }); + }); + + return ret; + }, + + wrapAll: function( html ) { + if ( this[0] ) + // The elements to wrap the target around + jQuery( html, this[0].ownerDocument ) + .clone() + .insertBefore( this[0] ) + .map(function(){ + var elem = this; + + while ( elem.firstChild ) + elem = elem.firstChild; + + return elem; + }) + .append(this); + + return this; + }, + + wrapInner: function( html ) { + return this.each(function(){ + jQuery( this ).contents().wrapAll( html ); + }); + }, + + wrap: function( html ) { + return this.each(function(){ + jQuery( this ).wrapAll( html ); + }); + }, + + append: function() { + return this.domManip(arguments, true, false, function(elem){ + if (this.nodeType == 1) + this.appendChild( elem ); + }); + }, + + prepend: function() { + return this.domManip(arguments, true, true, function(elem){ + if (this.nodeType == 1) + this.insertBefore( elem, this.firstChild ); + }); + }, + + before: function() { + return this.domManip(arguments, false, false, function(elem){ + this.parentNode.insertBefore( elem, this ); + }); + }, + + after: function() { + return this.domManip(arguments, false, true, function(elem){ + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + }, + + end: function() { + return this.prevObject || jQuery( [] ); + }, + + find: function( selector ) { + var elems = jQuery.map(this, function(elem){ + return jQuery.find( selector, elem ); + }); + + return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ? + jQuery.unique( elems ) : + elems ); + }, + + clone: function( events ) { + // Do the clone + var ret = this.map(function(){ + if ( jQuery.browser.msie && !jQuery.isXMLDoc(this) ) { + // IE copies events bound via attachEvent when + // using cloneNode. Calling detachEvent on the + // clone will also remove the events from the orignal + // In order to get around this, we use innerHTML. + // Unfortunately, this means some modifications to + // attributes in IE that are actually only stored + // as properties will not be copied (such as the + // the name attribute on an input). + var clone = this.cloneNode(true), + container = document.createElement("div"); + container.appendChild(clone); + return jQuery.clean([container.innerHTML])[0]; + } else + return this.cloneNode(true); + }); + + // Need to set the expando to null on the cloned set if it exists + // removeData doesn't work here, IE removes it from the original as well + // this is primarily for IE but the data expando shouldn't be copied over in any browser + var clone = ret.find("*").andSelf().each(function(){ + if ( this[ expando ] != undefined ) + this[ expando ] = null; + }); + + // Copy the events from the original to the clone + if ( events === true ) + this.find("*").andSelf().each(function(i){ + if (this.nodeType == 3) + return; + var events = jQuery.data( this, "events" ); + + for ( var type in events ) + for ( var handler in events[ type ] ) + jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data ); + }); + + // Return the cloned set + return ret; + }, + + filter: function( selector ) { + return this.pushStack( + jQuery.isFunction( selector ) && + jQuery.grep(this, function(elem, i){ + return selector.call( elem, i ); + }) || + + jQuery.multiFilter( selector, this ) ); + }, + + not: function( selector ) { + if ( selector.constructor == String ) + // test special case where just one selector is passed in + if ( isSimple.test( selector ) ) + return this.pushStack( jQuery.multiFilter( selector, this, true ) ); + else + selector = jQuery.multiFilter( selector, this ); + + var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType; + return this.filter(function() { + return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector; + }); + }, + + add: function( selector ) { + return this.pushStack( jQuery.unique( jQuery.merge( + this.get(), + typeof selector == 'string' ? + jQuery( selector ) : + jQuery.makeArray( selector ) + ))); + }, + + is: function( selector ) { + return !!selector && jQuery.multiFilter( selector, this ).length > 0; + }, + + hasClass: function( selector ) { + return this.is( "." + selector ); + }, + + val: function( value ) { + if ( value == undefined ) { + + if ( this.length ) { + var elem = this[0]; + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type == "select-one"; + + // Nothing was selected + if ( index < 0 ) + return null; + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + if ( option.selected ) { + // Get the specifc value for the option + value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value; + + // We don't need an array for one selects + if ( one ) + return value; + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + + // Everything else, we just grab the value + } else + return (this[0].value || "").replace(/\r/g, ""); + + } + + return undefined; + } + + if( value.constructor == Number ) + value += ''; + + return this.each(function(){ + if ( this.nodeType != 1 ) + return; + + if ( value.constructor == Array && /radio|checkbox/.test( this.type ) ) + this.checked = (jQuery.inArray(this.value, value) >= 0 || + jQuery.inArray(this.name, value) >= 0); + + else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(value); + + jQuery( "option", this ).each(function(){ + this.selected = (jQuery.inArray( this.value, values ) >= 0 || + jQuery.inArray( this.text, values ) >= 0); + }); + + if ( !values.length ) + this.selectedIndex = -1; + + } else + this.value = value; + }); + }, + + html: function( value ) { + return value == undefined ? + (this[0] ? + this[0].innerHTML : + null) : + this.empty().append( value ); + }, + + replaceWith: function( value ) { + return this.after( value ).remove(); + }, + + eq: function( i ) { + return this.slice( i, i + 1 ); + }, + + slice: function() { + return this.pushStack( Array.prototype.slice.apply( this, arguments ) ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function(elem, i){ + return callback.call( elem, i, elem ); + })); + }, + + andSelf: function() { + return this.add( this.prevObject ); + }, + + data: function( key, value ){ + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + if ( data === undefined && this.length ) + data = jQuery.data( this[0], key ); + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } else + return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){ + jQuery.data( this, key, value ); + }); + }, + + removeData: function( key ){ + return this.each(function(){ + jQuery.removeData( this, key ); + }); + }, + + domManip: function( args, table, reverse, callback ) { + var clone = this.length > 1, elems; + + return this.each(function(){ + if ( !elems ) { + elems = jQuery.clean( args, this.ownerDocument ); + + if ( reverse ) + elems.reverse(); + } + + var obj = this; + + if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) ) + obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") ); + + var scripts = jQuery( [] ); + + jQuery.each(elems, function(){ + var elem = clone ? + jQuery( this ).clone( true )[0] : + this; + + // execute all scripts after the elements have been injected + if ( jQuery.nodeName( elem, "script" ) ) + scripts = scripts.add( elem ); + else { + // Remove any inner scripts for later evaluation + if ( elem.nodeType == 1 ) + scripts = scripts.add( jQuery( "script", elem ).remove() ); + + // Inject the elements into the document + callback.call( obj, elem ); + } + }); + + scripts.each( evalScript ); + }); + } +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +function evalScript( i, elem ) { + if ( elem.src ) + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + + else + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + + if ( elem.parentNode ) + elem.parentNode.removeChild( elem ); +} + +function now(){ + return +new Date; +} + +jQuery.extend = jQuery.fn.extend = function() { + // copy reference to target object + var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options; + + // Handle a deep copy situation + if ( target.constructor == Boolean ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target != "object" && typeof target != "function" ) + target = {}; + + // extend jQuery itself if only one argument is passed + if ( length == i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) + // Extend the base object + for ( var name in options ) { + var src = target[ name ], copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) + continue; + + // Recurse if we're merging object values + if ( deep && copy && typeof copy == "object" && !copy.nodeType ) + target[ name ] = jQuery.extend( deep, + // Never move original objects, clone them + src || ( copy.length != null ? [ ] : { } ) + , copy ); + + // Don't bring in undefined values + else if ( copy !== undefined ) + target[ name ] = copy; + + } + + // Return the modified object + return target; +}; + +var expando = "jQuery" + now(), uuid = 0, windowData = {}, + // exclude the following css properties to add px + exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, + // cache defaultView + defaultView = document.defaultView || {}; + +jQuery.extend({ + noConflict: function( deep ) { + window.$ = _$; + + if ( deep ) + window.jQuery = _jQuery; + + return jQuery; + }, + + // See test/unit/core.js for details concerning this function. + isFunction: function( fn ) { + return !!fn && typeof fn != "string" && !fn.nodeName && + fn.constructor != Array && /^[\s[]?function/.test( fn + "" ); + }, + + // check if an element is in a (or is an) XML document + isXMLDoc: function( elem ) { + return elem.documentElement && !elem.body || + elem.tagName && elem.ownerDocument && !elem.ownerDocument.body; + }, + + // Evalulates a script in a global context + globalEval: function( data ) { + data = jQuery.trim( data ); + + if ( data ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + if ( jQuery.browser.msie ) + script.text = data; + else + script.appendChild( document.createTextNode( data ) ); + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); + }, + + cache: {}, + + data: function( elem, name, data ) { + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ]; + + // Compute a unique ID for the element + if ( !id ) + id = elem[ expando ] = ++uuid; + + // Only generate the data cache if we're + // trying to access or manipulate it + if ( name && !jQuery.cache[ id ] ) + jQuery.cache[ id ] = {}; + + // Prevent overriding the named cache with undefined values + if ( data !== undefined ) + jQuery.cache[ id ][ name ] = data; + + // Return the named cache data, or the ID for the element + return name ? + jQuery.cache[ id ][ name ] : + id; + }, + + removeData: function( elem, name ) { + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ]; + + // If we want to remove a specific section of the element's data + if ( name ) { + if ( jQuery.cache[ id ] ) { + // Remove the section of cache data + delete jQuery.cache[ id ][ name ]; + + // If we've removed all the data, remove the element's cache + name = ""; + + for ( name in jQuery.cache[ id ] ) + break; + + if ( !name ) + jQuery.removeData( elem ); + } + + // Otherwise, we want to remove all of the element's data + } else { + // Clean up the element expando + try { + delete elem[ expando ]; + } catch(e){ + // IE has trouble directly removing the expando + // but it's ok with using removeAttribute + if ( elem.removeAttribute ) + elem.removeAttribute( expando ); + } + + // Completely remove the data cache + delete jQuery.cache[ id ]; + } + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, length = object.length; + + if ( args ) { + if ( length == undefined ) { + for ( name in object ) + if ( callback.apply( object[ name ], args ) === false ) + break; + } else + for ( ; i < length; ) + if ( callback.apply( object[ i++ ], args ) === false ) + break; + + // A special, fast, case for the most common use of each + } else { + if ( length == undefined ) { + for ( name in object ) + if ( callback.call( object[ name ], name, object[ name ] ) === false ) + break; + } else + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} + } + + return object; + }, + + prop: function( elem, value, type, i, name ) { + // Handle executable functions + if ( jQuery.isFunction( value ) ) + value = value.call( elem, i ); + + // Handle passing in a number to a CSS property + return value && value.constructor == Number && type == "curCSS" && !exclude.test( name ) ? + value + "px" : + value; + }, + + className: { + // internal only, use addClass("class") + add: function( elem, classNames ) { + jQuery.each((classNames || "").split(/\s+/), function(i, className){ + if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) ) + elem.className += (elem.className ? " " : "") + className; + }); + }, + + // internal only, use removeClass("class") + remove: function( elem, classNames ) { + if (elem.nodeType == 1) + elem.className = classNames != undefined ? + jQuery.grep(elem.className.split(/\s+/), function(className){ + return !jQuery.className.has( classNames, className ); + }).join(" ") : + ""; + }, + + // internal only, use hasClass("class") + has: function( elem, className ) { + return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1; + } + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var old = {}; + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( var name in options ) + elem.style[ name ] = old[ name ]; + }, + + css: function( elem, name, force ) { + if ( name == "width" || name == "height" ) { + var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ]; + + function getWH() { + val = name == "width" ? elem.offsetWidth : elem.offsetHeight; + var padding = 0, border = 0; + jQuery.each( which, function() { + padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; + border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; + }); + val -= Math.round(padding + border); + } + + if ( jQuery(elem).is(":visible") ) + getWH(); + else + jQuery.swap( elem, props, getWH ); + + return Math.max(0, val); + } + + return jQuery.curCSS( elem, name, force ); + }, + + curCSS: function( elem, name, force ) { + var ret, style = elem.style; + + // A helper method for determining if an element's values are broken + function color( elem ) { + if ( !jQuery.browser.safari ) + return false; + + // defaultView is cached + var ret = defaultView.getComputedStyle( elem, null ); + return !ret || ret.getPropertyValue("color") == ""; + } + + // We need to handle opacity special in IE + if ( name == "opacity" && jQuery.browser.msie ) { + ret = jQuery.attr( style, "opacity" ); + + return ret == "" ? + "1" : + ret; + } + // Opera sometimes will give the wrong display answer, this fixes it, see #2037 + if ( jQuery.browser.opera && name == "display" ) { + var save = style.outline; + style.outline = "0 solid black"; + style.outline = save; + } + + // Make sure we're using the right name for getting the float value + if ( name.match( /float/i ) ) + name = styleFloat; + + if ( !force && style && style[ name ] ) + ret = style[ name ]; + + else if ( defaultView.getComputedStyle ) { + + // Only "float" is needed here + if ( name.match( /float/i ) ) + name = "float"; + + name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase(); + + var computedStyle = defaultView.getComputedStyle( elem, null ); + + if ( computedStyle && !color( elem ) ) + ret = computedStyle.getPropertyValue( name ); + + // If the element isn't reporting its values properly in Safari + // then some display: none elements are involved + else { + var swap = [], stack = [], a = elem, i = 0; + + // Locate all of the parent display: none elements + for ( ; a && color(a); a = a.parentNode ) + stack.unshift(a); + + // Go through and make them visible, but in reverse + // (It would be better if we knew the exact display type that they had) + for ( ; i < stack.length; i++ ) + if ( color( stack[ i ] ) ) { + swap[ i ] = stack[ i ].style.display; + stack[ i ].style.display = "block"; + } + + // Since we flip the display style, we have to handle that + // one special, otherwise get the value + ret = name == "display" && swap[ stack.length - 1 ] != null ? + "none" : + ( computedStyle && computedStyle.getPropertyValue( name ) ) || ""; + + // Finally, revert the display styles back + for ( i = 0; i < swap.length; i++ ) + if ( swap[ i ] != null ) + stack[ i ].style.display = swap[ i ]; + } + + // We should always get a number back from opacity + if ( name == "opacity" && ret == "" ) + ret = "1"; + + } else if ( elem.currentStyle ) { + var camelCase = name.replace(/\-(\w)/g, function(all, letter){ + return letter.toUpperCase(); + }); + + ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) { + // Remember the original values + var left = style.left, rsLeft = elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + elem.runtimeStyle.left = elem.currentStyle.left; + style.left = ret || 0; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + elem.runtimeStyle.left = rsLeft; + } + } + + return ret; + }, + + clean: function( elems, context ) { + var ret = []; + context = context || document; + // !context.createElement fails in IE with an error but returns typeof 'object' + if (typeof context.createElement == 'undefined') + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + + jQuery.each(elems, function(i, elem){ + if ( !elem ) + return; + + if ( elem.constructor == Number ) + elem += ''; + + // Convert html string into DOM nodes + if ( typeof elem == "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ + return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? + all : + front + ">"; + }); + + // Trim whitespace, otherwise indexOf won't work as expected + var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div"); + + var wrap = + // option or optgroup + !tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && + [ 1, "
+ + +
+ + + + + + + + + +
+ + + + + + + + +
 '.$app_strings["Calendar"].' '.$mod_strings["LBL_ALL_EVENTS_TODOS"].' 
+
+ + + "; +} +$sHTML .= ""; + + +return $sHTML; +} + +/** Returns graph, if the cached image is present it'll display that image, +otherwise it will render the graph with the given details +* Portions created by vtiger are Copyright (C) vtiger. +* All Rights Reserved. +* Contributor(s): ______________________________________.. +*/ + +// Function to get the chached image if exists +function render_graph($cache_file_name,$html_imagename,$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$graph_type) +{ + + //Checks whether the cached image is present or not + if(file_exists($cache_file_name)) + { + @unlink($cache_file_name); + } + if(file_exists($cache_file_name.'.map')) + { + @unlink($cache_file_name.'.map'); + } + if (!file_exists($cache_file_name) || !file_exists($cache_file_name.'.map')) + { + //If the Cached image is not present + if($graph_type=="horizontal") + { + return horizontal_graph($cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$cache_file_name,$html_imagename); + } + else if($graph_type=="vertical") + { + return vertical_graph($cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$cache_file_name,$html_imagename); + } + else if($graph_type=="pie") + { + return pie_chart($cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$cache_file_name,$html_imagename); + + } + } + else + { + //Getting the cached image + $imgMap_fp = fopen($cache_file_name.'.map', "rb"); + $imgMap = fread($imgMap_fp, filesize($cache_file_name.'.map')); + fclose($imgMap_fp); + $base_name_cache_file=basename($cache_file_name); + $ccc="cache/images/".$base_name_cache_file; + $return = "\n$imgMap\n"; + $return .= ""; + return $return; + } +} +function get_graph_homepg($cache_file_name,$html_imagename,$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$graph_date,$urlstring,$test_target_val,$date_start,$end_date) +{ + global $tmp_dir; + global $graph_title, $mod_strings; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $val=explode(":",$title); + $display_title=$val[0]; + $type = $_REQUEST[Chart_Type]; + if($type == 'horizontalbarchart') + $sHTML .= render_graph($tmp_dir."hor_".$cache_file_name,$html_imagename."_hor",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"horizontal"); + elseif($type == 'verticalbarchart') + $sHTML .= render_graph($tmp_dir."vert_".$cache_file_name,$html_imagename."_vert",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"vertical"); + elseif($type == 'piechart') + $sHTML .= render_graph($tmp_dir."pie_".$cache_file_name,$html_imagename."_pie",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"pie"); + return $sHTML; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Dashboard/Forms.php b/oss/vtiger/trunk/modules/Dashboard/Forms.php new file mode 100644 index 00000000..74089889 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Forms.php @@ -0,0 +1,166 @@ + + + + +EOQ; + +return $the_script; +} + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/HomepageDB.php b/oss/vtiger/trunk/modules/Dashboard/HomepageDB.php new file mode 100644 index 00000000..97fc4a95 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/HomepageDB.php @@ -0,0 +1,69 @@ +id.'.php'); + +global $current_user,$user_id,$date_start,$end_date,$tmp_dir,$mod_strings,$app_strings; +$type='recordsforuser'; + +// Performance Optimization: Using new API to generate dashboard chart +/* +$module_arr = Array ('Accounts','Contacts','Leads','Potentials','Quotes','Invoice','PurchaseOrder', 'SalesOrder','Calendar','HelpDesk','Campaigns'); +foreach ($module_arr as $key => $mod_name){ + if(isPermitted("$mod_name","index",'') == 'yes'){ + + $permitted_mod_list[$key] = $mod_name; + } +} + +if(is_array($permitted_mod_list)){ + $moduleList = implode("','",$permitted_mod_list); +} + +$homepagedb_query = "select * from vtiger_crmentity se left join vtiger_leaddetails le on le.leadid=se.crmid left join vtiger_troubletickets tt on tt.ticketid=se.crmid left join vtiger_activity act on act.activityid=se.crmid left join vtiger_potential pot on pot.potentialid=se.crmid where se.deleted=0 and (le.converted=0 or le.converted is null) and (pot.sales_stage not in('".$app_strings['LBL_CLOSE_WON']."','".$app_strings['LBL_CLOSE_LOST']."') or pot.sales_stage is null) and (tt.status!='Closed' or tt.status is null) and ((act.status!='Completed' and act.status!='Deferred') or act.status is null) and ((act.eventstatus!='Held' and act.eventstatus!='Not Held') or act.eventstatus is null) and setype in ('".$moduleList."') and se.deleted=0 and se.smownerid=".$current_user->id; +$graph_by="setype"; +$graph_title=$mod_strings['recordsforuser'].' '.$current_user->user_name; +$module="Home"; +$where=""; +$query=$homepagedb_query; + +//Giving the Cached image name +$cache_file_name=abs(crc32($current_user->id))."_".$type."_".crc32($date_start.$end_date).".png"; + $html_imagename=$graph_by; //Html image name for the graph +$graph_details=module_Chart($current_user->id,$date_start,$end_date,$query,$graph_by,$graph_title,$where,$module,$type); +*/ + +// Performance Optimization +$graph_details = module_Chart_HomePageDashboard($current_user); + +if (!empty($graph_details) && $graph_details[1] != 0) { // END + $name_val=$graph_details[0]; + $cnt_val=$graph_details[1]; + $graph_title=$graph_details[2]; + $target_val=$graph_details[3]; + $graph_date=$graph_details[4]; + $urlstring=$graph_details[5]; + $cnt_table=$graph_details[6]; + $test_target_val=$graph_details[7]; + + $width=560; + $height=225; + $top=30; + $left=140; + $bottom=120; + $title=$graph_title; + $sHTML = render_graph($tmp_dir."vert_".$cache_file_name,$html_imagename."_vert",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"vertical"); + echo $sHTML; +}else{ + echo $mod_strings['LBL_NO_DATA']; +} + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/ReportsCharts.php b/oss/vtiger/trunk/modules/Dashboard/ReportsCharts.php new file mode 100644 index 00000000..19de9172 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/ReportsCharts.php @@ -0,0 +1,194 @@ + + + + + + + + + "; + +$sHTML .= " + + + + + + + + "; + +$sHTML .= " + + + + + + + + "; + + return $sHTML; +} + +/** Returns graph, if the cached image is present it'll display that image, +otherwise it will render the graph with the given details +* Portions created by vtiger are Copyright (C) vtiger. +* All Rights Reserved. +* Contributor(s): ______________________________________.. +*/ + +// Function to get the chached image if exists +function render_graph($cache_file_name,$html_imagename,$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$graph_type) +{ + + //Checks whether the cached image is present or not + if(file_exists($cahce_file_name)) + { + unlink($cache_file_name); + } + if(file_exists($cache_file_name.'.map')) + { + unlink($cache_file_name.'.map'); + } + if (!file_exists($cache_file_name) || !file_exists($cache_file_name.'.map')) + { + //If the Cached image is not present + if($graph_type=="horizontal") + { + return horizontal_graph($cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$cache_file_name,$html_imagename); + } + else if($graph_type=="vertical") + { + return vertical_graph($cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$cache_file_name,$html_imagename); + } + else if($graph_type=="pie") + { + return pie_chart($cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$cache_file_name,$html_imagename); + + } + } + else + { + //Getting the cached image + $imgMap_fp = fopen($cache_file_name.'.map', "rb"); + $imgMap = fread($imgMap_fp, vtiger_filesize($cache_file_name.'.map')); + fclose($imgMap_fp); + $base_name_cache_file=basename($cache_file_name); + $ccc="cache/images/".$base_name_cache_file; + $return = "\n$imgMap\n"; + $return .= ""; + return $return; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Dashboard/accumulated_bargraph.php b/oss/vtiger/trunk/modules/Dashboard/accumulated_bargraph.php new file mode 100644 index 00000000..ad567efc --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/accumulated_bargraph.php @@ -0,0 +1,88 @@ +SetScale("textlin"); + +$graph->SetShadow(); + + +// Create the lines of the Graph +for($i=0;$iSetFillColor($color_array[$i]); + $bplot[$i]->SetWidth(10); + + $bplot[$i]->value->Show(); + $bplot[$i]->value->SetFont(FF_FONT1,FS_NORMAL,8); + $bplot[$i]->value->SetColor("black"); + $bplot[$i]->value->SetFormat('%d'); + $bplot[$i]->SetValuePos('max'); + +} + +$gbplot = new AccBarPlot($bplot); +$gbplot->SetWidth(0.7); + +// Add the bar to the graph +$graph->Add($gbplot); + +$graph->xaxis->SetTickLabels($datax); + +$graph->title->Set($title); + +$graph->Set90AndMargin($left,$right,$top,$bottom); +//$graph->SetFrame(false); +$graph->title->SetFont(FF_FONT1,FS_BOLD); +$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD); +$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD); + +$graph->SetColor("#7D9CB8"); +$graph->SetMarginColor("#3D6A93"); + +// Display the graph +$graph->Stroke(); + +?> + diff --git a/oss/vtiger/trunk/modules/Dashboard/display_charts.php b/oss/vtiger/trunk/modules/Dashboard/display_charts.php new file mode 100644 index 00000000..74f94aab --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/display_charts.php @@ -0,0 +1,829 @@ +id.'.php'); +global $current_language; +$mod_strings = return_module_language($current_language, 'Dashboard'); + + +$period=($_REQUEST['period'])?$_REQUEST['period']:"tmon"; // Period >> lmon- Last Month, tmon- This Month, lweek-LastWeek, tweek-ThisWeek; lday- Last Day +$type=($_REQUEST['type'])?$_REQUEST['type']:"leadsource"; +$dates_values=start_end_dates($period); //To get the stating and End dates for a given period +$date_start=$dates_values[0]; //Starting date +$end_date=$dates_values[1]; // Ending Date +$period_type=$dates_values[2]; //Period type as MONTH,WEEK,LDAY +$width=$dates_values[3]; +$height=$dates_values[4]; + +//It gives all the dates in between the starting and ending dates and also gives the number of days,declared in utils.php +$no_days_dates=get_days_n_dates($date_start,$end_date); +$days=$no_days_dates[0]; +$date_array=$no_days_dates[1]; //Array containig all the dates +$user_id=$current_user->id; + +// Query for Leads +$leads_query="select vtiger_crmentity.crmid,vtiger_crmentity.createdtime, vtiger_leaddetails.*, vtiger_crmentity.smownerid, vtiger_leadscf.* from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid inner join vtiger_leadsubdetails on vtiger_leadsubdetails.leadsubscriptionid=vtiger_leaddetails.leadid inner join vtiger_leadaddress on vtiger_leadaddress.leadaddressid=vtiger_leadsubdetails.leadsubscriptionid inner join vtiger_leadscf on vtiger_leaddetails.leadid = vtiger_leadscf.leadid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 and vtiger_leaddetails.converted=0 "; + + +//Query for Accounts +$account_query="select vtiger_crmentity.*, vtiger_account.*, vtiger_accountscf.* from vtiger_account inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid inner join vtiger_accountbillads on vtiger_account.accountid=vtiger_accountbillads.accountaddressid inner join vtiger_accountshipads on vtiger_account.accountid=vtiger_accountshipads.accountaddressid inner join vtiger_accountscf on vtiger_account.accountid = vtiger_accountscf.accountid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 "; + +//Query for Products by PO +$probyPO = "select vtiger_purchaseorder.*,vtiger_crmentity.* from vtiger_purchaseorder inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_purchaseorder.purchaseorderid inner join vtiger_inventoryproductrel on vtiger_purchaseorder.purchaseorderid = vtiger_inventoryproductrel.id LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid where vtiger_inventoryproductrel.id=vtiger_purchaseorder.purchaseorderid and vtiger_crmentity.deleted=0"; + +//Query for Products by Quotes +$probyQ = "select vtiger_quotes.*,vtiger_crmentity.* from vtiger_quotes inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_quotes.quoteid inner join vtiger_inventoryproductrel on vtiger_quotes.quoteid = vtiger_inventoryproductrel.id LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid where vtiger_inventoryproductrel.id=vtiger_quotes.quoteid and vtiger_crmentity.deleted=0"; + +//Query for Products by Invoices +$probyInv = "select vtiger_invoice.*,vtiger_crmentity.* from vtiger_invoice inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_invoice.invoiceid inner join vtiger_inventoryproductrel on vtiger_invoice.invoiceid = vtiger_inventoryproductrel.id LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid where vtiger_inventoryproductrel.id=vtiger_invoice.invoiceid and vtiger_crmentity.deleted=0"; + +//Query For Products qty in stock +$products_query="select distinct(vtiger_crmentity.crmid),vtiger_crmentity.createdtime,vtiger_products.* from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid left join vtiger_inventoryproductrel on vtiger_products.productid = vtiger_inventoryproductrel.id where vtiger_crmentity.deleted=0 and vtiger_products.qtyinstock > 0"; + +//Query for Potential +$potential_query= "select vtiger_crmentity.*,vtiger_account.accountname, vtiger_potential.*, vtiger_potentialscf.*, vtiger_groups.groupname from vtiger_potential inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_potential.potentialid left join vtiger_account on vtiger_potential.related_to = vtiger_account.accountid inner join vtiger_potentialscf on vtiger_potentialscf.potentialid = vtiger_potential.potentialid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 "; + +//Query for Sales Order +$so_query="select vtiger_crmentity.*,vtiger_salesorder.*,vtiger_account.accountid,vtiger_quotes.quoteid from vtiger_salesorder inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_salesorder.salesorderid inner join vtiger_sobillads on vtiger_salesorder.salesorderid=vtiger_sobillads.sobilladdressid inner join vtiger_soshipads on vtiger_salesorder.salesorderid=vtiger_soshipads.soshipaddressid left join vtiger_salesordercf on vtiger_salesordercf.salesorderid = vtiger_salesorder.salesorderid left outer join vtiger_quotes on vtiger_quotes.quoteid=vtiger_salesorder.quoteid left outer join vtiger_account on vtiger_account.accountid=vtiger_salesorder.accountid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 "; + + +//Query for Purchase Order + +$po_query="select vtiger_crmentity.*,vtiger_purchaseorder.* from vtiger_purchaseorder inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_purchaseorder.purchaseorderid left outer join vtiger_vendor on vtiger_purchaseorder.vendorid=vtiger_vendor.vendorid inner join vtiger_pobillads on vtiger_purchaseorder.purchaseorderid=vtiger_pobillads.pobilladdressid inner join vtiger_poshipads on vtiger_purchaseorder.purchaseorderid=vtiger_poshipads.poshipaddressid left join vtiger_purchaseordercf on vtiger_purchaseordercf.purchaseorderid = vtiger_purchaseorder.purchaseorderid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 "; + +// Query for Quotes +$quotes_query="select vtiger_crmentity.*,vtiger_quotes.* from vtiger_quotes inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_quotes.quoteid inner join vtiger_quotesbillads on vtiger_quotes.quoteid=vtiger_quotesbillads.quotebilladdressid inner join vtiger_quotesshipads on vtiger_quotes.quoteid=vtiger_quotesshipads.quoteshipaddressid left join vtiger_quotescf on vtiger_quotes.quoteid = vtiger_quotescf.quoteid left outer join vtiger_account on vtiger_account.accountid=vtiger_quotes.accountid left outer join vtiger_potential on vtiger_potential.potentialid=vtiger_quotes.potentialid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 "; + +//Query for Invoice +$invoice_query="select vtiger_crmentity.*,vtiger_invoice.* from vtiger_invoice inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_invoice.invoiceid inner join vtiger_invoicebillads on vtiger_invoice.invoiceid=vtiger_invoicebillads.invoicebilladdressid inner join vtiger_invoiceshipads on vtiger_invoice.invoiceid=vtiger_invoiceshipads.invoiceshipaddressid left outer join vtiger_salesorder on vtiger_salesorder.salesorderid=vtiger_invoice.salesorderid inner join vtiger_invoicecf on vtiger_invoice.invoiceid = vtiger_invoicecf.invoiceid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid where vtiger_crmentity.deleted=0 "; + +//Query for tickets +$helpdesk_query=" select vtiger_troubletickets.status AS ticketstatus, vtiger_groups.groupname AS ticketgroupname, vtiger_troubletickets.*,vtiger_crmentity.* from vtiger_troubletickets inner join vtiger_ticketcf on vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_contactdetails on vtiger_troubletickets.parent_id=vtiger_contactdetails.contactid left join vtiger_account on vtiger_account.accountid=vtiger_troubletickets.parent_id left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id and vtiger_troubletickets.ticketid = vtiger_ticketcf.ticketid where vtiger_crmentity.deleted=0"; + + +//Query for Contacts by Campaign +$cont_Q = "select crmid from vtiger_contactdetails inner join vtiger_campaigncontrel on vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id where vtiger_crmentity.deleted=0 ".dashboard_check("Contacts"); + +$result = $adb->pquery($cont_Q, array()); +$num_conts = $adb->num_rows($result); +$cont_Array = array(); +for($z=0;$z<$num_conts;$z++) +{ + $cont_ID=$adb->query_result($result,$z,'crmid'); + if(!in_array($cont_ID, $cont_Array)) + array_push($cont_Array, $cont_ID); +} +$cont_checkQ = " and vtiger_crmentityContacts.crmid in(0)"; +if(count($cont_Array) > 0) + $cont_checkQ = " and vtiger_crmentityContacts.crmid in(".implode(", ", $cont_Array).")"; + +$campaign_query="select vtiger_campaign.*,vtiger_crmentity.* from vtiger_campaign inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_campaign.campaignid inner join vtiger_campaigncontrel on vtiger_campaigncontrel.campaignid=vtiger_campaign.campaignid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id left join vtiger_contactdetails on vtiger_contactdetails.contactid = vtiger_campaigncontrel.contactid left join vtiger_crmentity as vtiger_crmentityContacts on vtiger_crmentityContacts.crmid = vtiger_contactdetails.contactid where vtiger_campaigncontrel.campaignid=vtiger_campaign.campaignid and vtiger_crmentity.deleted=0 and vtiger_crmentityContacts.deleted=0".$cont_checkQ; + + +//Query for tickets by account +$tickets_by_account="select vtiger_troubletickets.*, vtiger_groups.groupname AS ticketgroupname, vtiger_crmentity.*, vtiger_account.* from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid inner join vtiger_account on vtiger_account.accountid=vtiger_troubletickets.parent_id left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id where vtiger_crmentity.deleted=0"; + +//Query for tickets by contact +$tickets_by_contact="select vtiger_troubletickets.*, vtiger_groups.groupname AS ticketgroupname, vtiger_crmentity.*, vtiger_contactdetails.* from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid inner join vtiger_contactdetails on vtiger_contactdetails.contactid=vtiger_troubletickets.parent_id left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id where vtiger_crmentity.deleted=0"; + +//Query for product by category + +$product_category = "select vtiger_products.*,vtiger_crmentity.deleted from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_products.productid where vtiger_crmentity.deleted=0"; + +$graph_array = Array( + "DashboardHome" => $mod_strings['DashboardHome'], + "leadsource" => $mod_strings['leadsource'], + "leadstatus" => $mod_strings['leadstatus'], + "leadindustry" => $mod_strings['leadindustry'], + "salesbyleadsource" => $mod_strings['salesbyleadsource'], + "salesbyaccount" => $mod_strings['salesbyaccount'], + "salesbyuser" => $mod_strings['salesbyuser'], + "salesbyteam" => $mod_strings['salesbyteam'], + "accountindustry" => $mod_strings['accountindustry'], + "productcategory" => $mod_strings['productcategory'], + "productbyqtyinstock" => $mod_strings['productbyqtyinstock'], + "productbypo" => $mod_strings['productbypo'], + "productbyquotes" => $mod_strings['productbyquotes'], + "productbyinvoice" => $mod_strings['productbyinvoice'], + "sobyaccounts" => $mod_strings['sobyaccounts'], + "sobystatus" => $mod_strings['sobystatus'], + "pobystatus" => $mod_strings['pobystatus'], + "quotesbyaccounts" => $mod_strings['quotesbyaccounts'], + "quotesbystage" => $mod_strings['quotesbystage'], + "invoicebyacnts" => $mod_strings['invoicebyacnts'], + "invoicebystatus" => $mod_strings['invoicebystatus'], + "ticketsbystatus" => $mod_strings['ticketsbystatus'], + "ticketsbypriority" => $mod_strings['ticketsbypriority'], + "ticketsbycategory" => $mod_strings['ticketsbycategory'], + "ticketsbyuser" => $mod_strings['ticketsbyuser'], + "ticketsbyteam" => $mod_strings['ticketsbyteam'], + "ticketsbyproduct"=> $mod_strings['ticketsbyproduct'], + "contactbycampaign"=> $mod_strings['contactbycampaign'], + "ticketsbyaccount"=> $mod_strings['ticketsbyaccount'], + "ticketsbycontact"=> $mod_strings['ticketsbycontact'], + ); + if(isset($_REQUEST['from_page']) && $_REQUEST['from_page'] == 'HomePage') + { + + //Charts for Lead Source + if($profileTabsPermission[getTabid("Leads")] == 0 && ($type == "leadsource") && (getFieldVisibilityPermission('Leads',$user_id,'leadsource') == "0")) + { + $graph_by="leadsource"; + $graph_title= $mod_strings['leadsource']; + $module="Leads"; + $where=""; + $query=$leads_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + + } + // To display the charts for Lead status + elseif ($profileTabsPermission[getTabid("Leads")] == 0 && ($type == "leadstatus")&& (getFieldVisibilityPermission('Leads',$user_id,'leadstatus') == "0")) + { + $graph_by="leadstatus"; + $graph_title= $mod_strings['leadstatus']; + $module="Leads"; + $where=""; + $query=$leads_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_leaddetails.leadsource '.picklist_check($module,$graph_by); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Lead Industry + elseif ($profileTabsPermission[getTabid("Leads")] == 0 && ($type == "leadindustry") && (getFieldVisibilityPermission('Leads',$user_id,'industry') == "0")) + { + $graph_by="industry"; + $graph_title=$mod_strings['leadindustry']; + $module="Leads"; + $where=""; + $query=$leads_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Sales by Lead Source + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyleadsource")&& (getFieldVisibilityPermission('Potentials',$user_id,'leadsource') == "0")) + { + $graph_by="leadsource"; + $graph_title=$mod_strings['salesbyleadsource']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like '%Closed Won%' "; + $query=$potential_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Sales by Account + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyaccount") && (getFieldVisibilityPermission('Potentials',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['salesbyaccount']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like '%Closed Won%' "; + $query=$potential_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Sales by User + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyuser")) + { + $graph_by="smownerid"; + $graph_title=$mod_strings['salesbyuser']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like '%Closed Won%' and (vtiger_crmentity.smownerid != NULL || vtiger_crmentity.smownerid != ' ')"; + $query=$potential_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Sales by team + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyteam")) + { + $graph_by="groupname"; + $graph_title=$mod_strings['salesbyteam']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like '%Closed Won%' and (vtiger_groups.groupname != NULL || vtiger_groups.groupname != '')"; + $query=$potential_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Account by Industry + elseif ($profileTabsPermission[getTabid("Accounts")] == 0 && ($type == "accountindustry") && (getFieldVisibilityPermission('Accounts',$user_id,'industry') == "0")) + { + $graph_by="industry"; + $graph_title=$mod_strings['accountindustry']; + $module="Accounts"; + $where=""; + $query=$account_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Products by Category + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productcategory") && (getFieldVisibilityPermission('Products',$user_id,'productcategory') == "0")) + { + $graph_by="productcategory"; + $graph_title=$mod_strings['productcategory']; + $module="Products"; + $where=""; + $query=$product_category." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Products by Quantity in stock + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbyqtyinstock") && (getFieldVisibilityPermission('Products',$user_id,'qtyinstock') == "0")) + { + $graph_by="productname"; + $graph_title=$mod_strings['productbyqtyinstock']; + $module="Products"; + $where=""; + $query=$products_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Products by PO + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbypo") && $profileTabsPermission[getTabid("PurchaseOrder")] == 0) + { + $graph_by="purchaseorderid"; + $graph_title=$mod_strings['productbypo']; + $module="Products"; + $where=""; + $query=$probyPO." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Products by Quotes + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbyquotes") && $profileTabsPermission[getTabid("Quotes")] == 0) + { + $graph_by="quoteid"; + $graph_title=$mod_strings['productbyquotes']; + $module="Products"; + $where=""; + $query=$probyQ." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Charts for Products by Invoice + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbyinvoice") && $profileTabsPermission[getTabid("Invoice")] == 0) + { + $graph_by="invoiceid"; + $graph_title=$mod_strings['productbyinvoice']; + $module="Products"; + $where=""; + $query=$probyInv." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + + // Sales Order by Accounts + elseif ($profileTabsPermission[getTabid("SalesOrder")] == 0 && ($type == "sobyaccounts") && (getFieldVisibilityPermission('SalesOrder',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['sobyaccounts']; + $module="SalesOrder"; + $where=""; + $query=$so_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Sales Order by Status + elseif ($profileTabsPermission[getTabid("SalesOrder")] == 0 && ($type == "sobystatus") && (getFieldVisibilityPermission('SalesOrder',$user_id,'sostatus') == "0")) + { + $graph_by="sostatus"; + $graph_title=$mod_strings['sobystatus']; + $module="SalesOrder"; + $where=""; + $query=$so_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Purchase Order by Status + elseif ($profileTabsPermission[getTabid("PurchaseOrder")] == 0 && ($type == "pobystatus") && (getFieldVisibilityPermission('PurchaseOrder',$user_id,'postatus') == "0")) + { + $graph_by="postatus"; + $graph_title=$mod_strings['pobystatus']; + $module="PurchaseOrder"; + $where=""; + $query=$po_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Quotes by Accounts + elseif ($profileTabsPermission[getTabid("Quotes")] == 0 && ($type == "quotesbyaccounts") && (getFieldVisibilityPermission('Quotes',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title= $mod_strings['quotesbyaccounts']; + $module="Quotes"; + $where=""; + $query=$quotes_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Quotes by Stage + elseif ($profileTabsPermission[getTabid("Quotes")] == 0 && ($type == "quotesbystage") && (getFieldVisibilityPermission('Quotes',$user_id,'quotestage') == "0")) + { + $graph_by="quotestage"; + $graph_title=$mod_strings['quotesbystage']; + $module="Quotes"; + $where=""; + $query=$quotes_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Invoice by Accounts + elseif ($profileTabsPermission[getTabid("Invoice")] == 0 && ($type == "invoicebyacnts") && (getFieldVisibilityPermission('Invoice',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['invoicebyacnts']; + $module="Invoice"; + $where=""; + $query=$invoice_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Invoices by status + elseif ($profileTabsPermission[getTabid("Invoice")] == 0 && ($type == "invoicebystatus") && (getFieldVisibilityPermission('Invoice',$user_id,'invoicestatus') == "0")) + { + $graph_by="invoicestatus"; + $graph_title=$mod_strings['invoicebystatus']; + $module="Invoice"; + $where=""; + $query=$invoice_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Status + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbystatus") && (getFieldVisibilityPermission('HelpDesk',$user_id,'ticketstatus') == "0")) + { + $graph_by="ticketstatus"; + $graph_title=$mod_strings['ticketsbystatus']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Priority + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbypriority") && (getFieldVisibilityPermission('HelpDesk',$user_id,'ticketpriorities') == "0")) + { + $graph_by="priority"; + $graph_title=$mod_strings['ticketsbypriority']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Category + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbycategory") && (getFieldVisibilityPermission('HelpDesk',$user_id,'ticketcategories') == "0")) + { + $graph_by="category"; + $graph_title=$mod_strings['ticketsbycategory']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by User + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyuser")) + { + $graph_by="smownerid"; + $graph_title=$mod_strings['ticketsbyuser']; + $module="HelpDesk"; + $where=" and (vtiger_crmentity.smownerid != NULL || vtiger_crmentity.smownerid != ' ')"; + $query=$helpdesk_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Team + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyteam")) + { + $graph_by="ticketgroupname"; + $graph_title=$mod_strings['ticketsbyteam']; + $module="HelpDesk"; + $where=" and (vtiger_groups.groupname != NULL || vtiger_groups.groupname != ' ')"; + $query=$helpdesk_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Product + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyproduct") && (getFieldVisibilityPermission('HelpDesk',$user_id,'product_id') == "0")) + { + $graph_by="product_id"; + $graph_title=$mod_strings['ticketsbyproduct']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Campaigns by Contact + elseif ($profileTabsPermission[getTabid("Contacts")] == 0 && ($type == "contactbycampaign") && $profileTabsPermission[getTabid("Campaigns")] == 0) + { + $graph_by="campaignid"; + $graph_title=$mod_strings['contactbycampaign']; + $module="Contacts"; + $where=""; + $query=$campaign_query." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Account + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyaccount") && (getFieldVisibilityPermission('HelpDesk',$user_id,'parent_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['ticketsbyaccount']; + $module="HelpDesk"; + $where=""; + $query=$tickets_by_account." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + //Tickets by Contact + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbycontact") && (getFieldVisibilityPermission('HelpDesk',$user_id,'parent_id') == "0")) + { + $graph_by="contactid"; + $graph_title=$mod_strings['ticketsbycontact']; + $module="HelpDesk"; + $where=""; + $query=$tickets_by_contact." ".dashboard_check($module); + return get_graph_by_type($graph_by,$graph_title,$module,$where,$query,"210","210","forhomepage"); + } + else + { + //echo $mod_strings['LBL_NO_PERMISSION_FIELD']; + sleep(1); + return '

'.$mod_strings['LBL_NO_PERMISSION_FIELD'].'

'; + } + } + else + { + $html='
+ + + +
+ '; + echo $html_string; +?> diff --git a/oss/vtiger/trunk/modules/Calendar/index.php b/oss/vtiger/trunk/modules/Calendar/index.php new file mode 100644 index 00000000..06bda1f8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/index.php @@ -0,0 +1,32 @@ + diff --git a/oss/vtiger/trunk/modules/Calendar/language/en_us.lang.php b/oss/vtiger/trunk/modules/Calendar/language/en_us.lang.php new file mode 100644 index 00000000..3b5cf4c5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/language/en_us.lang.php @@ -0,0 +1,442 @@ +'Calendar', +'LBL_MODULE_TITLE'=>'Calendar: Home', +'LBL_MODULE_APPOINTMENT'=>'Calendar: Appointment', +'LBL_MODULE_APPOINTMENT_DETAIL'=>'Calendar: Appointment Detail', +'LBL_SAVE'=>'Save', +'LBL_RESET'=>'Cancel', +'LBL_LIST_USER_NAME'=>'User Name', +'LBL_LIST_NAME'=>'Name', +'LBL_CALENDAR_SHARED'=>'Calendar currently shared with', +'LBL_CALENDAR_SHARING'=>'Share calendar with', +'LBL_SHARING_OPTION'=>'Can see my calendar?', +'LBL_LIST_TOOLS'=>'Tools', +'LBL_SETTINGS'=>'Settings', +'LBL_CALSETTINGS'=>'Calendar Settings', +'LBL_USE24'=>'Use 24 hours format', +'LBL_CALSTART'=>'Start my calendar time at', +'LBL_TIMESETTINGS'=>'Time Settings', +'LBL_HOLDFOLLOWUP'=>'Hold followup on', +'LBL_CALL' => 'Call', +'LBL_MEET' => 'Meeting', +'LBL_APPNT' => 'Appointment', +'LBL_NEW_APPNT' => 'New Appointment', +'LBL_NEW_APPNT_INFO' => 'Create a new appointment', +'LBL_VIEW_DAY_APPNT_INFO' => 'View appointment(s) for this day', +'LBL_CHANGE_APPNT' => 'see or change this appointment (%s - %s)', + +'LBL_DAY' => 'Day', +'LBL_DAY_BUTTON_KEY' => 'D', +'LBL_DAY_BUTTON_TITLE' => 'Day [Alt+D]', +'LBL_DAY1' => 'Monday', +'LBL_DAY2' => 'Tuesday', +'LBL_DAY3' => 'Wednesday', +'LBL_DAY4' => 'Thursday', +'LBL_DAY5' => 'Friday', +'LBL_DAY6' => 'Saturday', +'LBL_DAY0' => 'Sunday', + +'LBL_SM_MON' => 'Mon', +'LBL_SM_TUE' => 'Tue', +'LBL_SM_WED' => 'Wed', +'LBL_SM_THU' => 'Thu', +'LBL_SM_FRI' => 'Fri', +'LBL_SM_SAT' => 'Sat', +'LBL_SM_SUN' => 'Sun', + +'LBL_DATE_TITLE' => 'Day %d, %A', + +'LBL_WEEK' => 'Week', +'LBL_WEEK_BUTTON_KEY' => 'W', +'LBL_WEEK_BUTTON_TITLE' => 'Week [Alt+W]', +'LBL_WEEKS' => 'Weeks', +'LBL_NEXT_WEEK' => 'next week', +'LBL_LAST_WEEK' => 'last week', +'LBL_4WEEKS_BACK' => '4 weeks back', +'LBL_4WEEKS_PLUS' => '4 weeks plus', +'LBL_RELOAD' => 'Reload', + + +'LBL_APPCREATED_BY' => 'Created by', +'LBL_AT_DATE_TIME' => 'at', + +'LBL_MON' => 'Month', +'LBL_MON_BUTTON_KEY' => 'M', +'LBL_MON_BUTTON_TITLE' => 'Month [Alt+M]', +'LBL_PREV_MON' => 'Previous Month', +'LBL_NEXT_MON' => 'Next Month', + +'LBL_YEAR_BUTTON_KEY'=>'Y', +'LBL_PREV_YEAR'=>'Previous Year', +'LBL_NEXT_YEAR' => 'Next Year', + +'LBL_APP_LOCATION' => 'Location', +'LBL_APP_IGNORE_TIME' => 'ignore above times', +'LBL_SUBJECT'=>'Subject:', +'LBL_APP_DESCRIPTION' => 'Description', +'LBL_CONTACT'=>'Contact:', +'LBL_CONTACT_LIST'=>'Contact List:', + +'LBL_APP_IGNORE_TIME2' => '(i.e. the appointment takes place
at no particular time on these day(s) )', + +'LBL_APP_ERR001' =>'Invalid Date in field %s!', +'LBL_APP_ERR002' =>'start after end !', +'LBL_APP_ERR003' =>'Missing Contact !', +'LBL_APP_ERR004' =>'Missing Subject !', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the appointment.", +'DELETE_CONFIRMATION'=>"Are you sure you want to delete this appointment?", + +'AppLoc'=> Array('0' => 'Office' + , '1' => 'Out' + , '2' => 'Vacation' + , '3' => 'sick' + , '4' => 'Postponed' + , '5' => 'Option' + , '6' => 'Private'), + +'cal_month_long'=>array( +"", +"January", +"February", +"March", +"April", +"May", +"June", +"July", +"August", +"September", +"October", +"November", +"December", +), + +'cal_weekdays_short'=>array( +"Sun", +"Mon", +"Tue", +"Wed", +"Thu", +"Fri", +"Sat", +), +'cal_weekdays_long'=>array( +"Sunday", +"Monday", +"Tuesday", +"Wednesday", +"Thursday", +"Friday", +"Saturday", +), +'cal_month_short'=>array( +"", +"Jan", +"Feb", +"Mar", +"Apr", +"May", +"Jun", +"Jul", +"Aug", +"Sep", +"Oct", +"Nov", +"Dec", +), + +'LBL_TIME'=>'Time', +'LBL_START_TIME' => 'Start Time', +'LBL_END_TIME' => 'End Time', +'LBL_START_DATE'=>'Start Date', +'LBL_TIME_START'=>'Time Start', +'LBL_DUE_DATE'=>'Due Date', +'LBL_START_DATE_TIME'=>'Start Date & Time', +'LBL_END_DATE_TIME'=>'End Date & Time', +'LBL_TODO'=>'To Do', +'LBL_TODOS'=>'To Dos', +'LBL_EVENTS'=>'Events', +'LBL_TOTALEVENTS'=>'My Total Events :', +'LBL_TOTALTODOS'=>'My Total To Dos :', +'LBL_VIEW'=>'View', +'LBL_LISTVIEW'=>'List View', +'LBL_HRVIEW'=>'Hour View', +'LBL_WEEKVIEW'=>'Weekly Calendar View', +'LBL_MONTHVIEW'=>'Monthly Calendar View', +'LBL_YEARVIEW'=>'Yearly Calendar View', +'LBL_STATUS'=>'Status', +'LBL_ACTION'=>'Actions', +'LBL_ADD'=>'Add', +'LBL_OPENCAL'=>'Open Calendar', + + +'LBL_ADD_EVENT'=>'Add Event', +'LBL_ADDCALL'=>'Call', +'LBL_ADDMEETING'=>'Meeting', +'LBL_ADDTODO'=>'To Do', +'LBL_BEFOREEVENT'=>'before the event starts', +'LBL_BEFORETASK'=>'before the task starts', +'LBL_EVENTDETAILS'=>'Event Details', +'LBL_CURSTATUS'=>'Current Status', +'LBL_ASSINGEDTO'=>'Assigned To', +'LBL_RELATEDTO'=>'Related To', +'LBL_PENDING'=>'Pending', +'LBL_PUBLIC'=>'Mark Public', +'LBL_MORE'=>'More', +'LBL_EDIT'=>'Edit', +'LBL_EVERYDAY'=>'Every Day', +'LBL_EVERYWEEK'=>'Every Week', +'LBL_EVERYMON'=>'Every Month', +'LBL_WEEKS'=>'Week(s)', +'LBL_MONTHS'=>'Month(s)', +'LBL_YEAR'=>'Year', +'LBL_NONE_SCHEDULED'=>'None Scheduled', + +'LBL_INVITE_INST1'=>'To invite, select the users from the "Available Users" list and click the "Add" button.', +'LBL_INVITE_SHARE'=>'To share, select the users from the "Available Users" list and click the "Add" button.', +'LBL_INVITE_INST2'=>'To remove, select the users from the "Selected Users" list and the click "Remove" button.', +'LBL_SELUSR_INFO'=>' Selected users will receive an email about the Event.', +'LBL_CALSHAREMESSAGE'=>'Share my calendar with the following selected users', +'LBL_CALSHARE'=>'Calendar Sharing', +'LBL_SEL_USERS'=>'Selected Users', +'LBL_AVL_USERS'=>'Available Users', +'LBL_ADD_BUTTON'=>'Add', +'LBL_USERS'=>'Users', +'LBL_RMV_BUTTON'=>'Remove', +'LBL_SDRMD'=>'Send Reminder to', +'LBL_ENABLE_REPEAT'=>'Enable Repeat', +'LBL_REPEAT_ONCE'=>'Repeat once in every', +'LBL_ADD_TODO'=>'Create To Do', +'LBL_TODONAME'=>'To Do', +'LBL_TODODATETIME'=>'Time & Date', + + + + + +//DON'T CONVERT THESE THEY ARE MAPPINGS - STARTS +'db_last_name' => 'LBL_LIST_LAST_NAME', +'db_first_name' => 'LBL_LIST_FIRST_NAME', +'db_title' => 'LBL_LIST_TITLE', +'db_email1' => 'LBL_LIST_EMAIL_ADDRESS', +'db_email2' => 'LBL_LIST_EMAIL_ADDRESS', +//DON'T CONVERT THESE THEY ARE MAPPINGS -ENDS +'LBL_COMPLETED'=>'Mark Completed', +'LBL_DEFERRED'=>'Mark Deferred', +'LBL_HELD'=>'Mark Held', +'LBL_NOTHELD'=>'Mark Not Held', +'LBL_POSTPONE'=>'Postpone', +'LBL_CHANGEOWNER'=>'Change Owner', +'LBL_DEL'=>'Delete', + +//Added for actvity merge with calendar +'LBL_SEARCH_FORM_TITLE'=>'Activity Search', +'LBL_LIST_FORM_TITLE'=>'Activity List', +'LBL_NEW_FORM_TITLE'=>'New Activity', +'LBL_TASK_INFORMATION'=>'Task Information', +'LBL_EVENT_INFORMATION'=>'Event Information', +'LBL_CALENDAR_INFORMATION'=>'Calendar Information', + +'LBL_NAME'=>'Subject:', +'LBL_ACTIVITY_NOTIFICATION'=>'This is a notification that an activity is assigned to you that has been', +'LBL_ACTIVITY_INVITATION'=>'You have been invited for an activity that has been ', +'LBL_DETAILS_STRING'=>'The details are', +'LBL_REGARDS_STRING'=>'Thanks & Regards', +'LBL_CONTACT_NAME'=>'Contact Name', +'LBL_OPEN_ACTIVITIES'=>'Open Activities', +'LBL_ACTIVITY'=>'Activity:', +'LBL_HISTORY'=>'History', +'LBL_UPCOMING'=>"My Upcoming and Pending Activities", +'LBL_TODAY'=>'through ', + +'LBL_NEW_TASK_BUTTON_TITLE'=>'New Task [Alt+N]', +'LBL_NEW_TASK_BUTTON_KEY'=>'N', +'LBL_NEW_TASK_BUTTON_LABEL'=>'New Task', +'LBL_SCHEDULE_MEETING_BUTTON_TITLE'=>'Schedule Meeting [Alt+M]', +'LBL_SCHEDULE_MEETING_BUTTON_KEY'=>'M', +'LBL_SCHEDULE_MEETING_BUTTON_LABEL'=>'Schedule Meeting', +'LBL_SCHEDULE_CALL_BUTTON_TITLE'=>'Schedule Call [Alt+C]', +'LBL_SCHEDULE_CALL_BUTTON_KEY'=>'C', +'LBL_SCHEDULE_CALL_BUTTON_LABEL'=>'Schedule Call', +'LBL_NEW_NOTE_BUTTON_TITLE'=>'New Document [Alt+T]', +'LBL_NEW_ATTACH_BUTTON_TITLE'=>'Attach File [Alt+F]', +'LBL_NEW_NOTE_BUTTON_KEY'=>'T', +'LBL_NEW_ATTACH_BUTTON_KEY'=>'F', +'LBL_NEW_NOTE_BUTTON_LABEL'=>'New Document', +'LBL_NEW_ATTACH_BUTTON_LABEL'=>'Attach File', +'LBL_TRACK_EMAIL_BUTTON_TITLE'=>'Track Email [Alt+K]', +'LBL_TRACK_EMAIL_BUTTON_KEY'=>'K', +'LBL_TRACK_EMAIL_BUTTON_LABEL'=>'Track Email', + +'LBL_LIST_CLOSE'=>'Close', +'LBL_LIST_STATUS'=>'Status', +'LBL_LIST_CONTACT'=>'Contact', +//Added for 4.2 release for Account column support as shown by Fredy +'LBL_LIST_ACCOUNT'=>'Account', +'LBL_LIST_RELATED_TO'=>'Related to', +'LBL_LIST_DUE_DATE'=>'Due Date', +'LBL_LIST_DATE'=>'Date', +'LBL_LIST_SUBJECT'=>'Subject', +'LBL_LIST_LAST_MODIFIED'=>'Last Modified', +'LBL_LIST_RECURRING_TYPE'=>'Recurring Type', + +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", +'NTC_NONE_SCHEDULED'=>'None scheduled.', + +// Added vtiger_fields for Attachments in Activities/SubPanelView.php +'LBL_ATTACHMENTS'=>'Attachments', +'LBL_NEW_ATTACHMENT'=>'New Attachment', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_CALL'=>'Call', +'LBL_MEETING'=>'Meeting', +'LBL_TASK'=>'Task', + +//Added for 4GA Release +'Subject'=>'Subject', +'Assigned To'=>'Assigned To', +'Start Date & Time'=>'Start Date & Time', +'Time Start'=>'Time Start', +'Due Date'=>'Due Date', +'Related To'=>'Related to', +'Contact Name'=>'Contact Name', +'Status'=>'Status', +'Priority'=>'Priority', +'Visibility'=>'Visibility', +'Send Notification'=>'Send Notification', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Activity Type'=>'Activity Type', +'Description'=>'Description', +'Duration'=>'Duration', +'Duration Minutes'=>'Duration Minutes', +'Location'=>'Location', +'No Time'=>'No Time', +//Added for Send Reminder 4.2 release +'Send Reminder'=>'Send Reminder', +'LBL_YES'=>'Yes', +'LBL_NO'=>'No', +'LBL_DAYS'=>'day(s)', +'LBL_MINUTES'=>'minutes', +'LBL_HOURS'=>'hours', +'LBL_BEFORE_EVENT'=>'before event', +//Added for CustomView 4.2 Release +'Close'=>'Close', +'Start Date'=>'Start Date', +'Type'=>'Type', +'End Date'=>'End Date', +'Recurrence'=> 'Recurring Events', +'Recurring Type'=> 'Recurring Type', +//Activities - Notification Error +'LBL_NOTIFICATION_ERROR'=>'Mail Error : Please check your outgoing mail server configuration in Settings->Outgoing Mail Server Configuration OR MailId for the present user is not Configured', +// Mike Crowe Mod --------------------------------------------------------added for generic search +'LBL_GENERAL_INFORMATION'=>'General Information', + +'LBL_EVENTTYPE'=>'Event Type', +'LBL_EVENTNAME'=>'Event Name', +'LBL_EVENTSTAT'=>'Event starts at', +'LBL_EVENTEDAT'=>'Event ends on', +'LBL_INVITE'=>'Invite', +'LBL_REPEAT'=>'Repeat', +'LBL_REMINDER'=>'Reminder', +'LBL_SENDREMINDER'=>'Send Reminder', +'LBL_NOTIFICATION'=>'Notification', +'LBL_SENDNOTIFICATION'=>'Send Notification', +'LBL_RMD_ON'=>'Remind on', +'LBL_REPEATEVENT'=>'Repeat once in every', +'LBL_TIMEDATE'=>'Time & Date', +'LBL_HR'=>'Hr', +'LBL_MIN'=>'min', +'LBL_EVENT'=>'Event', +'Daily'=>'Day(s)', +'Weekly'=>'Week(s)', +'Monthly'=>'Month(s)', +'Yearly'=>'Year', +'createdtime'=>'Created Time', +'modifiedtime'=>'Modified Time', +'first'=>'First', +'last'=>'Last', +'High'=>'High', +'Medium'=>'Medium', +'Low'=>'Low', +'LBL_SELECT'=>'Select', +'LBL_ALL_EVENTS_TODOS'=>'All Events & Todos', +'First'=>'First', +'Last'=>'Last', +'on'=>'on', +'day of the month'=>'day of the month', +'Private'=>'Private', +'Public'=>'Public', + +//Added for existing Picklist entries + +'Planned'=>'Planned', +'Held'=>'Held', +'Not Held'=>'Not Held', +'Completed'=>'Completed', +'Deferred'=>'Deferred', +'Not Started'=>'Not Started', +'In Progress'=>'In Progress', +'Pending Input'=>'Pending Input', +'LBL_REMAINDER_DAY'=>'days', +'LBL_REMAINDER_HRS'=>'hrs', +'Call'=>'Call', +'Meeting'=>'Meeting', + +//added to send dates and time in calendar notification/invitation mail. + +'Start date and time'=>'Start Date & Time', +'End date and time'=>'End Date & Time', +//this is for task +'End date'=>'End date', +'LBL_SET_DATE'=>'Set date..', +'Recurrence'=>'Recurrence', + +//added to send invitation mail Subject. +'INVITATION'=>' Invitation ', + +// Added/Updated for vtiger CRM 5.0.4 +'LBL_YEAR_BUTTON_TITLE'=>'Year [Alt+Y]', +'LBL_SELECT_CONTACT'=>'Select Contacts', +'SHARED_EVENT_DEL_MSG'=>'The User does not have permission to Edit/Delete Shared Event.', +//added to fix ticket#4525 +'LBL_CREATED'=>'created', +'LBL_UPDATED'=>'updated', + +//Added after 5.0.4 GA +'LBL_BUSY' => 'Busy', + +//Custom Fields support for Calendar +'LBL_CUSTOM_INFORMATION'=>'Custom Information', + +// Repeat Event support for Calendar +'LBL_UNTIL' => 'Until', +'LBL_SET_DATE'=>'Set Date', + +'LBL_MINE' =>'Mine', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Calendar/language/zh_cn.lang.php new file mode 100644 index 00000000..db1fb31b --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/language/zh_cn.lang.php @@ -0,0 +1,441 @@ + '计划任务', + 'LBL_MODULE_TITLE' => '计划任务: 首页', + 'LBL_MODULE_APPOINTMENT' => '计划任务: 行程', + 'LBL_MODULE_APPOINTMENT_DETAIL' => '计划任务: 计划细节', +'LBL_SAVE' => '保存', + 'LBL_RESET' => '取消', + 'LBL_LIST_USER_NAME' => '账号', + 'LBL_LIST_NAME' => '名称', +'LBL_CALENDAR_SHARED' => '计划目前分享给', + 'LBL_CALENDAR_SHARING' => '分享计划给', + 'LBL_SHARING_OPTION' => '可以检视我的计划?', + 'LBL_LIST_TOOLS' => '工具', + 'LBL_SETTINGS' => '设定', + 'LBL_CALSETTINGS' => '计划任务设定', + 'LBL_USE24' => '使用 24 小时制', + 'LBL_CALSTART' => '计划任务开始时间', + 'LBL_TIMESETTINGS' => '时间设定', + 'LBL_OPENCAL' => '开放计划任务', + 'LBL_CALL' => '电话记录', + 'LBL_MEET' => '会议', + 'LBL_APPNT' => '行程', + 'LBL_NEW_APPNT' => '新增行程', + 'LBL_NEW_APPNT_INFO' => '建立一笔新的行程', + 'LBL_VIEW_DAY_APPNT_INFO' => '浏览今天的行程', + 'LBL_CHANGE_APPNT' => '察看或变更这个行程 (%s - %s)', + + 'LBL_DAY' => '日', + 'LBL_DAY_BUTTON_KEY' => 'D', + 'LBL_DAY_BUTTON_TITLE' => '日 [Alt+D]', + 'LBL_DAY1' => '周一', + 'LBL_DAY2' => '周二', + 'LBL_DAY3' => '周三', + 'LBL_DAY4' => '周四', + 'LBL_DAY5' => '周五', + 'LBL_DAY6' => '周六', + 'LBL_DAY0' => '周日', + + 'LBL_SM_MON' => '一', + 'LBL_SM_TUE' => '二', + 'LBL_SM_WED' => '三', + 'LBL_SM_THU' => '四', + 'LBL_SM_FRI' => '五', + 'LBL_SM_SAT' => '六', + 'LBL_SM_SUN' => '日', + +'LBL_DATE_TITLE' => 'Day %d, %A', + + 'LBL_WEEK' => '周', + 'LBL_WEEK_BUTTON_KEY' => 'W', + 'LBL_WEEK_BUTTON_TITLE' => '周 [Alt+W]', + 'LBL_WEEKS' => '周', + 'LBL_NEXT_WEEK' => '下周', + 'LBL_LAST_WEEK' => '上周', + 'LBL_4WEEKS_BACK' => '四周前', + 'LBL_4WEEKS_PLUS' => '四周后', + 'LBL_RELOAD' => '重新加载', + + +'LBL_APPCREATED_BY' => '建立者:', +'LBL_AT_DATE_TIME' => '在', + + 'LBL_MON' => '月', + 'LBL_MON_BUTTON_KEY' => 'M', + 'LBL_MON_BUTTON_TITLE' => '月 [Alt+M]', + 'LBL_PREV_MON' => '上个月', + 'LBL_NEXT_MON' => '下个月', + + 'LBL_YEAR_BUTTON_KEY' => 'Y', + 'LBL_PREV_YEAR' => '去年', + 'LBL_NEXT_YEAR' => '明年', + +'LBL_APP_LOCATION' => '所在地', +'LBL_APP_IGNORE_TIME' => '忽略', +'LBL_SUBJECT'=>'主题:', +'LBL_APP_DESCRIPTION' => '描述', +'LBL_CONTACT'=>'联系方式:', +'LBL_CONTACT_LIST'=>'联系人列表:', + +'LBL_APP_IGNORE_TIME2' => '(注:这个行程在该期间没有特定的时间 )', + +'LBL_APP_ERR001' =>'字段 %s产生错误!', + 'LBL_APP_ERR002' => '开始日期在结束日期之后 !', + 'LBL_APP_ERR003' => '漏填联系人 !', + 'LBL_APP_ERR004' => '漏填标题 !', +'ERR_DELETE_RECORD' => '在删除行程前必须输入正确的记录编号.', + 'DELETE_CONFIRMATION' => '您确定要删除这次的行程?', + +'AppLoc'=> Array('0' => '办公室', + '1' => '户外', + '2' => '休假', + '3' => '病假', + '4' => '延期', + '5' => '随意', + '6' => '私人',), + +'cal_month_long'=>array( +"", +"一月", +"二月", +"三月", +"四月", +"五月", +"六月", +"七月", +"八月", +"九月", +"十月", +"十一月", +"十二月", +), + +'cal_weekdays_short'=>array( +"日", +"一", +"二", +"三", +"四", +"五", +"六", +), +'cal_weekdays_long'=>array( +"星期日", +"星期一", +"星期二", +"星期三", +"星期四", +"星期五", +"星期六", +), +'cal_month_short'=>array( +"", +"一月", +"二月", +"三月", +"四月", +"五月", +"六月", +"七月", +"八月", +"九月", +"十月", +"十一月", +"十二月", +), + +'LBL_TIME'=>'时间', +'LBL_START_TIME' => '开始时间', +'LBL_END_TIME' => '结束时间', +'LBL_START_DATE'=>'开始日期', +'LBL_TIME_START'=>'时间开始', +'LBL_DUE_DATE'=>'到期日', +'LBL_START_DATE_TIME'=>'开始日期 & 时间', +'LBL_END_DATE_TIME'=>'结束日期 & 时间', +'LBL_TODO'=>'待办', +'LBL_TODOS'=>'待办事项', +'LBL_EVENTS'=>'事件', +'LBL_TOTALEVENTS'=>'我的全部事件 :', +'LBL_TOTALTODOS'=>'我的待办事项 :', +'LBL_VIEW'=>'查看', +'LBL_LISTVIEW'=>'查看列表', +'LBL_HRVIEW'=>'产看时间', +'LBL_WEEKVIEW'=>'查看周历', +'LBL_MONTHVIEW'=>'查看月历', +'LBL_YEARVIEW'=>'查看年历', +'LBL_STATUS'=>'状态', +'LBL_ACTION'=>'操作', +'LBL_ADD'=>'添加', +'LBL_OPENCAL'=>'打开日历', + + +'LBL_ADD_EVENT'=>'添加事件', +'LBL_ADDCALL'=>'呼叫', +'LBL_ADDMEETING'=>'会议', +'LBL_ADDTODO'=>'待办', +'LBL_BEFOREEVENT'=>'在事件开始之前', +'LBL_BEFORETASK'=>'在任务开始之前', +'LBL_EVENTDETAILS'=>'事件细节', +'LBL_CURSTATUS'=>'当前状态', +'LBL_ASSINGEDTO'=>'分配给', +'LBL_RELATEDTO'=>'关联于', +'LBL_PENDING'=>'即将发生', +'LBL_PUBLIC'=>'标记公共', +'LBL_MORE'=>'更多', +'LBL_EDIT'=>'编辑', + 'LBL_EVERYDAY' => '每天', + 'LBL_EVERYWEEK' => '每周', + 'LBL_EVERYMON' => '每月', +'LBL_WEEKS'=>'周', +'LBL_MONTHS'=>'月', +'LBL_YEAR'=>'年', +'LBL_NONE_SCHEDULED'=>'没有行程', + + 'LBL_INVITE_INST1' => '邀请的方式可以从目前使用者列表选择并且点选新增按钮', +'LBL_INVITE_SHARE'=>'分享的方式可以从目前使用者列表选择并且点选新增按钮.', +'LBL_INVITE_INST2' => '移除邀请的人可以从选择的使用者列表选择并且点选移除按钮', + 'LBL_SELUSR_INFO' => '选择的使用者会收到一封事件的通知。', + 'LBL_CALSHAREMESSAGE'=>'开放我的行事历给下面选择的使用者', +'LBL_CALSHARE' => '开放行事历', + 'LBL_SEL_USERS' => '选择的使用者', + 'LBL_AVL_USERS' => '目前使用者', + 'LBL_ADD_BUTTON' => '新增', + 'LBL_USERS' => '使用者', +'LBL_RMV_BUTTON'=>'移除', +'LBL_SDRMD'=>'发送提醒讯息', +'LBL_ENABLE_REPEAT'=>'启用循环', +'LBL_REPEAT_ONCE'=>'循环频率', +'LBL_ADD_TODO'=>'建立待办事项', +'LBL_TODONAME'=>'待办事项', +'LBL_TODODATETIME'=>'时间与日期', + + + + + +//DON'T CONVERT THESE THEY ARE MAPPINGS - STARTS +'db_last_name' => 'LBL_LIST_LAST_NAME', +'db_first_name' => 'LBL_LIST_FIRST_NAME', +'db_title' => 'LBL_LIST_TITLE', +'db_email1' => 'LBL_LIST_EMAIL_ADDRESS', +'db_email2' => 'LBL_LIST_EMAIL_ADDRESS', +//DON'T CONVERT THESE THEY ARE MAPPINGS -ENDS +'LBL_COMPLETED' => '标示为完成', + 'LBL_DEFERRED' => '标示为延缓', + 'LBL_HELD' => '标示为执行', + 'LBL_NOTHELD' => '标示为不执行', + 'LBL_POSTPONE' => '延期', + 'LBL_CHANGEOWNER' => '修改负责人', + 'LBL_DEL' => '删除', + +//Added for actvity merge with calendar +'LBL_SEARCH_FORM_TITLE'=>'搜索待办事项', +'LBL_LIST_FORM_TITLE'=>'待办事项列表', +'LBL_NEW_FORM_TITLE'=>'新增待办事项', +'LBL_TASK_INFORMATION'=>'任务信息', +'LBL_EVENT_INFORMATION'=>'事件信息', +'LBL_CALENDAR_INFORMATION'=>'日历信息', + +'LBL_NAME' => '主题:', +'LBL_ACTIVITY_NOTIFICATION'=>'这是通知活动分配给你', +'LBL_ACTIVITY_INVITATION'=>'你被邀请参与一个活动 ', +'LBL_DETAILS_STRING'=>'细节是', +'LBL_REGARDS_STRING'=>'感谢和问候', + 'LBL_CONTACT_NAME' => '联系人', + 'LBL_OPEN_ACTIVITIES' => '进行中事项', + 'LBL_ACTIVITY' => '待办事项:', + 'LBL_HISTORY' => '纪录', + 'LBL_UPCOMING' => '即将到来与等待中待办事项', + 'LBL_TODAY' => '到', + + 'LBL_NEW_TASK_BUTTON_TITLE' => '新增任务 [Alt+N]', + 'LBL_NEW_TASK_BUTTON_KEY' => 'N', + 'LBL_NEW_TASK_BUTTON_LABEL' => '新增任务', + 'LBL_SCHEDULE_MEETING_BUTTON_TITLE' => '安排会议 [Alt+M]', + 'LBL_SCHEDULE_MEETING_BUTTON_KEY' => 'M', + 'LBL_SCHEDULE_MEETING_BUTTON_LABEL' => '安排会议', + 'LBL_SCHEDULE_CALL_BUTTON_TITLE' => '安排电话 [Alt+C]', + 'LBL_SCHEDULE_CALL_BUTTON_KEY' => 'C', + 'LBL_SCHEDULE_CALL_BUTTON_LABEL' => '安排电话', + 'LBL_NEW_NOTE_BUTTON_TITLE' => '新增记事 [Alt+T]', + 'LBL_NEW_ATTACH_BUTTON_TITLE' => '附加档案 [Alt+F]', + 'LBL_NEW_NOTE_BUTTON_KEY' => 'T', + 'LBL_NEW_ATTACH_BUTTON_KEY' => 'F', + 'LBL_NEW_NOTE_BUTTON_LABEL' => '新增记事', + 'LBL_NEW_ATTACH_BUTTON_LABEL' => '附加档案', + 'LBL_TRACK_EMAIL_BUTTON_TITLE' => '追踪邮件 [Alt+K]', + 'LBL_TRACK_EMAIL_BUTTON_KEY' => 'K', + 'LBL_TRACK_EMAIL_BUTTON_LABEL' => '追踪邮件', + + 'LBL_LIST_CLOSE' => '关闭', + 'LBL_LIST_STATUS' => '状态', + 'LBL_LIST_CONTACT' => '联系人', +//Added for 4.2 release for Account column support as shown by Fredy +'LBL_LIST_ACCOUNT' => '客户', + 'LBL_LIST_RELATED_TO' => '相关于', + 'LBL_LIST_DUE_DATE' => '结束日期', + 'LBL_LIST_DATE' => '日期', + 'LBL_LIST_SUBJECT' => '主旨1', + 'LBL_LIST_LAST_MODIFIED' => '最后更新', + 'LBL_LIST_RECURRING_TYPE' => '循环类型', + +'ERR_DELETE_RECORD'=>"一个记录编号必须被指定删除vtiger_account.", +'NTC_NONE_SCHEDULED'=>'没有安排.', + +// Added vtiger_fields for Attachments in Activities/SubPanelView.php +'LBL_ATTACHMENTS' => '附加档案', + 'LBL_NEW_ATTACHMENT' => '新增附加档案', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'全部', +'LBL_CALL'=>'呼叫', +'LBL_MEETING'=>'会议', +'LBL_TASK'=>'任务', + +//Added for 4GA Release + 'Subject' => '主旨2', + 'Assigned To' => '负责人', + 'Start Date & Time' => '开始日期与时间', + 'Time Start' => '开始时间', + 'Due Date' => '到期日', + 'Related To' => '相关于', + 'Contact Name' => '联系人名称', + 'Status' => '状态', + 'Priority' => '优先级', + 'Visibility' => '显示', + 'Send Notification' => '寄送通知', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Activity Type' => '活动类型', + 'Description' => '描述', + 'Duration' => '期间', + 'Duration Minutes' => '期间分钟', + 'Location' => '位置', + 'No Time' => '没有时间', +//Added for Send Reminder 4.2 release + 'Send Reminder' => '提醒通知', +'LBL_YES'=>'是', +'LBL_NO'=>'否', +'LBL_DAYS'=>'日', +'LBL_MINUTES'=>'分', +'LBL_HOURS'=>'时', +'LBL_BEFORE_EVENT'=>'时间前', +//Added for CustomView 4.2 Release + 'Close' => '关闭', + 'Start Date' => '开始日期', + 'Type' => '类型', + 'End Date' => '结束日期', + 'Recurrence' => '循环事件', + 'Recurring Type' => '循环类型', +//Activities - Notification Error +'LBL_NOTIFICATION_ERROR' => '邮件错误:请检查您的外寄邮件服务器设定,在 设定->外寄邮件服务器设定 或是目前使用者的邮件没有设定好', +// Mike Crowe Mod --------------------------------------------------------added for generic search + 'LBL_GENERAL_INFORMATION' => '一般信息', + +'LBL_EVENTTYPE'=>'事件类型', +'LBL_EVENTNAME'=>'事件名称', +'LBL_EVENTSTAT'=>'事件开始于', +'LBL_EVENTEDAT'=>'事件结束于', +'LBL_INVITE'=>'邀请', +'LBL_REPEAT'=>'重复', +'LBL_REMINDER'=>'提示', +'LBL_SENDREMINDER'=>'发送提示', +'LBL_NOTIFICATION'=>'通知', +'LBL_SENDNOTIFICATION'=>'发送通知', +'LBL_RMD_ON'=>'提醒', +'LBL_REPEATEVENT'=>'每个都重复一次', +'LBL_TIMEDATE'=>'时间和日期', +'LBL_HR'=>'时', +'LBL_MIN'=>'分', +'LBL_EVENT'=>'事件', +'Daily'=>'天', +'Weekly'=>'周', +'Monthly'=>'月', +'Yearly'=>'年', +'createdtime'=>'建立时间', +'modifiedtime'=>'修改时间', +'first'=>'第一个', +'last'=>'最后一个', +'High'=>'高', +'Medium'=>'中', +'Low'=>'低', +'LBL_SELECT'=>'选择', + 'LBL_ALL_EVENTS_TODOS' => '所有事件与工作', + 'First' => '第一笔', + 'Last' => '最后一笔', + 'on' => '于', + 'day of the month' => '日', +'Private'=>'私有', +'Public'=>'公共', + +//Added for existing Picklist entries + +'Planned' => '已规划', + 'Held' => '保留', +'Not Held' => '不保留', + 'Completed' => '完成', + 'Deferred' => '延期', + 'Not Started' => '未开始', + 'In Progress' => '处理中', + 'Pending Input' => '等待输入', + 'LBL_REMAINDER_DAY' => '天', + 'LBL_REMAINDER_HRS' => '小时', + 'Call' => '电话', + 'Meeting' => '会议', + +//added to send dates and time in calendar notification/invitation mail. + +'Start date and time'=>'开始日期和时间', +'End date and time'=>'结束日期和时间', +//this is for task +'End date'=>'结束日期', +'LBL_SET_DATE'=>'设置日期..', +'Recurrence'=>'再现', + + +'INVITATION'=>' 邀请 ', + + +'LBL_YEAR_BUTTON_TITLE'=>'Year [Alt+Y]', + 'LBL_SELECT_CONTACT' => '选择联系人', +'SHARED_EVENT_DEL_MSG'=>'用户没有允许删除这个纪录.', +//added to fix ticket#4525 +'LBL_CREATED'=>'created', +'LBL_UPDATED'=>'updated', +//Added after 5.0.4 GA +'LBL_BUSY' => '忙碌', + +//Custom Fields support for Calendar +'LBL_CUSTOM_INFORMATION'=>'自定义信息', + +// Repeat Event support for Calendar +'LBL_UNTIL' => '至', +'LBL_SET_DATE'=>'设置日期', + +'LBL_MINE' =>'我的', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Calendar/new_calendar.php b/oss/vtiger/trunk/modules/Calendar/new_calendar.php new file mode 100644 index 00000000..afcf5490 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/new_calendar.php @@ -0,0 +1,92 @@ +activity_view == "This Year"){ + $mysel = 'year'; + }else if($current_user->activity_view == "This Month"){ + $mysel = 'month'; + }else if($current_user->activity_view == "This Week"){ + $mysel = 'week'; + }else{ + $mysel = 'day'; + } +} +/* fix given by dartagnanlaf END --integrated by Minnie */ +$date_data = array(); +if ( isset($_REQUEST['day'])) +{ + + $date_data['day'] = $_REQUEST['day']; +} + +if ( isset($_REQUEST['month'])) +{ + $date_data['month'] = $_REQUEST['month']; +} + +if ( isset($_REQUEST['week'])) +{ + $date_data['week'] = $_REQUEST['week']; +} + +if ( isset($_REQUEST['year'])) +{ + if ($_REQUEST['year'] > 2037 || $_REQUEST['year'] < 1970) + { + print("".$app_strings['LBL_CAL_LIMIT_MSG'].""); + exit; + } + $date_data['year'] = $_REQUEST['year']; +} + + +if(empty($date_data)) +{ + $data_value=date('Y-m-d H:i:s'); + preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$data_value,$value); + $date_data = Array( + 'day'=>$value[3], + 'month'=>$value[2], + 'year'=>$value[1], + 'hour'=>$value[4], + 'min'=>$value[5], + ); + +} +$calendar_arr['calendar'] = new Calendar($mysel,$date_data); +if($current_user->hour_format != '') + $calendar_arr['calendar']->hour_format=$current_user->hour_format; +if ($viewBox == 'hourview' && ($mysel == 'day' || $mysel == 'week' || $mysel == 'month' || $mysel == 'year')) +{ + $calendar_arr['calendar']->add_Activities($current_user); +} +$calendar_arr['view'] = $mysel; +calendar_layout($calendar_arr,$viewBox,$subtab); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/script.js b/oss/vtiger/trunk/modules/Calendar/script.js new file mode 100644 index 00000000..c90ceb8f --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/script.js @@ -0,0 +1,1399 @@ +/********************************************************************************* + +** 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. + ********************************************************************************/ + +function DisableSharing() +{ + + x = document.SharedList.selected_id.length; + idstring = ""; + xx = 0; + if ( x == undefined) + { + + if (document.SharedList.selected_id.checked) + { + document.SharedList.idlist.value=document.SharedList.selected_id.value; + } + else + { + alert(alert_arr.SELECT_ATLEAST_ONE_USER); + return false; + } + } + else + { + for(i = 0; i < x ; i++) + { + if(document.SharedList.selected_id[i].checked) + { + idstring = document.SharedList.selected_id[i].value +";"+idstring + xx++ + } + } + if (xx != 0) + { + document.SharedList.idlist.value=idstring; + } + else + { + alert(alert_arr.SELECT_ATLEAST_ONE_USER); + return false; + } + } + if(confirm(alert_arr.DISABLE_SHARING_CONFIRMATION+xx+alert_arr.USERS)) + { + document.SharedList.action="index.php?module=Calendar&action=disable_sharing&return_module=Calendar&return_action=calendar_share"; + } + else + { + return false; + } +} + + + +function showhide(argg) +{ + var x=document.getElementById(argg).style; + if (x.display=="none") + { + x.display="block" + + } + else { + x.display="none" + } +} + + +function showhideRepeat(argg1,argg2) +{ + var x=document.getElementById(argg2).style; + var y=document.getElementById(argg1).checked; + + if (y) + { + x.display="block"; + } + else { + x.display="none"; + } + +} + + + +function gshow(argg1,type,startdate,enddate,starthr,startmin,startfmt,endhr,endmin,endfmt,viewOption,subtab) +{ + smin = parseInt(startmin,10); + smin = smin - (smin%5); + var y=document.getElementById(argg1).style; + + if(type != 'todo' && type!='') + { + for(var i=0;;i++){ + if( document.EditView.activitytype[i].value == type){ + document.EditView.activitytype[i].selected='yes'; + break; + } + } + + smin = _2digit(smin); + document.EditView.date_start.value = startdate; + document.EditView.starthr.value = starthr; + document.EditView.startmin.value = smin; + document.EditView.startfmt.value = startfmt; + document.EditView.viewOption.value = viewOption; + document.EditView.subtab.value = subtab; + calDuedatetime(type); + } + if(type == 'todo') + { + smin = _2digit(smin); + document.createTodo.task_date_start.value = startdate; + document.createTodo.task_due_date.value = enddate; + document.createTodo.starthr.value = starthr; + document.createTodo.startmin.value = smin; + document.createTodo.startfmt.value = startfmt; + document.createTodo.viewOption.value = viewOption; + document.createTodo.subtab.value = subtab; + } + if (y.display=="none") + { + y.display="block"; + } +} + +function rptoptDisp(Opt){ + var currOpt = Opt.options[Opt.selectedIndex].value; + if(currOpt == "Daily") + { + ghide('repeatWeekUI'); + ghide('repeatMonthUI'); + } + else if(currOpt == "Weekly") + { + if(document.getElementById('repeatWeekUI').style.display == "none"); + document.getElementById('repeatWeekUI').style.display = "block"; + ghide('repeatMonthUI'); + } + else if(currOpt == "Monthly") + { + ghide('repeatWeekUI'); + if(document.getElementById('repeatMonthUI').style.display == "none"); + document.getElementById('repeatMonthUI').style.display = "block"; + } + else if(currOpt == "Yearly") + { + ghide('repeatWeekUI'); + ghide('repeatMonthUI'); + } +} + +function Taskshow(argg1,type,startdate,starthr,startmin,startfmt) +{ + var y=document.getElementById(argg1).style; + if (y.display=="none") + { + document.EditView.date_start.value = startdate; + document.EditView.starthr.value = starthr; + document.EditView.startmin.value = startmin; + document.EditView.startfmt.value = startfmt; + y.display="block"; + } +} + +function ghide(argg2) +{ + var z=document.getElementById(argg2).style; + if (z.display=="block" ) + { + z.display="none" + + } +} + + function moveMe(arg1) { + var posx = 0; + var posy = 0; + var e=document.getElementById(arg1); + + if (!e) var e = window.event; + + if (e.pageX || e.pageY) + { + posx = e.pageX; + posy = e.pageY; + } + else if (e.clientX || e.clientY) + { + posx = e.clientX + document.body.scrollLeft; + posy = e.clientY + document.body.scrollTop; + } + } + +function switchClass(myModule,toStatus) { + var x=document.getElementById(myModule); + if($(x)) + { + if (toStatus=="on") { + x.className="dvtSelectedCell"; + } + if (toStatus=="off") { + x.className="dvtUnSelectedCell"; + } + } + +} + +function enableCalstarttime() +{ + if(document.SharingForm.sttime_check.checked == true) + document.SharingForm.start_hour.disabled = false; + else + document.SharingForm.start_hour.disabled = true; +} +function check_form() +{ + formSelectColumnString('inviteesid','selectedusers'); + if(trim(document.EditView.subject.value) == "") + { + alert(alert_arr.MISSING_EVENT_NAME); + document.EditView.subject.focus() + return false; + } + else + { + if(document.EditView.record.value != '') + { + document.EditView.mode.value = 'edit'; + } + else + { + document.EditView.mode.value = 'create'; + } + starthour = parseInt(document.EditView.starthr.value,10); + startmin = parseInt(document.EditView.startmin.value,10); + startformat = document.EditView.startfmt.value; + endhour = parseInt(document.EditView.endhr.value,10); + endmin = parseInt(document.EditView.endmin.value,10); + endformat = document.EditView.endfmt.value; + followupformat = document.EditView.followup_startfmt.value; + followuphour = parseInt(document.EditView.followup_starthr.value,10); + followupmin = parseInt(document.EditView.followup_startmin.value,10); + if(startformat != '') + { + if(startformat == 'pm') + { + if(starthour == 12) + starthour = 12; + else + starthour = starthour + 12; + } + else + { + if(starthour == 12) + starthour = 0; + else + starthour = starthour; + } + } + if(endformat != '') + { + if(endformat == 'pm') + { + if(endhour == 12) + endhour = 12; + else + endhour = endhour + 12; + } + else + { + if(endhour == 12) + endhour = 0; + else + endhour = endhour; + } + } + if(!dateValidate('date_start','Start date','OTH')) + { + return false; + } + if(!dateValidate('due_date','End date','OTH')) + { + return false; + } + if(dateComparison('due_date','End date','date_start','Start date','GE')) + { + var dateval1=getObj('date_start').value.replace(/^\s+/g, '').replace(/\s+$/g, ''); + var dateval2=getObj('due_date').value.replace(/^\s+/g, '').replace(/\s+$/g, ''); + var dateval3=getObj('followup_date').value.replace(/^\s+/g, '').replace(/\s+$/g, ''); + + var dateelements1=splitDateVal(dateval1) + var dateelements2=splitDateVal(dateval2) + var dateelements3=splitDateVal(dateval3) + + dd1=dateelements1[0] + mm1=dateelements1[1] + yyyy1=dateelements1[2] + + dd2=dateelements2[0] + mm2=dateelements2[1] + yyyy2=dateelements2[2] + + dd3=dateelements3[0] + mm3=dateelements3[1] + yyyy3=dateelements3[2] + + var date1=new Date() + var date2=new Date() + var date3=new Date() + + date1.setYear(yyyy1) + date1.setMonth(mm1-1) + date1.setDate(dd1) + date1.setHours(starthour) + date1.setMinutes(startmin) + + date2.setYear(yyyy2) + date2.setMonth(mm2-1) + date2.setDate(dd2) + date2.setHours(endhour) + date2.setMinutes(endmin) + + date3.setYear(yyyy3) + date3.setMonth(mm3-1) + date3.setDate(dd3) + + diff_ms = Math.abs(date2.getTime()-date1.getTime())/(1000*60); + hour = Math.floor(diff_ms/(60)); + minute = Math.floor(diff_ms % 60) + document.EditView.duration_hours.value = hour; + document.EditView.duration_minutes.value = minute; + + event_starthour = _2digit(starthour); + event_startmin = _2digit(startmin); + event_endhour = _2digit(endhour); + event_endmin = _2digit(endmin); + document.EditView.time_start.value = event_starthour+':'+event_startmin; + document.EditView.time_end.value = event_endhour+':'+event_endmin; + // Added for Aydin Kurt-Elli requirement START -by Minnie + if (document.EditView.followup.checked == true && document.getElementById('date_table_thirdtd').style.display == 'block') + { + if(!dateValidate('followup_date','Followup Date','OTH')) + { + return false; + } + if(followupformat != '') + { + if(followupformat == 'pm') + { + if(followuphour == 12) + followuphour = 12; + else + followuphour = followuphour + 12; + } + else + { + if(followuphour == 12) + followuphour = 0; + else + followuphour = followuphour; + } + } + + if ( compareDates(date3,'Followup Date',date2,'End Date','GE')) + { + if (date3 <= date2) + { + if((followuphour*60+followupmin) <= (endhour*60+endmin)) + { + alert(alert_arr.FOLLOWUPTIME_GREATER_THAN_STARTTIME); + document.EditView.followup_starthr.focus(); + return false; + } + } + } + else return false; + //modified to set followup end date depends on the event or todo. If it is Event, the difference between followup start date and end date is 1hr. If it is todo then difference is 5mins. + date3.setMinutes(followupmin); + date3.setHours(followuphour); + if(document.EditView.activitytype[0].checked == true) + { + date3.setMinutes(parseInt(date3.getMinutes(),10)+5); + } + if(document.EditView.activitytype[1].checked == true) + { + date3.setMinutes(parseInt(date3.getMinutes(),10)+60); + } + var tempdate = getdispDate(date3); + + followuphour = _2digit(followuphour); + followupmin = _2digit(followupmin); + followupendhour = _2digit(date3.getHours()); + followupendmin = _2digit(date3.getMinutes()); + document.EditView.followup_due_date.value = tempdate; + document.EditView.followup_time_start.value = followuphour+':'+followupmin; + document.EditView.followup_time_end.value = followupendhour+':'+followupendmin; + //end + } + // Added for Aydin Kurt-Elli requirement END -by Minnie --> + + //added to avoid db error while giving characters in the repeat "every n no of day in month" text box + if((getObj("recurringcheck")) && (document.EditView.recurringcheck.checked == true) && (document.EditView.recurringtype.value =="Monthly")) + { + if((document.EditView.repeatMonth[0].checked == true) && ((parseInt(parseFloat(document.EditView.repeatMonth_date.value))!=document.EditView.repeatMonth_date.value) || document.EditView.repeatMonth_date.value=='' || parseInt(document.EditView.repeatMonth_date.value)>'31' || document.EditView.repeatMonth_date.value<='0')) + { + alert(alert_arr.INVALID +' "'+document.EditView.repeatMonth_date.value+'" '); + document.EditView.repeatMonth_date.focus(); + return false; + } + } + //end + + + //added to check Start Date & Time,if Activity Status is Planned.//start + if(document.EditView.eventstatus.value == "Planned") + { + var chkdate=new Date() + chkdate.setMinutes(event_startmin) + chkdate.setHours(event_starthour) + chkdate.setYear(yyyy1) + chkdate.setMonth(mm1-1) + chkdate.setDate(dd1) + if(!comparestartdate(chkdate)) return false; + + } + + } + else + return false; + if(getObj("recurringcheck") && document.EditView.recurringcheck.checked == false) + { + document.EditView.recurringtype.value = '--None--'; + } + return true; + } +} + +function task_check_form() +{ + starthour = parseInt(document.createTodo.starthr.value,10); + startmin = parseInt(document.createTodo.startmin.value,10); + startformat = document.createTodo.startfmt.value; + if(startformat != '') + { + if(startformat == 'pm') + { + if(starthour == 12) + starthour = 12; + else + starthour = starthour + 12; + + } + else + { + if(starthour == 12) + starthour = 0; + else + starthour = starthour; + } + } + starthour = _2digit(starthour); + startmin = _2digit(startmin); + document.createTodo.task_time_start.value = starthour+':'+startmin; + if(document.createTodo.record.value != '') + { + document.createTodo.mode.value = 'edit'; + } + else + { + document.createTodo.mode.value = 'create'; + } + +} + + +function maintask_check_form() +{ + starthour = parseInt(document.EditView.starthr.value,10); + startmin = parseInt(document.EditView.startmin.value,10); + startformat = document.EditView.startfmt.value; + if(startformat != '') + { + if(startformat == 'pm') + { + if(starthour == 12) + starthour = 12; + else + starthour = starthour + 12; + } + else + { + if(starthour == 12) + starthour = 0; + else + starthour = starthour; + } + } + starthour = _2digit(starthour); + startmin = _2digit(startmin); + document.EditView.time_start.value = starthour+':'+startmin; +} + + +var moveupLinkObj,moveupDisabledObj,movedownLinkObj,movedownDisabledObj; + +function userEventSharing(selectedusrid,selcolid) +{ + formSelectColumnString(selectedusrid,selcolid); +} + + +function incUser(avail_users,sel_users) +{ + availListObj=getObj(avail_users) + selectedColumnsObj=getObj(sel_users) + var selectlength=selectedColumnsObj.length + var availlength=availListObj.length + + for (i=0;i= 0) + selectedColumnsObj.remove(selectedColumnsObj.options.selectedIndex) + } + +} + + +// function to delete activity related contact in calendar +var del_ids = new Array(); +function removeActContacts() +{ + var avail_contacts = getObj('parentid'); + // this block is to remove contacts and get deleted contact ids + if(avail_contacts.options.selectedIndex > -1) + { + for(m = 0; m < avail_contacts.options.length; m++) + { + if(avail_contacts.options[m].selected == true) + { + del_ids.push(avail_contacts.options[m].value); + avail_contacts.options[m] = null; + removeActContacts(); + } + } + } + document.EditView.deletecntlist.value = del_ids.join(";"); + + // this block is to get available id list + var avail_ids = new Array(); + for(n=0; n window.innerWidth ){ + leftSide = eval(leftSide) - eval(widthM); + tagName.style.left = leftSide + 'px'; + } + else + tagName.style.left= leftSide + 'px'; + tagName.style.top= topSide + 'px'; + tagName.style.display = 'block'; + tagName.style.visibility = "visible"; + if(type == 'event') + { + var heldstatus = "eventstatus=Held"; + var notheldstatus = "eventstatus=Not Held"; + var activity_mode = "Events"; + var complete = document.getElementById("complete"); + var pending = document.getElementById("pending"); + var postpone = document.getElementById("postpone"); + var actdelete = document.getElementById("actdelete"); + var changeowner = document.getElementById("changeowner"); + var OptionData = document.getElementById('view_Option').options[document.getElementById('view_Option').selectedIndex].value; + + } + if(type == 'todo') + { + var heldstatus = "status=Completed"; + var notheldstatus = "status=Deferred"; + var activity_mode = "Task"; + var complete = document.getElementById("taskcomplete"); + var pending = document.getElementById("taskpending"); + var postpone = document.getElementById("taskpostpone"); + var actdelete = document.getElementById("taskactdelete"); + var changeowner = document.getElementById("taskchangeowner"); + var OptionData = ''; + } + document.getElementById("idlist").value = id; + document.change_owner.hour.value = hour; + document.change_owner.day.value = day; + document.change_owner.view.value = view; + document.change_owner.month.value = month; + document.change_owner.year.value = year; + document.change_owner.subtab.value = type; + if(complete) complete.href="javascript:updateStatus("+id+",'"+heldstatus+"','"+view+"',"+hour+","+day+","+month+","+year+",'"+type+"')"; + if(pending) pending.href="javascript:updateStatus("+id+",'"+notheldstatus+"','"+view+"',"+hour+","+day+","+month+","+year+",'"+type+"')"; + + if(postpone) postpone.href="index.php?module=Calendar&action=EditView&record="+id+"&return_action=index&activity_mode="+activity_mode+"&view="+view+"&hour="+hour+"&day="+day+"&month="+month+"&year="+year+"&viewOption="+OptionData+"&subtab="+type+"&maintab=Calendar"; + + if(actdelete) actdelete.href="javascript:delActivity("+id+",'"+view+"',"+hour+","+day+","+month+","+year+",'"+type+"')"; + + if(changeowner) changeowner.href="javascript:dispLayer('act_changeowner');"; + +} + +function dispLayer(lay) +{ + var tagName = document.getElementById(lay); + tagName.style.visibility = 'visible'; + tagName.style.display = 'block'; +} + +//check whether user form selected or group form selected +function checkgroup() +{ + if($("group_checkbox").checked) + { + document.change_owner.lead_group_owner.style.display = "block"; + document.change_owner.lead_owner.style.display = "none"; + } + else + { + document.change_owner.lead_group_owner.style.display = "none"; + document.change_owner.lead_owner.style.display = "block"; + } +} + +function calendarChangeOwner() +{ + var idlist = document.change_owner.idlist.value; + var view = document.change_owner.view.value; + var day = document.change_owner.day.value; + var month = document.change_owner.month.value; + var year = document.change_owner.year.value; + var hour = document.change_owner.hour.value; + var subtab = document.change_owner.subtab.value; + + //var checked = document.change_owner.user_lead_owner[0].checked; + if($("user_checkbox").checked) + { + var user_id = document.getElementById('lead_owner').options[document.getElementById('lead_owner').options.selectedIndex].value; + var url = 'module=Users&action=updateLeadDBStatus&return_module=Calendar&return_action=ActivityAjax&owner_id='+user_id+'&idlist='+idlist+'&view='+view+'&hour='+hour+'&day='+day+'&month='+month+'&year='+year+'&type=change_owner&owner_type=User'; + } + else + { + var group_id = document.getElementById('lead_group_owner').options[document.getElementById('lead_group_owner').options.selectedIndex].value; + var url = 'module=Users&action=updateLeadDBStatus&return_module=Calendar&return_action=ActivityAjax&owner_id='+group_id+'&idlist='+idlist+'&view='+view+'&hour='+hour+'&day='+day+'&month='+month+'&year='+year+'&type=change_owner&owner_type=Group'; + } + + if(subtab == 'event') + { + var OptionData = $('view_Option').options[$('view_Option').selectedIndex].value; + var eventurl = url+'&viewOption='+OptionData+'&subtab=event&ajax=true'; + + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: eventurl, + onComplete: function(response) { + if(OptionData == 'listview') + { + result = response.responseText.split('####'); + $("total_activities").innerHTML = result[1]; + $("listView").innerHTML=result[0]; + document.EventViewOption.action.value = "index"; + window.document.EventViewOption.submit(); + } + if(OptionData == 'hourview') + { + result = response.responseText.split('####'); + $("total_activities").innerHTML = result[1]; + $("hrView").innerHTML=result[0]; + document.EventViewOption.action.value = "index"; + window.document.EventViewOption.submit(); + } + } + } + ); + } + if(subtab == 'todo') + { + + var todourl = url+'&subtab=todo&ajax=true'; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: todourl, + onComplete: function(response) { + result = response.responseText.split('####'); + $("total_activities").innerHTML = result[1]; + $("mnuTab2").innerHTML=result[0]; + } + } + ); + } +} + +function delActivity(id,view,hour,day,month,year,subtab) +{ + if(subtab == 'event') + { + var OptionData = $('view_Option').options[$('view_Option').selectedIndex].value; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=Users&action=massdelete&return_module=Calendar&return_action=ActivityAjax&idlist='+id+'&view='+view+'&hour='+hour+'&day='+day+'&month='+month+'&year='+year+'&type=activity_delete&viewOption='+OptionData+'&subtab=event&ajax=true', + onComplete: function(response) { + if(OptionData == 'listview') + { + result = response.responseText.split('####'); + $("total_activities").innerHTML = result[1]; + $("listView").innerHTML=result[0]; + } + if(OptionData == 'hourview') + { + result = response.responseText.split('####'); + $("total_activities").innerHTML = result[1]; + $("hrView").innerHTML=result[0]; + } + } + } + ); + } + if(subtab == 'todo') + { + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=Users&action=massdelete&return_module=Calendar&return_action=ActivityAjax&idlist='+id+'&view='+view+'&hour='+hour+'&day='+day+'&month='+month+'&year='+year+'&type=activity_delete&subtab=todo&ajax=true', + onComplete: function(response) { + result = response.responseText.split('####'); + $("total_activities").innerHTML = result[1]; + $("mnuTab2").innerHTML=result[0]; + } + } + ); + } +} + + +/* +* javascript function to display the div tag +* @param divId :: div tag ID +*/ +function cal_show(divId) + +{ + + var id = document.getElementById(divId); + + id.style.visibility = 'visible'; + +} + +function fnAssignTo(){ + var option_Box = document.getElementById('parent_type'); + var option_select = option_Box.options[option_Box.selectedIndex].value; + if(option_select == "Leads" || option_select == "Leads&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "Accounts" || option_select == "Accounts&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "Potentials" || option_select == "Potentials&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "Quotes&action=Popup" || option_select == "Quotes&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "PurchaseOrder" || option_select == "PurchaseOrder&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "SalesOrder" || option_select == "SalesOrder&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "Invoice" || option_select == "Invoice&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else if(option_select == "Campaigns" || option_select == "Campaigns&action=Popup") + { + document.getElementById('leadLay').style.visibility = 'visible'; + } + else{ + document.getElementById('leadLay').style.visibility = 'hidden'; + } + } + +function fnShowPopup(){ + document.getElementById('popupLay').style.display = 'block'; +} + +function fnHidePopup(){ + document.getElementById('popupLay').style.display = 'none'; +} + +function getValidationarr(id,activity_mode,opmode,subtab,viewOption) +{ + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=Calendar&action=ActivityAjax&record='+id+'&activity_mode='+activity_mode+'&ajax=true&type=view&file=DetailView', + onComplete: function(response) { + $("dataArray").innerHTML=response.responseText; + setFieldvalues(opmode,subtab,viewOption); + } + } + ); + +} + +function setFieldvalues(opmode,subtab,viewOption) +{ + var st = document.getElementById('activity_cont'); + eval(st.innerHTML); + if(activity_type == 'Events') + { + document.EditView.viewOption.value = viewOption; + document.EditView.subtab.value = subtab; + for(x=0;x is a contact id + ltext ==> is a contact name +**/ +function addOption(lvalue,ltext) +{ + var optObj = document.createElement('OPTION') + if (browser_ie) optObj.innerText = ltext; + else if(browser_nn4 || browser_nn6) optObj.text = ltext; + else optObj.text = ltext; + optObj.value = lvalue; + document.getElementById('parentid').appendChild(optObj); +} + +function getdispDate(tempDate) +{ + var datefmt = document.EditView.dateformat.value; + var dd = _2digit(parseInt(tempDate.getDate(),10)); + var mm = _2digit(parseInt(tempDate.getMonth(),10)+1); + var yy = tempDate.getFullYear(); + if(datefmt == '%d-%m-%Y') return dd+'-'+mm+'-'+yy; + else if(datefmt == '%m-%d-%Y') return mm+'-'+dd+'-'+yy; + else return yy+'-'+mm+'-'+dd; +} diff --git a/oss/vtiger/trunk/modules/Calendar/updateCalendarSharing.php b/oss/vtiger/trunk/modules/Calendar/updateCalendarSharing.php new file mode 100644 index 00000000..a1c09e71 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/updateCalendarSharing.php @@ -0,0 +1,45 @@ +pquery($delquery, array($_REQUEST["current_userid"])); + +$selectedid = $_REQUEST['shar_userid']; +$sharedid = explode (";",$selectedid); +if(isset($sharedid) && $sharedid != null) +{ + foreach($sharedid as $sid) + { + if($sid != '') + { + $sql = "insert into vtiger_sharedcalendar values (?,?)"; + $adb->pquery($sql, array($_REQUEST["current_userid"], $sid)); + } + } +} +if(isset($_REQUEST['start_hour']) && $_REQUEST['start_hour'] != '') +{ + $sql = "update vtiger_users set start_hour=? where id=?"; + $adb->pquery($sql, array($_REQUEST['start_hour'], $current_user->id)); +} + +$sql = "update vtiger_users set hour_format=? where id=?"; +$adb->pquery($sql, array($hour_format, $current_user->id)); +RecalculateSharingRules(); +header("Location: index.php?action=index&module=Calendar&view=".vtlib_purify($_REQUEST['view'])."&hour=".vtlib_purify($_REQUEST['hour'])."&day=".vtlib_purify($_REQUEST['day'])."&month=".vtlib_purify($_REQUEST['month'])."&year=".vtlib_purify($_REQUEST['year'])."&viewOption=".vtlib_purify($_REQUEST['viewOption'])."&subtab=".vtlib_purify($_REQUEST['subtab'])."&parenttab=".getParentTab()); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calendar/updateRelations.php b/oss/vtiger/trunk/modules/Calendar/updateRelations.php new file mode 100644 index 00000000..b6e17de7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calendar/updateRelations.php @@ -0,0 +1,64 @@ +pquery($sql, array($id, $_REQUEST["parentid"])); + } + } + header("Location: index.php?action=CallRelatedList&module=Calendar&activity_mode=Events&record=".$record); + +} +elseif(isset($_REQUEST['entityid']) && $_REQUEST['entityid'] != '' && $_REQUEST['destination_module'] == 'Contacts') +{ + $record = vtlib_purify($_REQUEST["parentid"]); + $sql = "insert into vtiger_cntactivityrel values (?,?)"; + $adb->pquery($sql, array($_REQUEST["entityid"], $_REQUEST["parentid"])); + header("Location: index.php?action=DetailView&module=Calendar&activity_mode=Events&record=".$record); +} + +//This if for adding the vtiger_users +if(isset($_REQUEST['idlist']) && $_REQUEST['idlist'] != '' && $_REQUEST['destination_module'] == 'Users') +{ + //split the string and store in an array + $storearray = explode (";",$idlist); + foreach($storearray as $id) + { + if($id != '') + { + $record = vtlib_purify($_REQUEST['parentid']); + $sql = "insert into vtiger_salesmanactivityrel values (?,?)"; + $adb->pquery($sql, array($id, $_REQUEST["parentid"])); + } + } + header("Location: index.php?action=DetailView&module=Calendar&activity_mode=Events&record=".$record); +} +elseif(isset($_REQUEST['entityid']) && $_REQUEST['entityid'] != '' && $_REQUEST['destination_module'] == 'Users') +{ + $record = vtlib_purify($_REQUEST['parentid']); + $sql = "insert into vtiger_salesmanactivityrel values (?,?)"; + $adb->pquery($sql, array($_REQUEST["entityid"], $_REQUEST["parentid"])); + header("Location: index.php?action=DetailView&module=Calendar&activity_mode=Events&record=".$record); + +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Calls/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Calls/language/zh_cn.lang.php new file mode 100644 index 00000000..4cd0de56 --- /dev/null +++ b/oss/vtiger/trunk/modules/Calls/language/zh_cn.lang.php @@ -0,0 +1,45 @@ + '电话', + 'LBL_MODULE_TITLE' => '电话: 首页', + 'LBL_SEARCH_FORM_TITLE' => '查找电话', + 'LBL_LIST_FORM_TITLE' => '电话列表', + 'LBL_NEW_FORM_TITLE' => '计划客户电话', + 'LBL_LIST_CLOSE' => '完成', + 'LBL_LIST_SUBJECT' => '主题', + 'LBL_LIST_CONTACT' => '联系人', + 'LBL_LIST_RELATED_TO' => '相关对象', + 'LBL_LIST_DATE' => '开始日期', + 'LBL_LIST_TIME' => '开始时间', + 'LBL_LIST_DURATION' => '时间', + 'LBL_SUBJECT' => '主题:', + 'LBL_CONTACT_NAME' => '联系人:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息:', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_STATUS' => '状态:', + 'LBL_DATE' => '开始日期:', + 'LBL_DURATION' => '时间:', + 'LBL_HOURS_MINUTES' => '(小时/分钟)', + 'LBL_CALL' => '电话:', + 'LBL_DATE_TIME' => '开始日期与时间:', + 'LBL_TIME' => '开始时间:', + 'LBL_HOURS_ABBREV' => '时', + 'LBL_MINSS_ABBREV' => '分', + 'LBL_COLON' => ':', + 'LBL_DEFAULT_STATUS' => '已计划', + 'LNK_NEW_LEAD' => '新增线索', + 'LNK_NEW_CONTACT' => '新增联系人', + 'LNK_NEW_ACCOUNT' => '新增客户', + 'LNK_NEW_OPPORTUNITY' => '新增商机', + 'LNK_NEW_CASE' => '新增拜访', + 'LNK_NEW_NOTE' => '新增备忘录', + 'LNK_NEW_CALL' => '新增电话', + 'LNK_NEW_EMAIL' => '新增Email', + 'LNK_NEW_MEETING' => '新增会议', + 'LNK_NEW_TASK' => '新增任务', + 'ERR_DELETE_RECORD' => '必须指定纪录编号才能删除客户.', + 'NTC_REMOVE_INVITEE' => '您确定要删除这个电话邀请吗?', + 'LBL_INVITEE' => '*受邀者', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/CallRelatedList.php b/oss/vtiger/trunk/modules/Campaigns/CallRelatedList.php new file mode 100644 index 00000000..b9633ed4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/CallRelatedList.php @@ -0,0 +1,104 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['campaignname']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings,$adb; + global $theme; + global $currentModule; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array=getRelatedLists($currentModule,$focus); + + // vtlib customization: Related module could be disabled, check it + if(isset($related_array)) { + foreach($related_array as $mod_key=>$mod_val) { + if($mod_key == "Contacts" || $mod_key == "Leads") { + $rel_checked=$_REQUEST[$mod_key.'_all']; + $rel_check_split=explode(";",$rel_checked); + if (is_array($mod_val)) { + $mod_val["checked"]=array(); + if (isset($mod_val['entries'])) { + foreach($mod_val['entries'] as $key=>$val) { + if(in_array($key,$rel_check_split)) + $related_array[$mod_key]["checked"][$key] = 'checked'; + else + $related_array[$mod_key]["checked"][$key] = ''; + } + } + } + } + } + } + // END + $smarty->assign("RELATEDLISTS", $related_array); + + require_once('modules/CustomView/CustomView.php'); + + // 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 + + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("CATEGORY",$category); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("ID",$focus->id); + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$app_strings['Campaign']); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + + if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("RelatedListContents.tpl"); + else + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/Campaigns.js b/oss/vtiger/trunk/modules/Campaigns/Campaigns.js new file mode 100644 index 00000000..d2d4935a --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/Campaigns.js @@ -0,0 +1,42 @@ +/********************************************************************************* + +** 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. + ********************************************************************************/ + + + +function set_return_specific_campaign(campaign_id, campaign_name) { + if(document.getElementById('from_link').value != '') { + window.opener.document.QcEditView.campaignname.value = campaign_name; + window.opener.document.QcEditView.campaignid.value = campaign_id; + } else { + window.opener.document.EditView.campaignname.value = campaign_name; + window.opener.document.EditView.campaignid.value = campaign_id; +} +} + +function set_return(product_id, product_name) { + if(document.getElementById('from_link').value != '') { + window.opener.document.QcEditView.parent_name.value = product_name; + window.opener.document.QcEditView.parent_id.value = product_id; + } else { + window.opener.document.EditView.parent_name.value = product_name; + window.opener.document.EditView.parent_id.value = product_id; +} +} + +function set_return_todo(product_id, product_name) { + if(document.getElementById('from_link').value != '') { + window.opener.document.QcEditView.task_parent_name.value = product_name; + window.opener.document.QcEditView.task_parent_id.value = product_id; + } else { + window.opener.document.createTodo.task_parent_name.value = product_name; + window.opener.document.createTodo.task_parent_id.value = product_id; +} +} + diff --git a/oss/vtiger/trunk/modules/Campaigns/Campaigns.php b/oss/vtiger/trunk/modules/Campaigns/Campaigns.php new file mode 100644 index 00000000..26f2367f --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/Campaigns.php @@ -0,0 +1,466 @@ +'crmid','vtiger_campaign'=>'campaignid','vtiger_campaignscf'=>'campaignid'); + /** + * Mandatory table for supporting custom fields. + */ + var $customFieldTable = Array('vtiger_campaignscf', 'campaignid'); + var $column_fields = Array(); + + var $sortby_fields = Array('campaignname','smownerid','campaigntype','productname','expectedrevenue','closingdate','campaignstatus','expectedresponse','targetaudience','expectedcost'); + + var $list_fields = Array( + 'Campaign Name'=>Array('campaign'=>'campaignname'), + 'Campaign Type'=>Array('campaign'=>'campaigntype'), + 'Campaign Status'=>Array('campaign'=>'campaignstatus'), + 'Expected Revenue'=>Array('campaign'=>'expectedrevenue'), + 'Expected Close Date'=>Array('campaign'=>'closingdate'), + 'Assigned To' => Array('crmentity'=>'smownerid') + ); + + var $list_fields_name = Array( + 'Campaign Name'=>'campaignname', + 'Campaign Type'=>'campaigntype', + 'Campaign Status'=>'campaignstatus', + 'Expected Revenue'=>'expectedrevenue', + 'Expected Close Date'=>'closingdate', + 'Assigned To'=>'assigned_user_id' + ); + + var $list_link_field= 'campaignname'; + //Added these variables which are used as default order by and sortorder in ListView + var $default_order_by = 'crmid'; + var $default_sort_order = 'DESC'; + + //var $groupTable = Array('vtiger_campaigngrouprelation','campaignid'); + + var $search_fields = Array( + 'Campaign Name'=>Array('vtiger_campaign'=>'campaignname'), + 'Campaign Type'=>Array('vtiger_campaign'=>'campaigntype'), + ); + + var $search_fields_name = Array( + 'Campaign Name'=>'campaignname', + 'Campaign Type'=>'campaigntype', + ); + // Used when enabling/disabling the mandatory fields for the module. + // Refers to vtiger_field.fieldname values. + var $mandatory_fields = Array('campaignname','createdtime' ,'modifiedtime','assigned_user_id'); + + function Campaigns() + { + $this->log =LoggerManager::getLogger('campaign'); + $this->db = PearDatabase::getInstance(); + $this->column_fields = getColumnFields('Campaigns'); + } + + /** Function to handle module specific operations when saving a entity + */ + function save_module($module) + { + } + + // Mike Crowe Mod --------------------------------------------------------Default ordering for us + /** + * Function to get sort order + * return string $sorder - sortorder string either 'ASC' or 'DESC' + */ + function getSortOrder() + { + global $log; + $log->debug("Entering getSortOrder() method ..."); + if(isset($_REQUEST['sorder'])) + $sorder = $this->db->sql_escape_string($_REQUEST['sorder']); + else + $sorder = (($_SESSION['CAMPAIGN_SORT_ORDER'] != '')?($_SESSION['CAMPAIGN_SORT_ORDER']):($this->default_sort_order)); + + $log->debug("Exiting getSortOrder method ..."); + return $sorder; + } + + /** + * Function to get order by + * return string $order_by - fieldname(eg: 'campaignname') + */ + function getOrderBy() + { + global $log; + $log->debug("Entering getOrderBy() method ..."); + + $use_default_order_by = ''; + if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) { + $use_default_order_by = $this->default_order_by; + } + + if (isset($_REQUEST['order_by'])) + $order_by = $this->db->sql_escape_string($_REQUEST['order_by']); + else + $order_by = (($_SESSION['CAMPAIGN_ORDER_BY'] != '')?($_SESSION['CAMPAIGN_ORDER_BY']):($use_default_order_by)); + + $log->debug("Exiting getOrderBy method ..."); + return $order_by; + } + // Mike Crowe Mod -------------------------------------------------------- + + /** + * Function to get Campaign related Contacts + * @param integer $id - campaignid + * returns related Contacts record in array format + */ + function get_contacts($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule; + $log->debug("Entering get_contacts(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + if($singlepane_view == 'true') + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + else + $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id; + + $button = ''; + + // Send mail button for selected Leads + $button .= ""; + $button .= '    '; + + /* To get Leads CustomView -START */ + require_once('modules/CustomView/CustomView.php'); + $lhtml = ""; + /* To get Leads CustomView -END */ + + $button .= $lhtml.""; + $button .= '    '; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') { + $button .= " "; + } + } + + $query = "SELECT vtiger_contactdetails.accountid, vtiger_account.accountname, + CASE when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name , + vtiger_contactdetails.contactid, vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, vtiger_contactdetails.title, + vtiger_contactdetails.department, vtiger_contactdetails.email, vtiger_contactdetails.phone, vtiger_crmentity.crmid, + vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime + FROM vtiger_contactdetails + INNER JOIN vtiger_campaigncontrel ON vtiger_campaigncontrel.contactid = vtiger_contactdetails.contactid + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid=vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id + LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_contactdetails.accountid + WHERE vtiger_campaigncontrel.campaignid = ".$id." AND vtiger_crmentity.deleted=0"; + + $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_contacts method ..."); + return $return_value; + } + + /** + * Function to get Campaign related Leads + * @param integer $id - campaignid + * returns related Leads record in array format + */ + function get_leads($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view, $currentModule; + $log->debug("Entering get_leads(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + if($singlepane_view == 'true') + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + else + $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id; + + $button = ''; + + // Send mail button for selected Leads + $button .= ""; + $button .= '    '; + + /* To get Leads CustomView -START */ + require_once('modules/CustomView/CustomView.php'); + $lhtml = ""; + /* To get Leads CustomView -END */ + + $button .= $lhtml.""; + $button .= '    '; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') { + $button .= " "; + } + } + + $query = "SELECT vtiger_leaddetails.*, vtiger_crmentity.crmid,vtiger_leadaddress.phone,vtiger_leadsubdetails.website, + CASE when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + vtiger_crmentity.smownerid FROM vtiger_leaddetails + INNER JOIN vtiger_campaignleadrel ON vtiger_campaignleadrel.leadid=vtiger_leaddetails.leadid + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadsubdetails ON vtiger_leadsubdetails.leadsubscriptionid = vtiger_leaddetails.leadid + INNER JOIN vtiger_leadaddress ON vtiger_leadaddress.leadaddressid = vtiger_leadsubdetails.leadsubscriptionid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id + LEFT JOIN vtiger_groups ON vtiger_groups.groupid=vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted=0 AND vtiger_campaignleadrel.campaignid = ".$id; + + $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_leads method ..."); + return $return_value; + } + + /** + * Function to get Campaign related Potentials + * @param integer $id - campaignid + * returns related potentials record in array format + */ + function get_opportunities($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule,$current_user; + $log->debug("Entering get_opportunities(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + if($singlepane_view == 'true') + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + else + $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id; + + $button = ''; + + if($actions && getFieldVisibilityPermission($related_module,$current_user->id,'campaignid') == '0') { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') { + $button .= " "; + } + } + + $query = "SELECT CASE when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + vtiger_potential.related_to, vtiger_account.accountname, vtiger_potential.potentialid, vtiger_potential.potentialname, + vtiger_potential.potentialtype, vtiger_potential.sales_stage, vtiger_potential.amount, vtiger_potential.closingdate, + vtiger_crmentity.crmid, vtiger_crmentity.smownerid FROM vtiger_campaign + INNER JOIN vtiger_potential ON vtiger_campaign.campaignid = vtiger_potential.campaignid + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_potential.potentialid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid=vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id=vtiger_crmentity.smownerid + LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_potential.related_to + WHERE vtiger_campaign.campaignid = ".$id." AND vtiger_crmentity.deleted=0"; + + $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_opportunities method ..."); + return $return_value; + } + + /** + * Function to get Campaign related Activities + * @param integer $id - campaignid + * returns related activities record in array format + */ + function get_activities($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule,$current_user; + $log->debug("Entering get_activities(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/Activity.php"); + $other = new Activity(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + if($singlepane_view == 'true') + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + else + $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id; + + $button = ''; + + $button .= ''; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') { + $button .= " "; + } + } + + $query = "SELECT vtiger_contactdetails.lastname, + vtiger_contactdetails.firstname, + vtiger_contactdetails.contactid, + vtiger_activity.*, + vtiger_seactivityrel.*, + vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_crmentity.modifiedtime, + CASE when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + vtiger_recurringevents.recurringtype + FROM vtiger_activity + INNER JOIN vtiger_seactivityrel + ON vtiger_seactivityrel.activityid = vtiger_activity.activityid + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid=vtiger_activity.activityid + LEFT JOIN vtiger_cntactivityrel + ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_contactdetails + ON vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT OUTER JOIN vtiger_recurringevents + ON vtiger_recurringevents.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + WHERE vtiger_seactivityrel.crmid=".$id." + AND vtiger_crmentity.deleted = 0 + AND (activitytype = 'Task' + OR activitytype !='Emails')"; + + $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_activities method ..."); + return $return_value; + + } + + /* + * Function to get the secondary query part of a report + * @param - $module primary module name + * @param - $secmodule secondary module name + * returns the query string formed on fetching the related data for report for secondary module + */ + function generateReportsSecQuery($module,$secmodule){ + $query = $this->getRelationQuery($module,$secmodule,"vtiger_campaign","campaignid"); + $query .=" left join vtiger_crmentity as vtiger_crmentityCampaigns on vtiger_crmentityCampaigns.crmid=vtiger_campaign.campaignid and vtiger_crmentityCampaigns.deleted=0 + left join vtiger_products as vtiger_productsCampaigns on vtiger_campaign.product_id = vtiger_productsCampaigns.productid + left join vtiger_campaignscf on vtiger_campaignscf.campaignid = vtiger_crmentityCampaigns.crmid + left join vtiger_groups as vtiger_groupsCampaigns on vtiger_groupsCampaigns.groupid = vtiger_crmentityCampaigns.smownerid + left join vtiger_users as vtiger_usersCampaigns on vtiger_usersCampaigns.id = vtiger_crmentityCampaigns.smownerid"; + + return $query; + } + + /* + * Function to get the relation tables for related modules + * @param - $secmodule secondary module name + * returns the array with table names and fieldnames storing relations between module and this module + */ + function setRelationTables($secmodule){ + $rel_tables = array ( + "Contacts" => array("vtiger_campaigncontrel"=>array("campaignid","contactid"),"vtiger_campaign"=>"campaignid"), + "Leads" => array("vtiger_campaignleadrel"=>array("campaignid","leadid"),"vtiger_campaign"=>"campaignid"), + "Potentials" => array("vtiger_potential"=>array("campaignid","potentialid"),"vtiger_campaign"=>"campaignid"), + "Calendar" => array("vtiger_seactivityrel"=>array("crmid","activityid"),"vtiger_campaign"=>"campaignid"), + "Products" => array("vtiger_campaign"=>array("campaignid","product_id")), + ); + return $rel_tables[$secmodule]; + } + + // Function to unlink an entity with given Id from another entity + function unlinkRelationship($id, $return_module, $return_id) { + global $log; + if(empty($return_module) || empty($return_id)) return; + + if($return_module == 'Leads') { + $sql = 'DELETE FROM vtiger_campaignleadrel WHERE campaignid=? AND leadid=?'; + $this->db->pquery($sql, array($id, $return_id)); + } elseif($return_module == 'Contacts') { + $sql = 'DELETE FROM vtiger_campaigncontrel WHERE campaignid=? AND contactid=?'; + $this->db->pquery($sql, array($id, $return_id)); + } else { + $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)'; + $params = array($id, $return_module, $return_id, $id, $return_module, $return_id); + $this->db->pquery($sql, $params); + } + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/CampaignsAjax.php b/oss/vtiger/trunk/modules/Campaigns/CampaignsAjax.php new file mode 100644 index 00000000..e2d11f6b --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/CampaignsAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Campaigns/CustomView.php b/oss/vtiger/trunk/modules/Campaigns/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Campaigns/Delete.php b/oss/vtiger/trunk/modules/Campaigns/Delete.php new file mode 100644 index 00000000..9dddc075 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/Delete.php @@ -0,0 +1,39 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/DetailView.php b/oss/vtiger/trunk/modules/Campaigns/DetailView.php new file mode 100644 index 00000000..cd82717d --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/DetailView.php @@ -0,0 +1,107 @@ +retrieve_entity_info($_REQUEST['record'],"Campaigns"); + $focus->name=$focus->column_fields['campaignname']; + $focus->id = $_REQUEST['record']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; +} +global $app_strings,$mod_strings,$theme,$currentModule,$default_module_view,$adb; + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("SINGLE_MOD",'Campaign'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +if(isPermitted("Campaigns","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("Campaigns","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +// 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 + +$tabid = getTabid("Campaigns"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("SinglePane_View", $singlepane_view); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("DetailView.tpl"); + +$focus->id = $_REQUEST['record']; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/DetailViewAjax.php b/oss/vtiger/trunk/modules/Campaigns/DetailViewAjax.php new file mode 100644 index 00000000..31f31673 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/DetailViewAjax.php @@ -0,0 +1,45 @@ +retrieve_entity_info($crmid,"Campaigns"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Campaigns"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/EditView.php b/oss/vtiger/trunk/modules/Campaigns/EditView.php new file mode 100644 index 00000000..fb88c563 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/EditView.php @@ -0,0 +1,131 @@ +assign("SEARCH", $searchurl); +//4600 ends + + +if(isset($_REQUEST['record']) && $_REQUEST['record'] !='') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Campaigns"); + $focus->name=$focus->column_fields['campaignname']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $smarty->assign("BASBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS')); +} + +$smarty->assign("OP_MODE",$disp_view); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Campaign'); + + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); + +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} +$smarty->assign("ID", $focus->id); +if($focus->mode == 'edit') +{ + $smarty->assign("MODE", $focus->mode); + $smarty->assign("OLDSMOWNERID", $focus->column_fields['assigned_user_id']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); +} + +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['product_id'])) +$smarty->assign("PRODUCTID", vtlib_purify($_REQUEST['product_id'])); +if (isset($_REQUEST['return_viewname'])) +$smarty->assign("RETURN_VIEWNAME", vtlib_purify($_REQUEST['return_viewname'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +$tabid = getTabid("Campaigns"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 '
'. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +if($focus->mode == 'edit') + $smarty->display("salesEditView.tpl"); +else + $smarty->display("CreateView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/ListView.php b/oss/vtiger/trunk/modules/Campaigns/ListView.php new file mode 100644 index 00000000..c5d65dab --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/ListView.php @@ -0,0 +1,262 @@ +initSortbyField('Campaigns'); +// END +$category = getParentTab(); +$smarty = new vtigerCRM_Smarty; +$other_text = Array(); +$url_string = ''; // assigning http url string + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to Change/Delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} + +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['CAMPAIGN_ORDER_BY'] = $order_by; +$_SESSION['CAMPAIGN_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + + + +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); +} + +//<<<>>>>>> +$oCustomView = new CustomView("Campaigns"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +$smarty->assign("CHANGE_OWNER",getUserslist()); +$smarty->assign("CHANGE_GROUP_OWNER",getGroupslist()); +//<<<<>>>> + +if($viewid != 0) +{ + $CActionDtls = $oCustomView->getCustomActionDetails($viewid); +} +elseif($viewid ==0) +{ + echo "
"; + echo "
+ + + + + + + + + +
+ $app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} +// Buttons and View options +if(isPermitted('Campaigns','Delete','') == 'yes') +{ + $other_text ['del']=$app_strings[LBL_MASS_DELETE]; +} +if(isPermitted('Campaigns','EditView','') == 'yes') +{ + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; + $other_text['c_owner'] = $app_strings[LBL_CHANGE_OWNER]; +} +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("BUTTONS",$other_text); +$smarty->assign("CATEGORY",$category); +$smarty->assign("SINGLE_MOD",'Campaign'); + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Campaigns"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Campaigns"); +} +else +{ + $list_query = getListQuery("Campaigns"); +} +//<<<<<<<>>>>>>>> + +if(isset($where) && $where != '') +{ + $list_query .= ' and '.$where; +} + +//sort by "assignedto" and default sort by "ticketid"(DESC) +if(isset($order_by) && $order_by != '') +{ + if($order_by == 'smownerid') + { + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY user_name'; + $list_query .= ' ORDER BY user_name '.$sorder; + } + else + { + $tablename = getTableNameForField('Campaigns',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY '.$tablename.$order_by; + + $list_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } +} +else +{ + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY vtiger_campaign.campaignid'; + $list_query .= ' ORDER BY vtiger_campaign.campaignid DESC'; +} + +//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); + +//mass merge for word templates -- *Raj*17/11 +while($row = $adb->fetch_array($list_result)) +{ + $ids[] = $row["crmid"]; +} +if(isset($ids)) +{ + $smarty->assign("ALLIDS", implode($ids,";")); +} + +//Retreive the List View Table Header +if($viewid !='') + $url_string .="&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"Campaigns",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search = getSearchListHeaderValues($focus,"Campaigns",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER",$listview_header_search); + +$listview_entries = getListViewEntries($focus,"Campaigns",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); + +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Campaigns","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','campaignname','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); + +$smarty->assign("NAVIGATION", $navigationOutput); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/ListViewPagging.php b/oss/vtiger/trunk/modules/Campaigns/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/LoadList.php b/oss/vtiger/trunk/modules/Campaigns/LoadList.php new file mode 100644 index 00000000..9a18b28c --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/LoadList.php @@ -0,0 +1,38 @@ +query($cvObj->getModifiedCvListQuery(vtlib_purify($_REQUEST["cvid"]),$listquery,vtlib_purify($_REQUEST["list_type"]))); + +if($_REQUEST["list_type"] == "Leads"){ + $reltable = "vtiger_campaignleadrel"; + $relid = "leadid"; +} +elseif($_REQUEST["list_type"] == "Contacts"){ + $reltable = "vtiger_campaigncontrel"; + $relid = "contactid"; +} + +while($row=$adb->fetch_array($rs)) { + $sql = "delete from $reltable where $relid = ? and campaignid = ?"; + $adb->pquery($sql, array($row["crmid"], $_REQUEST['return_id'])); + $adb->pquery("INSERT INTO ".$reltable." VALUES(?,?)", array($_REQUEST["return_id"], $row["crmid"])); +} + +header("Location: index.php?module=Campaigns&action=CampaignsAjax&file=CallRelatedList&ajax=true&record=".vtlib_purify($_REQUEST['return_id'])); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/MassEdit.php b/oss/vtiger/trunk/modules/Campaigns/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/MassEditSave.php b/oss/vtiger/trunk/modules/Campaigns/MassEditSave.php new file mode 100644 index 00000000..0e1f2a6f --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/Popup.php b/oss/vtiger/trunk/modules/Campaigns/Popup.php new file mode 100644 index 00000000..98ea8ece --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/Popup.php @@ -0,0 +1,23 @@ + diff --git a/oss/vtiger/trunk/modules/Campaigns/QuickCreate.php b/oss/vtiger/trunk/modules/Campaigns/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Campaigns/Save.php b/oss/vtiger/trunk/modules/Campaigns/Save.php new file mode 100644 index 00000000..b9a717f7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/Save.php @@ -0,0 +1,80 @@ +id); + $rate_symbol = getCurrencySymbolandCRate($currencyid); + $rate = $rate_symbol['rate']; +//added to fix 4600 +$search=vtlib_purify($_REQUEST['search_url']); +setObjectValuesFromRequest($focus); + +if(isset($_REQUEST['expectedrevenue'])) +{ + $value = convertToDollar($_REQUEST['expectedrevenue'],$rate); + $focus->column_fields['expectedrevenue'] = $value; +} +if(isset($_REQUEST['budgetcost'])) +{ + $value = convertToDollar($_REQUEST['budgetcost'],$rate); + $focus->column_fields['budgetcost'] = $value; +} +if(isset($_REQUEST['actualcost'])) +{ + $value = convertToDollar($_REQUEST['actualcost'],$rate); + $focus->column_fields['actualcost'] = $value; +} +if(isset($_REQUEST['actualroi'])) +{ + $value = convertToDollar($_REQUEST['actualroi'],$rate); + $focus->column_fields['actualroi'] = $value; +} +if(isset($_REQUEST['expectedroi'])) +{ + $value = convertToDollar($_REQUEST['expectedroi'],$rate); + $focus->column_fields['expectedroi'] = $value; +} + +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("Campaigns"); +$return_id = $focus->id; + +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Campaigns"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_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); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/Settings.php b/oss/vtiger/trunk/modules/Campaigns/Settings.php new file mode 100644 index 00000000..48a80c0b --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/Settings.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/TagCloud.php b/oss/vtiger/trunk/modules/Campaigns/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Campaigns/UnifiedSearch.php b/oss/vtiger/trunk/modules/Campaigns/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Campaigns/index.php b/oss/vtiger/trunk/modules/Campaigns/index.php new file mode 100644 index 00000000..da92b36b --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/index.php @@ -0,0 +1,17 @@ + diff --git a/oss/vtiger/trunk/modules/Campaigns/language/en_us.lang.php b/oss/vtiger/trunk/modules/Campaigns/language/en_us.lang.php new file mode 100644 index 00000000..349b78e9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/language/en_us.lang.php @@ -0,0 +1,91 @@ +'Campaign Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_EXPECTATIONS_AND_ACTUALS'=>'Expectations & Actuals', + +'Campaign Name'=>'Campaign Name', +'Campaign Type'=>'Campaign Type', +'Campaign Status'=>'Campaign Status', +'Campaign ID'=>'Campaign ID', +'Expected Close Date'=>'Expected Close Date', +'Expected Revenue'=>'Expected Revenue', +'Budget Cost'=>'Budget Cost', +'Actual Cost'=>'Actual Cost', +'Expected Response'=>'Expected Response', +'Assigned To'=>'Assigned To', +'Num Sent'=>'Num Sent', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Description'=>'Description', +'Product'=>'Product', +'Target Audience'=>'Target Audience', +'TargetSize'=>'Target Size', +'Sponsor'=>'Sponsor', + +'Expected Sales Count'=>'Expected Sales Count', +'Expected Response Count'=>'Expected Response Count', +'Expected ROI'=>'Expected ROI', + +'Actual Sales Count'=>'Actual Sales Count', +'Actual Response Count'=>'Actual Response Count', +'Actual ROI'=>'Actual ROI', +'Select One'=>'Select One', +'LBL_LOAD_LIST'=>'Load List', + +//Added for existing Picklist Entries + +'Conference'=>'Conference', +'Webinar'=>'Webinar', +'Trade Show'=>'Trade Show', +'Public Relations'=>'Public Relations', +'Partners'=>'Partners', +'Referral Program'=>'Referral Program', +'Advertisement'=>'Advertisement', +'Banner Ads'=>'Banner Ads', +'Direct Mail'=>'Direct Mail', +'Email'=>'Email', +'Telemarketing'=>'Telemarketing', +'Others'=>'Others', + +'Planning'=>'Planning', +'Active'=>'Active', +'Inactive'=>'Inactive', +'Complete'=>'Complete', +'Cancelled'=>'Cancelled', + +'Excellent'=>'Excellent', +'Good'=>'Good', +'Average'=>'Average', +'Poor'=>'Poor', + +//Module Sequence Numbering +'Campaign No'=>'Campaign No', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Campaigns/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Campaigns/language/zh_cn.lang.php new file mode 100644 index 00000000..90bc7553 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/language/zh_cn.lang.php @@ -0,0 +1,92 @@ + '活动信息', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + 'LBL_DESCRIPTION_INFORMATION' => '说明信息', + 'LBL_EXPECTATIONS_AND_ACTUALS' => '预估与实际', + + 'Campaign Name' => '活动名称', + 'Campaign Type' => '活动类型', + 'Campaign Status' => '活动状态', + 'Campaign ID' => '活动编号', + 'Expected Close Date' => '预期结束日期', + 'Expected Revenue' => '预期收益', + 'Budget Cost' => '估计成本', + 'Actual Cost' => '实际成本', + 'Expected Response' => '预期反应', + 'Assigned To' => '负责人', + 'Num Sent' => '寄送数量', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Description' => '说明', + 'Product' => '产品', + 'Target Audience' => '目标族群', + 'TargetSize' => '目标规模', + 'Sponsor' => '赞助商', + + + 'Expected Sales Count' => '预期销售数量', +'Expected Response Count' => '预期回应数量', + 'Expected ROI' => '预期收益', + + 'Actual Sales Count' => '实际销售数量', + 'Actual Response Count' => '实际回应数量', + 'Actual ROI' => '实际收益', + 'Select One' => '选择一个', + 'LBL_LOAD_LIST' => '读取清单', + +//Added for existing Picklist Entries + + 'Conference' => '研讨会', + 'Webinar' => '网络发表会', + 'Trade Show' => '贸易展览', + 'Public Relations' => '公众关系', + 'Partners' => '伙伴', + 'Referral Program' => '介绍活动', + 'Advertisement' => '广告', + 'Banner Ads' => '网站广告', + 'Direct Mail' => '邮件营销', + 'Email' => '电子邮件', + 'Telemarketing' => '电话营销', + 'Others' => '其它', + +'Planning' => '规划中', + 'Active' => '启用', + 'Inactive' => '停用', + 'Complete' => '完成', + 'Cancelled' => '取消', + + 'Excellent' => '极佳', + 'Good' => '好', + 'Average' => '平均', + 'Poor' => '差', + +//Module Sequence Numbering +'Campaign No'=>'Campaign No', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Campaigns/updateRelations.php b/oss/vtiger/trunk/modules/Campaigns/updateRelations.php new file mode 100644 index 00000000..1f9f4cf3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Campaigns/updateRelations.php @@ -0,0 +1,57 @@ +pquery($sql, array($forCRMRecord, $id)); + } else { + $focus->save_related_module($currentModule, $forCRMRecord, $update_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Cases/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Cases/language/zh_cn.lang.php new file mode 100644 index 00000000..fbf596e9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Cases/language/zh_cn.lang.php @@ -0,0 +1,39 @@ + '拜访', + 'LBL_MODULE_TITLE' => '拜访:首页', + 'LBL_SEARCH_FORM_TITLE' => '查找拜访', + 'LBL_LIST_FORM_TITLE' => '拜访列表', + 'LBL_NEW_FORM_TITLE' => '新增拜访', + 'LBL_CONTACT_CASE_TITLE' => '拜访联系人:', + 'LBL_SUBJECT' => '主题:', + 'LBL_CASE' => '拜访:', + 'LBL_CASE_NUMBER' => '拜访编号:', + 'LBL_NUMBER' => '编号:', + 'LBL_STATUS' => '状态:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_CONTACT_NAME' => '联系人姓名:', + 'LBL_CASE_SUBJECT' => '事件主题:', + 'LBL_CONTACT_ROLE' => '角色:', + 'LBL_LIST_NUMBER' => '编号', + 'LBL_LIST_SUBJECT' => '主题', + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_LIST_STATUS' => '状态', + 'LBL_LIST_LAST_MODIFIED' => '最新修改', + 'LBL_INVITEE' => '*受邀者', + 'LNK_NEW_CONTACT' => '新增联系人', + 'LNK_NEW_LEAD' => '新增线索', + 'LNK_NEW_ACCOUNT' => '新增客户', + 'LNK_NEW_OPPORTUNITY' => '新增商机', + 'LNK_NEW_CASE' => '新增拜访', + 'LNK_NEW_NOTE' => '新增备忘录', + 'LNK_NEW_CALL' => '新增电话', + 'LNK_NEW_EMAIL' => '新增Email', + 'LNK_NEW_MEETING' => '新增会议', + 'LNK_NEW_TASK' => '新增任务', + 'NTC_REMOVE_INVITEE' => '*您确定要从拜访中移除这个联系人?', + 'ERR_DELETE_RECORD' => '必须指定记录编号才能删除客户.', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Contacts/CallRelatedList.php b/oss/vtiger/trunk/modules/Contacts/CallRelatedList.php new file mode 100644 index 00000000..8c8b9ef6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/CallRelatedList.php @@ -0,0 +1,101 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['firstname'].' '.$focus->column_fields['lastname']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $adb; + $sql = $adb->pquery('select accountid from vtiger_contactdetails where contactid=?', array($focus->id)); + $accountid = $adb->query_result($sql,0,'accountid'); + if($accountid == 0) $accountid=''; + + global $mod_strings; + global $app_strings; + global $theme; + global $currentModule; + global $current_user; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + $smarty->assign("accountid",$accountid); + + + if(isset($_request['isduplicate']) && $_request['isduplicate'] == 'true') { + $focus->id = ""; + } + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + $parent_email = getEmailParentsList('Contacts',$_REQUEST['record'], $focus); + $smarty->assign("HIDDEN_PARENTS_LIST",$parent_email); + + if(isset($_REQUEST['record']) && $_REQUEST['record']!='') { + $userid = $current_user->id; + $sql = "select fieldname from vtiger_field where uitype = '13' and tabid = 4 and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array()); + $num_fieldnames = $adb->num_rows($result); + for($i = 0; $i < $num_fieldnames; $i++) { + $fieldname = $adb->query_result($result,$i,"fieldname"); + $permit= getFieldVisibilityPermission("Contacts",$userid,$fieldname); + } + } + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("CONTACT_PERMISSION",CheckFieldPermission('contact_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("CATEGORY",$category); + $smarty->assign("ID",$focus->id); + $smarty->assign("NAME",$focus->name); + $smarty->assign("EMAIL",$focus->column_fields['email']); + $smarty->assign("YAHOO",$focus->column_fields['yahooid']); + + // 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->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$app_strings['Contact']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Contacts/Contacts.js b/oss/vtiger/trunk/modules/Contacts/Contacts.js new file mode 100644 index 00000000..de29b5d9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/Contacts.js @@ -0,0 +1,250 @@ +/********************************************************************************* + +** 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. + ********************************************************************************/ + +document.write(" +pquery($sql, array($templateid)); +$temparray = $adb->fetch_array($result); + +$fileContent = $temparray['data']; +$filename=html_entity_decode($temparray['filename'], ENT_QUOTES, $default_charset); +// Fix For: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$filename= $randomfilename . "_word.doc"; + +$filesize=$temparray['filesize']; +$wordtemplatedownloadpath =$root_directory ."/test/wordtemplatedownload/"; + +$handle = fopen($wordtemplatedownloadpath .$filename,"wb"); +fwrite($handle,base64_decode($fileContent),$filesize); +fclose($handle); + + +//<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>> +$mass_merge = $_REQUEST['allselectedboxes']; +$single_record = $_REQUEST['record']; + +if($mass_merge != "") +{ + $mass_merge = explode(";",$mass_merge); + $temp_mass_merge = $mass_merge; + if(array_pop($temp_mass_merge)=="") + array_pop($mass_merge); + //$mass_merge = implode(",",$mass_merge); +}else if($single_record != "") +{ + $mass_merge = $single_record; +}else +{ + die("Record Id is not found, cannot merge the document"); +} + +//<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>> + +global $current_user; +require('user_privileges/user_privileges_'.$current_user->id.'.php'); +if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users" || $module == "Emails") +{ + $query1="select vtiger_tab.name,vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where vtiger_field.tabid in (4,6) and vtiger_field.block <> 75 order by vtiger_field.tablename and vtiger_field.presence in (0,2)"; + $params1 = array(); +} +else +{ + $profileList = getCurrentUserProfileList(); + $query1="select vtiger_tab.name,vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid in (4,6) and vtiger_field.block <> 75 AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid order by vtiger_field.tablename"; + $params1 = array($profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query1 = fixPostgresQuery( $query1, $log, 0); +} +$result = $adb->pquery($query1, $params1); +$y=$adb->num_rows($result); + +for ($x=0; $x<$y; $x++) +{ + $tablename = $adb->query_result($result,$x,"tablename"); + $columnname = $adb->query_result($result,$x,"columnname"); + $modulename = $adb->query_result($result,$x,"name"); + + if($tablename == "crmentity") + { + if($modulename == "Accounts") + { + $tablename = "crmentityAccounts"; + } + } + $querycolumns[$x] = $tablename.".".$columnname; + if($columnname == "smownerid") + { + if($modulename == "Accounts") + { + $querycolumns[$x]="case when (usersAccounts.user_name not like '') then concat(usersAccounts.last_name,' ',usersAccounts.first_name) else groupsAccounts.groupname end as username"; + } + if($modulename == "Contacts") + { + $querycolumns[$x]="case when (vtiger_users.user_name not like '') then concat(vtiger_users.last_name,' ',vtiger_users.first_name) else vtiger_groups.groupname end as usercname,vtiger_users.first_name,vtiger_users.last_name,vtiger_users.user_name,vtiger_users.yahoo_id,vtiger_users.title,vtiger_users.phone_work,vtiger_users.department,vtiger_users.phone_mobile,vtiger_users.phone_other,vtiger_users.phone_fax,vtiger_users.email1,vtiger_users.phone_home,vtiger_users.email2,vtiger_users.address_street,vtiger_users.address_city,vtiger_users.address_state,vtiger_users.address_postalcode,vtiger_users.address_country"; + } + } + if($columnname == "parentid") + { + $querycolumns[$x] = "accountAccounts.accountname"; + } + if($columnname == "accountid") + { + $querycolumns[$x] = "accountContacts.accountname"; + } + if($columnname == "reportsto") + { + $querycolumns[$x] = "contactdetailsContacts.lastname"; + } + + + if($modulename == "Accounts") + { + $field_label[$x] = "ACCOUNT_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + } + + if($modulename == "Contacts") + { + $field_label[$x] = "CONTACT_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + if($columnname == "smownerid") + { + $field_label[$x] = $field_label[$x].",USER_FIRSTNAME,USER_LASTNAME,USER_USERNAME,USER_YAHOOID,USER_TITLE,USER_OFFICEPHONE,USER_DEPARTMENT,USER_MOBILE,USER_OTHERPHONE,USER_FAX,USER_EMAIL,USER_HOMEPHONE,USER_OTHEREMAIL,USER_PRIMARYADDRESS,USER_CITY,USER_STATE,USER_POSTALCODE,USER_COUNTRY"; + } + } + + +} +$csvheader = implode(",",$field_label); +//echo $csvheader; +//<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>> + +if(count($querycolumns) > 0) +{ + $selectcolumns = implode($querycolumns,","); + + + $query = "select $selectcolumns from vtiger_contactdetails + inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid + inner join vtiger_contactaddress on vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + inner join vtiger_contactsubdetails on vtiger_contactdetails.contactid = vtiger_contactsubdetails.contactsubscriptionid + inner join vtiger_contactscf on vtiger_contactdetails.contactid = vtiger_contactscf.contactid + inner join vtiger_customerdetails on vtiger_contactdetails.contactid = vtiger_customerdetails.customerid + left join vtiger_contactdetails as contactdetailsContacts on contactdetailsContacts.contactid = vtiger_contactdetails.reportsto + left join vtiger_account as accountContacts on accountContacts.accountid = vtiger_contactdetails.accountid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_account on vtiger_account.accountid = vtiger_contactdetails.accountid + left join vtiger_crmentity as crmentityAccounts on crmentityAccounts.crmid=vtiger_account.accountid + left join vtiger_accountbillads on vtiger_account.accountid=vtiger_accountbillads.accountaddressid + left join vtiger_accountshipads on vtiger_account.accountid=vtiger_accountshipads.accountaddressid + left join vtiger_accountscf on vtiger_account.accountid = vtiger_accountscf.accountid + left join vtiger_account as accountAccounts on accountAccounts.accountid = vtiger_account.parentid + left join vtiger_users as usersAccounts on usersAccounts.id = crmentityAccounts.smownerid + LEFT JOIN vtiger_groups as groupsAccounts + ON groupsAccounts.groupid = vtiger_crmentity.smownerid + where vtiger_crmentity.deleted=0 and (crmentityAccounts.deleted is NULL or crmentityAccounts.deleted <> 1) and vtiger_contactdetails.contactid in(". generateQuestionMarks($mass_merge) .")"; + + + $result = $adb->pquery($query, array($mass_merge)); + $avail_pick_arr = getAccessPickListValues('Contacts'); +while($columnValues = $adb->fetch_array($result)) +{ + $y=$adb->num_fields($result); + for($x=0; $x<$y; $x++) + { + $value = $columnValues[$x]; + foreach($columnValues as $key=>$val) + { + if($val == $value && $value != '') + { + if(array_key_exists($key,$avail_pick_arr)) + { + if(!in_array($val,$avail_pick_arr[$key])) + { + $value = "Not Accessible"; + } + } + } + } + //<<<<<<<<<<<<<<< For blank Fields >>>>>>>>>>>>>>>>>>>>>>>>>>>> + if(trim($value) == "--None--" || trim($value) == "--none--") + { + $value = ""; + } + //<<<<<<<<<<<<<<< End >>>>>>>>>>>>>>>>>>>>>>>>>>>> + $actual_values[$x] = $value; + $actual_values[$x] = str_replace('"'," ",$actual_values[$x]); + //if value contains any line feed or carriage return replace the value with ".value." + if (preg_match ("/(\r\n)/", $actual_values[$x])) + { + $actual_values[$x] = '"'.$actual_values[$x].'"'; + } + $actual_values[$x] = decode_html(str_replace(","," ",$actual_values[$x])); + } + $mergevalue[] = implode($actual_values,","); +} +$csvdata = implode($mergevalue,"###"); +}else +{ + die("No fields to do Merge"); +} +// Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$datafilename = $randomfilename . "_data.csv"; + +$handle = fopen($wordtemplatedownloadpath.$datafilename,"wb"); +fwrite($handle,$csvheader."\r\n"); +fwrite($handle,str_replace("###","\r\n",$csvdata)); +fclose($handle); + +?> + + + diff --git a/oss/vtiger/trunk/modules/Contacts/Popup.php b/oss/vtiger/trunk/modules/Contacts/Popup.php new file mode 100644 index 00000000..98ea8ece --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/Popup.php @@ -0,0 +1,23 @@ + diff --git a/oss/vtiger/trunk/modules/Contacts/ProcessDuplicates.php b/oss/vtiger/trunk/modules/Contacts/ProcessDuplicates.php new file mode 100644 index 00000000..877dbd84 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/ProcessDuplicates.php @@ -0,0 +1,133 @@ +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,""); + } + } + + ?> + +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"); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Contacts/QuickCreate.php b/oss/vtiger/trunk/modules/Contacts/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Contacts/Save.php b/oss/vtiger/trunk/modules/Contacts/Save.php new file mode 100644 index 00000000..d5104a97 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/Save.php @@ -0,0 +1,223 @@ +email_opt_out = 'off'; +if (!isset($_REQUEST['do_not_call'])) $focus->do_not_call = 'off'; + +//Checking If image is given or not +//$image_upload_array=SaveImage($_FILES,'contact',$focus->id,$focus->mode); +$image_name_val=$image_upload_array['imagename']; +$image_error="false"; +$errormessage=$image_upload_array['errormessage']; +$saveimage=$image_upload_array['saveimage']; + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + +if($image_error=="true") //If there is any error in the file upload then moving all the data to EditView. +{ + //re diverting the page and reassigning the same values as image error occurs + if($_REQUEST['activity_mode'] != '')$activity_mode=vtlib_purify($_REQUEST['activity_mode']); + if($_REQUEST['return_module'] != '')$return_module=vtlib_purify($_REQUEST['return_module']); + if($_REQUEST['return_action'] != '')$return_action=vtlib_purify($_REQUEST['return_action']); + if($_REQUEST['return_id'] != '')$return_id=vtlib_purify($_REQUEST['return_id']); + + $log->debug("There is an error during the upload of contact image."); + $field_values_passed.=""; + foreach($focus->column_fields as $fieldname => $val) + { + if(isset($_REQUEST[$fieldname])) + { + $log->debug("Assigning the previous values given for the contact to respective vtiger_fields "); + $field_values_passed.="&"; + $value = $_REQUEST[$fieldname]; + $focus->column_fields[$fieldname] = $value; + $field_values_passed.=$fieldname."=".$value; + + } + } + $values_pass=$field_values_passed; + $encode_field_values=base64_encode($values_pass); + + $error_module = "Contacts"; + $error_action = "EditView"; + + $return_action .= '&activity_mode='.vtlib_purify($_request['activity_mode']); + + if($mode=="edit") { + $return_id=vtlib_purify($_REQUEST['record']); + } + header("location: index.php?action=$error_action&module=$error_module&record=$return_id&return_id=$return_id&return_action=$return_action&return_module=$return_module&activity_mode=$activity_mode&return_viewname=$return_viewname".$search."&saveimage=$saveimage&error_msg=$errormessage&image_error=$image_error&encode_val=$encode_field_values"); +} +if($saveimage=="true") +{ + $focus->column_fields['imagename']=$image_name_val; + $log->debug("Assign the Image name to the vtiger_field name "); +} + +//if image added then we have to set that $_FILES['name'] in imagename field then only the image will be displayed +if($_FILES['imagename']['name'] != '') +{ + if(isset($_REQUEST['imagename_hidden'])) { + $focus->column_fields['imagename'] = vtlib_purify($_REQUEST['imagename_hidden']); + } else { + $focus->column_fields['imagename'] = $_FILES['imagename']['name']; + } +} +elseif($focus->id != '') +{ + $result = $adb->pquery("select imagename from vtiger_contactdetails where contactid = ?", array($focus->id)); + $focus->column_fields['imagename'] = $adb->query_result($result,0,'imagename'); +} + +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']; +} +//Saving the contact +if($image_error=="false") +{ + $focus->save("Contacts"); + $return_id = $focus->id; + + if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); + else $return_module = "Contacts"; + if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); + else $return_action = "DetailView"; + if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + + if(isset($_REQUEST['activity_mode']) && $_REQUEST['activity_mode'] != '') $activitymode = vtlib_purify($_REQUEST['activity_mode']); + + $local_log->debug("Saved record with id of ".$return_id); + + if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] == "Campaigns") + { + if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") + { + $sql = "delete from vtiger_campaigncontrel where contactid = ?"; + $adb->pquery($sql, array($focus->id)); + $sql = "insert into vtiger_campaigncontrel values (?,?)"; + $adb->pquery($sql, array($_REQUEST['return_id'], $focus->id)); + } + } + + //BEGIN -- Code for Create Customer Portal Users password and Send Mail + if($_REQUEST['portal'] == '' && $_REQUEST['mode'] == 'edit') + { + $sql = "update vtiger_portalinfo set user_name=?,isactive=0 where id=?"; + $adb->pquery($sql, array($_REQUEST['email'], $_REQUEST['record'])); + } + elseif($_REQUEST['portal'] != '' && $_REQUEST['email'] != '')// && $_REQUEST['mode'] != 'edit') + { + $id = $_REQUEST['record']; + $username = $_REQUEST['email']; + + if($_REQUEST['mode'] != 'edit') + $insert = 'true'; + + $sql = "select id,user_name,user_password,isactive from vtiger_portalinfo"; + $result = $adb->pquery($sql, array()); + + for($i=0;$i<$adb->num_rows($result);$i++) + { + if($id == $adb->query_result($result,$i,'id')) + { + $dbusername = $adb->query_result($result,$i,'user_name'); + $isactive = $adb->query_result($result,$i,'isactive'); + + if($username == $dbusername && $isactive == 1) + $flag = 'true'; + else + { + $sql = "update vtiger_portalinfo set user_name=?, isactive=1 where id=?"; + $adb->pquery($sql, array($username, $id)); + $update = 'true'; + $flag = 'true'; + $password = $adb->query_result($result,$i,'user_password'); + } + } + } + if($flag != 'true') + $insert = 'true'; + else + $insert = 'false'; + + if($insert == 'true') + { + $password = makeRandomPassword(); + $sql = "insert into vtiger_portalinfo values(?,?,?,?,?,?,?,?)"; + $params = array($focus->id, $username, $password, 'C', '0000-00-00 00:00:00', '0000-00-00 00:00:00', '0000-00-00 00:00:00', 1); + $adb->pquery($sql, $params); + } + + //changes made to send mail to portal user when we use ajax edit + $data_array = Array(); + $data_array['first_name'] = $_REQUEST['firstname']; + $data_array['last_name'] = $_REQUEST['lastname']; + $data_array['email'] = $_REQUEST['email']; + $data_array['portal_url'] = ''.$mod_strings['Please Login Here'].''; + + $value = getmail_contents_portalUser($data_array,$password,"LoginDetails"); + $contents=$value["body"]; $subject=$value["subject"]; + + $log->info("Customer Portal Information Updated in database and details are going to send => '".$_REQUEST['email']."'"); + if($insert == 'true' || $update == 'true') + { + $mail_status = send_mail('Support',$_REQUEST['email'],$current_user->user_name,'',$subject,$contents); + } + $log->info("After return from the SendMailToCustomer function. Now control will go to the header."); + } + //END -- Code for Create Customer Portal Users password and Send Mail + + $log->info("This Page is redirected to : ".$return_module." / ".$return_action."& return id =".$return_id); + + //code added for returning back to the current view after edit from list view + if($_REQUEST['return_viewname'] == '') $return_viewname='0'; + if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + + $parenttab = getParentTab(); + + //Send notification mail to the assigned to owner about the contact creation + if($focus->column_fields['notify_owner'] == 1 || $focus->column_fields['notify_owner'] == 'on') + $status = sendNotificationToOwner('Contacts',$focus); + + header("Location: index.php?action=$return_action&module=$return_module&parenttab=$parenttab&record=$return_id&activity_mode=$activitymode&viewname=$return_viewname&start=".vtlib_purify($_REQUEST['pagenumber'])); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Contacts/Settings.php b/oss/vtiger/trunk/modules/Contacts/Settings.php new file mode 100644 index 00000000..48a80c0b --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/Settings.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Contacts/TagCloud.php b/oss/vtiger/trunk/modules/Contacts/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Contacts/UnifiedSearch.php b/oss/vtiger/trunk/modules/Contacts/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Contacts/contactSeedData.php b/oss/vtiger/trunk/modules/Contacts/contactSeedData.php new file mode 100644 index 00000000..ff2881ae --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/contactSeedData.php @@ -0,0 +1,21190 @@ + diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/2tbarPrivateChat.gif b/oss/vtiger/trunk/modules/Contacts/imgs/2tbarPrivateChat.gif new file mode 100644 index 00000000..f0d7a1f5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/2tbarPrivateChat.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/2tbarPublicChat.gif b/oss/vtiger/trunk/modules/Contacts/imgs/2tbarPublicChat.gif new file mode 100644 index 00000000..9c8d42d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/2tbarPublicChat.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_BL.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_BL.gif new file mode 100644 index 00000000..d81412a9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_BL.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_BR.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_BR.gif new file mode 100644 index 00000000..44b171d5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_BR.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_M.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_M.gif new file mode 100644 index 00000000..e1fa15ea Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_M.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_ML.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_ML.gif new file mode 100644 index 00000000..559ccf08 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_ML.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_MR.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_MR.gif new file mode 100644 index 00000000..dd798fc5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_MR.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_T.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_T.gif new file mode 100644 index 00000000..d09eb43c Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_T.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_TL.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_TL.gif new file mode 100644 index 00000000..87ce1987 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_TL.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/box_TR.gif b/oss/vtiger/trunk/modules/Contacts/imgs/box_TR.gif new file mode 100644 index 00000000..70b5c27f Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/box_TR.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/btn_close.gif b/oss/vtiger/trunk/modules/Contacts/imgs/btn_close.gif new file mode 100644 index 00000000..1d7b0f84 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/btn_close.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/btn_hide.gif b/oss/vtiger/trunk/modules/Contacts/imgs/btn_hide.gif new file mode 100644 index 00000000..8419cd10 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/btn_hide.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/btn_send.gif b/oss/vtiger/trunk/modules/Contacts/imgs/btn_send.gif new file mode 100644 index 00000000..300880ec Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/btn_send.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/bx_B.gif b/oss/vtiger/trunk/modules/Contacts/imgs/bx_B.gif new file mode 100644 index 00000000..f6d8e815 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/bx_B.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/close.gif b/oss/vtiger/trunk/modules/Contacts/imgs/close.gif new file mode 100644 index 00000000..1e157ce8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/close.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/hide.gif b/oss/vtiger/trunk/modules/Contacts/imgs/hide.gif new file mode 100644 index 00000000..96ef9a15 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/hide.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/icone_chat.gif b/oss/vtiger/trunk/modules/Contacts/imgs/icone_chat.gif new file mode 100644 index 00000000..35c0a957 Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/icone_chat.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/icone_keyb.gif b/oss/vtiger/trunk/modules/Contacts/imgs/icone_keyb.gif new file mode 100644 index 00000000..d15e643c Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/icone_keyb.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/site_bg.gif b/oss/vtiger/trunk/modules/Contacts/imgs/site_bg.gif new file mode 100644 index 00000000..a638838f Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/site_bg.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/imgs/user_icon.gif b/oss/vtiger/trunk/modules/Contacts/imgs/user_icon.gif new file mode 100644 index 00000000..724727cc Binary files /dev/null and b/oss/vtiger/trunk/modules/Contacts/imgs/user_icon.gif differ diff --git a/oss/vtiger/trunk/modules/Contacts/index.php b/oss/vtiger/trunk/modules/Contacts/index.php new file mode 100644 index 00000000..010dcf03 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/index.php @@ -0,0 +1,27 @@ + diff --git a/oss/vtiger/trunk/modules/Contacts/language/en_us.lang.php b/oss/vtiger/trunk/modules/Contacts/language/en_us.lang.php new file mode 100644 index 00000000..ac90dd61 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/language/en_us.lang.php @@ -0,0 +1,249 @@ +'Contacts', +'LBL_INVITEE'=>'Direct Reports', +'LBL_MODULE_TITLE'=>'Contacts: Home', +'LBL_SEARCH_FORM_TITLE'=>'Contact Search', +'LBL_LIST_FORM_TITLE'=>'Contact List', +'LBL_NEW_FORM_TITLE'=>'New Contact', +'LBL_CONTACT_OPP_FORM_TITLE'=>'Contact-Opportunity:', +'LBL_CONTACT'=>'Contact:', + +'LBL_LIST_NAME'=>'Name', +'LBL_LIST_LAST_NAME'=>'Last Name', +'LBL_LIST_FIRST_NAME'=>'First Name', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', +'LBL_LIST_TITLE'=>'Title', +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_LIST_EMAIL_ADDRESS'=>'Email', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_CONTACT_ROLE'=>'Role', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_last_name' => 'LBL_LIST_LAST_NAME', +'db_first_name' => 'LBL_LIST_FIRST_NAME', +'db_title' => 'LBL_LIST_TITLE', +'db_email1' => 'LBL_LIST_EMAIL_ADDRESS', +'db_email2' => 'LBL_LIST_EMAIL_ADDRESS', +//END DON'T CONVERT + +'LBL_EXISTING_CONTACT' => 'Used an existing contact', +'LBL_CREATED_CONTACT' => 'Created a new contact', +'LBL_EXISTING_ACCOUNT' => 'Used an existing vtiger_account', +'LBL_CREATED_ACCOUNT' => 'Created a new vtiger_account', +'LBL_CREATED_CALL' => 'Created a new call', +'LBL_CREATED_MEETING' => 'Created a new meeting', +'LBL_ADDMORE_BUSINESSCARD' =>'Add another business card', + +'LBL_BUSINESSCARD' => 'Business Card', + +'LBL_NAME'=>'Name:', +'LBL_CONTACT_NAME'=>'Contact Name:', +'LBL_CONTACT_INFORMATION'=>'Contact Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_FIRST_NAME'=>'First Name:', +'LBL_OFFICE_PHONE'=>'Office Phone:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_PHONE'=>'Phone:', +'LBL_LAST_NAME'=>'Last Name:', +'LBL_MOBILE_PHONE'=>'Mobile:', +'LBL_HOME_PHONE'=>'Home:', +'LBL_LEAD_SOURCE'=>'Lead Source:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_FAX_PHONE'=>'Fax:', +'LBL_TITLE'=>'Title:', +'LBL_DEPARTMENT'=>'Department:', +'LBL_BIRTHDATE'=>'Birthdate:', +'LBL_EMAIL_ADDRESS'=>'Email:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_REPORTS_TO'=>'Reports To:', +'LBL_ASSISTANT'=>'Assistant:', +'LBL_YAHOO_ID'=>'Yahoo! ID:', +'LBL_ASSISTANT_PHONE'=>'Assistant Phone:', +'LBL_DO_NOT_CALL'=>'Do Not Call:', +'LBL_EMAIL_OPT_OUT'=>'Email Opt Out:', +'LBL_PRIMARY_ADDRESS'=>'Primary Address:', +'LBL_ALTERNATE_ADDRESS'=>'Other Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_IMAGE_INFORMATION'=>'Contact Image Information:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_DESCRIPTION'=>'Description:', +'LBL_CONTACT_ROLE'=>'Role:', +'LBL_OPP_NAME'=>'Opportunity Name:', +'LBL_DUPLICATE'=>'Potential Duplicate Contacts', +'MSG_DUPLICATE' => 'Creating this contact may vtiger_potentialy create a duplicate contact. You may either select a contact from the list below or you may click on Create New Contact to continue creating a new contact with the previously entered data.', + +'LNK_NEW_APPOINTMENT' => 'New Appointment', +'LBL_ADD_BUSINESSCARD' => 'Add Business Card', +'NTC_DELETE_CONFIRMATION'=>'Are you sure you want to delete this record?', +'NTC_REMOVE_CONFIRMATION'=>'Are you sure you want to remove this contact from this case?', +'NTC_REMOVE_DIRECT_REPORT_CONFIRMATION'=>'Are you sure you want to remove this record as a direct vtiger_report?', +'ERR_DELETE_RECORD'=>"en_us A record number must be specified to delete the contact.", +'NTC_COPY_PRIMARY_ADDRESS'=>'Copy primary address to alternate address', +'NTC_COPY_ALTERNATE_ADDRESS'=>'Copy alternate address to primary address', + +'LBL_SELECT_CONTACT'=>'Select Contact', +//Added for search heading +'LBL_GENERAL_INFORMATION'=>'General Information', + + + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_NOTE'=>'New Document', +'LBL_NOTE_TITLE'=>'Documents', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Contact Tools', + +'Salutation'=>'Salutation', +'First Name'=>'First Name', +'Office Phone'=>'Office Phone', +'Last Name'=>'Last Name', +'Mobile'=>'Mobile', +'Account Name'=>'Account Name', +'Home Phone'=>'Home Phone', +'Lead Source'=>'Lead Source', +'Other Phone'=>'Other Phone', +'Title'=>'Title', +'Fax'=>'Fax', +'Department'=>'Department', +'Birthdate'=>'Birthdate', +'Email'=>'Email', +'Reports To'=>'Reports To', +'Assistant'=>'Assistant', +'Yahoo Id'=>'Yahoo Id', +'Assistant Phone'=>'Assistant Phone', +'Do Not Call'=>'Do Not Call', +'Email Opt Out'=>'Email Opt Out', +'Assigned To'=>'Assigned To', +'Campaign Source'=>'Campaign Source', +'Reference' =>'Reference', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Mailing Street'=>'Mailing Street', +'Other Street'=>'Other Street', +'Mailing City'=>'Mailing City', +'Mailing State'=>'Mailing State', +'Mailing Zip'=>'Mailing Postal Code', +'Mailing Country'=>'Mailing Country', +'Mailing Po Box'=>'Mailing PO Box', +'Other Po Box'=>'Other PO Box', +'Other City'=>'Other City', +'Other State'=>'Other State', +'Other Zip'=>'Other Postal Code', +'Other Country'=>'Other Country', +'Contact Image'=>'Contact Image', +'Description'=>'Description', + +// Added vtiger_fields for Add Business Card +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_NEW_ACCOUNT'=>'New Account', +'LBL_NOTE_SUBJECT'=>'Document Subject:', +'LBL_NOTE'=>'Note:', +'LBL_WEBSITE'=>'Website:', +'LBL_NEW_APPOINTMENT'=>'New Appointment', +'LBL_SUBJECT'=>'Subject:', +'LBL_START_DATE'=>'Start Date:', +'LBL_START_TIME'=>'Start Time:', + +//Added vtiger_field after 4_0_1 +'Portal User'=>'Portal User', +'LBL_CUSTOMER_PORTAL_INFORMATION'=>'Customer Portal Information', +'Support Start Date'=>'Support Start Date', +'Support End Date'=>'Support End Date', +//Added for 4.2 Release -- CustomView +'Name'=>'Name', +'LBL_ALL'=>'All', +'LBL_MAXIMUM_LIMIT_ERROR'=>'Sorry, the uploaded file exceeds the maximum vtiger_filesize limit. Please try a file smaller than 800000 bytes', +'LBL_UPLOAD_ERROR'=>'Problems in file upload. Please try again!', +'LBL_IMAGE_ERROR'=>'The given file is not of type image(.gif/.jpg/.png)', +'LBL_INVALID_IMAGE'=>'Invalid file OR File has no data', + +//Added after 5Alpha5 +'Notify Owner'=>'Notify Owner', + +//Added for Picklist Values +'--None--'=>'--None--', + +'Mr.'=>'Mr.', +'Ms.'=>'Ms.', +'Mrs.'=>'Mrs.', +'Dr.'=>'Dr.', +'Prof.'=>'Prof.', + +'Cold Call'=>'Cold Call', +'Existing Customer'=>'Existing Customer', +'Self Generated'=>'Self Generated', +'Employee'=>'Employee', +'Partner'=>'Partner', +'Public Relations'=>'Public Relations', +'Direct Mail'=>'Direct Mail', +'Conference'=>'Conference', +'Trade Show'=>'Trade Show', +'Web Site'=>'Web Site', +'Word of mouth'=>'Word of mouth', +'Other'=>'Other', +'User List'=>'User List', + +//Added for 5.0.3 +'Customer Portal Login Details'=>'Customer Portal Login Details', +'Dear'=>'Dear', +'Your Customer Portal Login details are given below:'=>'Your Customer Portal Login details are given below:', +'User Id :'=>'User Id :', +'Password :'=>'Password :', +'Please Login Here'=>'Please Login Here', +'Note :'=>'Note :', +'We suggest you to change your password after logging in first time'=>'We suggest you to change your password after logging in first time.', +'Support Team'=>'Support Team', + +'TITLE_AJAX_CSS_POPUP_CHAT'=>'Ajax Css-Popup chat', + +// Added after 5.0.4 GA + +// Module Sequence Numbering +'Contact Id' => 'Contact Id', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Contacts/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Contacts/language/zh_cn.lang.php new file mode 100644 index 00000000..6e7507de --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/language/zh_cn.lang.php @@ -0,0 +1,249 @@ + '联系人', + 'LBL_INVITEE' => '针对报告', + 'LBL_MODULE_TITLE' => '联系人: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻联系人', + 'LBL_LIST_FORM_TITLE' => '联系人列表', + 'LBL_NEW_FORM_TITLE' => '新增联系人', + 'LBL_CONTACT_OPP_FORM_TITLE' => '联系人-机会:', + 'LBL_CONTACT' => '联系人:', + + 'LBL_LIST_NAME' => '名称', + 'LBL_LIST_LAST_NAME' => '姓名', + 'LBL_LIST_FIRST_NAME' => '英文名', + 'LBL_LIST_CONTACT_NAME' => '联系人名称', + 'LBL_LIST_TITLE' => '在线IM', + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_CONTACT_ROLE' => '职位', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_last_name' => 'LBL_LIST_LAST_NAME', +'db_first_name' => 'LBL_LIST_FIRST_NAME', +'db_title' => 'LBL_LIST_TITLE', +'db_email1' => 'LBL_LIST_EMAIL_ADDRESS', +'db_email2' => 'LBL_LIST_EMAIL_ADDRESS', +//END DON'T CONVERT + +'LBL_EXISTING_CONTACT' => '使用现有的联系人', + 'LBL_CREATED_CONTACT' => '建立新的联系人', + 'LBL_EXISTING_ACCOUNT' => '使用现有的客户', + 'LBL_CREATED_ACCOUNT' => '建立新的客户', + 'LBL_CREATED_CALL' => '建立新的电话记录l', + 'LBL_CREATED_MEETING' => '建立新的会议', + 'LBL_ADDMORE_BUSINESSCARD' => '增加其它的商业名片', + + 'LBL_BUSINESSCARD' => '商业名片', + +'LBL_NAME' => '名称:', + 'LBL_CONTACT_NAME' => '联系人名称:', + 'LBL_CONTACT_INFORMATION' => '联系人信息', + 'LBL_CUSTOM_INFORMATION' => '客户信息', + 'LBL_FIRST_NAME' => '英文名:', + 'LBL_OFFICE_PHONE' => '办公室电话:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_ANY_PHONE' => '其它电话:', + 'LBL_PHONE' => '电话:', + 'LBL_LAST_NAME' => '姓名:', + 'LBL_MOBILE_PHONE' => '手机:', + 'LBL_HOME_PHONE' => '首页:', + 'LBL_LEAD_SOURCE' => '接触来源:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_FAX_PHONE' => '传真:', + 'LBL_TITLE' => '在线IM:', + 'LBL_DEPARTMENT' => '部门:', + 'LBL_BIRTHDATE' => '生日:', + 'LBL_EMAIL_ADDRESS' => '电子邮件:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子邮件:', + 'LBL_ANY_EMAIL' => '其它电子邮件:', + 'LBL_REPORTS_TO' => '报告给:', + 'LBL_ASSISTANT' => '助理:', + 'LBL_YAHOO_ID' => 'Yahoo账号:', + 'LBL_ASSISTANT_PHONE' => '助理电话:', + 'LBL_DO_NOT_CALL' => '请勿来电:', + 'LBL_EMAIL_OPT_OUT' => '请勿寄电子邮件:', + 'LBL_PRIMARY_ADDRESS' => '主要地址:', + 'LBL_ALTERNATE_ADDRESS' => '其它地址:', + 'LBL_ANY_ADDRESS' => '其它地址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '市(县):', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '省(市/自治区):', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息', + 'LBL_IMAGE_INFORMATION' => '联系人照片:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_CONTACT_ROLE' => '职位:', + 'LBL_OPP_NAME' => '机会名称:', + 'LBL_DUPLICATE' => '接触到潜在案件', + 'MSG_DUPLICATE' => '建立这个联系人可能造成重复,您可以点选建立联系人来透过已存在的数据建立新的联系人或是点选取消。', + + 'LNK_NEW_APPOINTMENT' => '新增行程', + 'LBL_ADD_BUSINESSCARD' => '新增商业名片', + 'NTC_DELETE_CONFIRMATION' => '您确定要删除这笔记录?', + 'NTC_REMOVE_CONFIRMATION' => '您确定要从这个案件中移除这位联系人?', + 'NTC_REMOVE_DIRECT_REPORT_CONFIRMATION' => '您确定要将此记录从直接报告人处删除吗?', + 'ERR_DELETE_RECORD' => '在删除联系人前必须输入正确的记录编号.', + 'NTC_COPY_PRIMARY_ADDRESS' => '复制主要地址到替代地址', + 'NTC_COPY_ALTERNATE_ADDRESS' => '复制替代地址到替代地址', + + 'LBL_SELECT_CONTACT' => '选择联系人', +//Added for search heading +'LBL_GENERAL_INFORMATION'=>'一般信息', + + + +//for v4 release added + 'LBL_NEW_POTENTIAL' => '新增潜在', + 'LBL_POTENTIAL_TITLE' => '潜在', + + 'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '电子邮件', + 'LBL_NEW_NOTE' => '新增备忘录', + 'LBL_NOTE_TITLE' => '备忘录', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '联系人编辑区', + + 'Salutation' => '问候', + 'First Name' => '英文名', + 'Office Phone' => '办公室电话', + 'Last Name' => '姓名', + 'Mobile' => '手机', + 'Account Name' => '客户名称', + 'Home Phone' => '家用电话', + 'Lead Source' => '客户来源', + 'Phone' => '电话', + 'Title' => '在线QQ', + 'Fax' => '传真', + 'Department' => '部门', + 'Birthdate' => '生日', + 'Email' => '电子邮件', + 'Reports To' => '报告给', + 'Assistant' => '助理', + 'Yahoo Id' => 'Yahoo账号', + 'Assistant Phone' => '助理电话', + 'Do Not Call' => '拒绝来电', + 'Email Opt Out' => '拒绝电子邮件', + 'Assigned To' => '负责人', + 'Campaign Source' => '活动来源', + 'Reference' => '参考', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Mailing Street' => '邮寄地址', + 'Other Street' => '其它地址', + 'Mailing City' => '乡镇市区', + 'Mailing State' => '市(县)', + 'Mailing Zip' => '邮政编码', + 'Mailing Country' => '省(市/自治区)', + 'Mailing Po Box' => '采购订单信箱', + 'Other Po Box' => '其它采购订单信箱', + 'Other City' => '乡镇市区', + 'Other State' => '市(县)', + 'Other Zip' => '邮政编码', + 'Other Country' => '省(市/自治区)', + 'Contact Image' => '照片', + 'Description' => '描述', + +// Added vtiger_fields for Add Business Card + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_NEW_ACCOUNT' => '新增客户', + 'LBL_NOTE_SUBJECT' => '备忘录标题:', + 'LBL_NOTE' => '备忘录:', + 'LBL_WEBSITE' => '网站:', + 'LBL_NEW_APPOINTMENT' => '新增行程', + 'LBL_SUBJECT' => '在线IM:', + 'LBL_START_DATE' => '开始日期:', + 'LBL_START_TIME' => '开始时间:', + +//Added vtiger_field after 4_0_1 +'Portal User' => '网站账号', + 'LBL_CUSTOMER_PORTAL_INFORMATION' => '网站客户信息', + 'Support Start Date' => '支持开始日期', + 'Support End Date' => '支持结束日期', +//Added for 4.2 Release -- CustomView +'Name' => '名称', + 'LBL_ALL' => '全部', + 'LBL_MAXIMUM_LIMIT_ERROR' => '抱歉,文件超过系统限制,请保持上传文件在 800000 bytes 以下', + 'LBL_UPLOAD_ERROR' => '上传失败,请重试!', + 'LBL_IMAGE_ERROR' => '提供的文件不是图片格式(.gif/.jpg/.png)', + 'LBL_INVALID_IMAGE' => '文件有误或是没有数据', + + +//Added after 5Alpha5 + 'Notify Owner' => '提醒负责人', + +//Added for Picklist Values + '--None--' => '-- 无 --', + +'Mr.' => '先生', + 'Ms.' => '小姐', + 'Mrs.' => '太太', + 'Dr.' => '博士', + 'Prof.' => '专家', + + 'Cold Call' => '陌生拜访', + 'Existing Customer' => '既有客户', + 'Self Generated' => '自动产生', + 'Employee' => '员工', + 'Partner' => '伙伴', + 'Public Relations' => '公众关系', + 'Direct Mail' => '邮件营销', + 'Conference' => '研讨会', + 'Trade Show' => '贸易展览', + 'Web Site' => '网站', + 'Word of mouth' => '口耳相传', + 'Other' => '其它', + 'User List' => '使用者清单', + +//Added for 5.0.3 +'Customer Portal Login Details'=>'顾客注册细节', +'Dear'=>'亲爱的', +'Your Customer Portal Login details are given below:'=>'您的顾客提供了以下注册细节:', +'User Id :'=>'用户号 :', +'Password :'=>'密码 :', +'Please Login Here'=>'请在这里登录', +'Note :'=>'笔记 :', +'We suggest you to change your password after logging in first time'=>'请您在第一次登录时修改密码以保证安全.', +'Support Team'=>'项目团队', + + +'TITLE_AJAX_CSS_POPUP_CHAT'=>'Ajax Css-Popup chat', +// Added after 5.0.4 GA + +// Module Sequence Numbering +'Contact Id' => '编号', +// END +); + +?> diff --git a/oss/vtiger/trunk/modules/Contacts/updateRelations.php b/oss/vtiger/trunk/modules/Contacts/updateRelations.php new file mode 100644 index 00000000..ea8cd200 --- /dev/null +++ b/oss/vtiger/trunk/modules/Contacts/updateRelations.php @@ -0,0 +1,55 @@ +pquery($sql, array($forCRMRecord, $_REQUEST["pot_id"])); +} +$focus = CRMEntity::getInstance($currentModule); +foreach($storearray as $id) +{ + if($id != '') + { + if($dest_mod == 'Products') + $adb->pquery("insert into vtiger_seproductsrel values (?,?,?)", array($forCRMRecord, $id, 'Contacts')); + elseif($dest_mod == 'Campaigns') + $adb->pquery("insert into vtiger_campaigncontrel values(?,?)", array($id, $forCRMRecord)); + elseif($dest_mod == 'Documents') + $adb->pquery("insert into vtiger_senotesrel values(?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/ChangeStatus.php b/oss/vtiger/trunk/modules/CustomView/ChangeStatus.php new file mode 100644 index 00000000..c4a224df --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/ChangeStatus.php @@ -0,0 +1,54 @@ +isPermittedCustomView($cvid,$now_action,$oCustomView->customviewmodule) == 'yes') + { + $updateStatusSql = "update vtiger_customview set status=? where cvid=? and entitytype=?"; + $updateresult = $adb->pquery($updateStatusSql, array($status, $cvid, $module)); + if(!$updateresult) + echo ':#:FAILURE:#:'; + else + echo ':#:SUCCESS:#:' . $module . ':#:'; + } + else + { + global $theme, $app_strings; + echo "
"; + echo "
+ + + + + + + + + +
+ $app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/CustomView.js b/oss/vtiger/trunk/modules/CustomView/CustomView.js new file mode 100644 index 00000000..9e234cef --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/CustomView.js @@ -0,0 +1,393 @@ + /********************************************************************************* + ** 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. + * + ********************************************************************************/ +function trimfValues(value) +{ + var string_array; + string_array = value.split(":"); + return string_array[4]; +} + +function updatefOptions(sel, opSelName) { + var selObj = document.getElementById(opSelName); + var fieldtype = null ; + + var currOption = selObj.options[selObj.selectedIndex]; + var currField = sel.options[sel.selectedIndex]; + var fld = currField.value.split(":"); + var tod = fld[4]; + if(fld[4] == 'D' || fld[4] == 'DT') + { + $("and"+sel.id).innerHTML = ""; + if(sel.id != "fcol5") + $("and"+sel.id).innerHTML = "("+$("user_dateformat").value+") "+alert_arr.LBL_AND; + else + $("and"+sel.id).innerHTML = "("+$("user_dateformat").value+") "; + } + else if(fld[4] == 'T' && fld[1] != 'time_start' && fld[1] != 'time_end') + { + $("and"+sel.id).innerHTML = ""; + if(sel.id != "fcol5") + $("and"+sel.id).innerHTML = "("+$("user_dateformat").value+" hh:mm:ss) "+alert_arr.LBL_AND; + else + $("and"+sel.id).innerHTML = "("+$("user_dateformat").value+" hh:mm:ss) "; + } + +else if(fld[4] == 'I' && fld[1] == 'time_start' || fld[1] == 'time_end') + { + $("and"+sel.id).innerHTML = ""; + if(sel.id != "fcol5") + $("and"+sel.id).innerHTML = "hh:mm "+alert_arr.LBL_AND; + else + $("and"+sel.id).innerHTML = "hh:mm"; + } + + else if(fld[4] == 'T' && fld[1] == 'time_start' || fld[1] == 'time_end') + { + $("and"+sel.id).innerHTML = ""; + if(sel.id != "fcol5") + $("and"+sel.id).innerHTML = "hh:mm "+alert_arr.LBL_AND; + else + $("and"+sel.id).innerHTML = "hh:mm"; + } + + + else if(fld[4] == 'C') + { + $("and"+sel.id).innerHTML = ""; + if(sel.id != "fcol5") + $("and"+sel.id).innerHTML = "( Yes / No ) "+alert_arr.LBL_AND; + else + $("and"+sel.id).innerHTML = "( Yes / No ) "; + } + else { + $("and"+sel.id).innerHTML = ""; + if(sel.id != "fcol5") + $("and"+sel.id).innerHTML = " "+alert_arr.LBL_AND; + else + $("and"+sel.id).innerHTML = " "; + } + + if(currField.value != null && currField.value.length != 0) + { + fieldtype = trimfValues(currField.value); + ops = typeofdata[fieldtype]; + var off = 0; + if(ops != null) + { + + var nMaxVal = selObj.length; + for(nLoop = 0; nLoop < nMaxVal; nLoop++) + { + selObj.remove(0); + } + selObj.options[0] = new Option ('None', ''); + if (currField.value == '') { + selObj.options[0].selected = true; + } + off = 1; + for (var i = 0; i < ops.length; i++) + { + var label = fLabels[ops[i]]; + if (label == null) continue; + var option = new Option (fLabels[ops[i]], ops[i]); + selObj.options[i + off] = option; + if (currOption != null && currOption.value == option.value) + { + option.selected = true; + } + } + } + }else + { + if (currField.value == '') { + selObj.options[0].selected = true; + } + } + +} +function verify_data() { + var isError = false; + var errorMessage = ""; + if (trim(document.CustomView.viewName.value) == "") { + isError = true; + errorMessage += "\nView Name"; + } + // Here we decide whether to submit the form. + if (isError == true) { + alert(alert_arr.MISSING_REQUIRED_FIELDS + errorMessage); + return false; + } + //return true; +} + + +function CancelForm() +{ +var cvmodule = document.templatecreate.cvmodule.value; +var viewid = document.templatecreate.cvid.value; +document.location.href = "index.php?module="+cvmodule+"&action=index&viewname="+viewid; +} + + +function check4null(form) +{ + var isError = false; + var errorMessage = ""; + // Here we decide whether to submit the form. + if (trim(form.subject.value) =='') { + isError = true; + errorMessage += "\n subject"; + form.subject.focus(); + } + + // Here we decide whether to submit the form. + if (isError == true) { + alert(alert_arr.MISSING_REQUIRED_FIELDS + errorMessage); + return false; + } + return true; +} + +// Added for Custom View Advance Filter validation +function checkval() +{ + var value,option,arr,dttime,sep; + for(var i=1;i<=5;i++) + { + value=trim(getObj("fval"+i).value); + option=getObj("fcol"+i).value; + fopvalue=trim(getObj("fop"+i).value); + if(option !="" && value !="") + { + if(getObj("fop"+i).selectedIndex == 0) + { + alert(alert_arr.LBL_SELECT_CRITERIA); + return false; + } + arr=option.split(":"); + if(arr[4] == "N" || arr[4] == "I" || arr[4] == "NN") + { + sep=value.split(","); + for(var j=0;j 1) + { + if(!cv_patternValidate(dttime[1],"Time","TIMESECONDS")) + { + getObj("fval"+i).select(); + return false; + } + } + } + + } + if(arr[4] == "C") + { + if(value == "1") + { + getObj("fval"+i).value= "yes"; + continue; + } + else if(value == "0") + { + getObj("fval"+i).value= "no"; + continue; + } + if(value.toLowerCase() != "yes") if(value.toLowerCase() != "no") + { + alert(alert_arr.LBL_PROVIDE_YES_NO); + getObj("fval"+i).select(); + return false; + } + } + } + else if (!(option =="" && fopvalue == "" && value == "")) + { + if(option =="") + { + alert(alert_arr.LBL_SELECT_COLUMN); + return false; + } + if(fopvalue == "") + { + alert(alert_arr.LBL_SELECT_CRITERIA); + return false; + } + } + } +return true; +} + +//Added for Custom view validation +//Copied from general.js and altered some lines. becos we cant send vales to function present in general.js. it accept only field names. +function cv_dateValidate(fldval,fldLabel,type) { + if(cv_patternValidate(fldval,fldLabel,"DATE")==false) + return false; + dateval=fldval.replace(/^\s+/g, '').replace(/\s+$/g, '') + + var dateelements=splitDateVal(dateval) + + dd=dateelements[0] + mm=dateelements[1] + yyyy=dateelements[2] + + if (dd<1 || dd>31 || mm<1 || mm>12 || yyyy<1 || yyyy<1000) { + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + + if ((mm==2) && (dd>29)) {//checking of no. of days in february month + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + + if ((mm==2) && (dd>28) && ((yyyy%4)!=0)) {//leap year checking + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + + switch (parseInt(mm)) { + case 2 : + case 4 : + case 6 : + case 9 : + case 11 : if (dd>30) { + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + } + + var currdate=new Date() + var chkdate=new Date() + + chkdate.setYear(yyyy) + chkdate.setMonth(mm-1) + chkdate.setDate(dd) + + if (type!="OTH") { + if (!compareDates(chkdate,fldLabel,currdate,"current date",type)) { + return false + } else return true; + } else return true; +} + +//Added for Custom view validation +//Copied from general.js and altered some lines. becos we cant send vales to function present in general.js. it accept only field names. +function cv_patternValidate(fldval,fldLabel,type) { + if (type.toUpperCase()=="DATE") {//DATE validation + + switch (userDateFormat) { + case "yyyy-mm-dd" : + var re = /^\d{4}(-)\d{1,2}\1\d{1,2}$/ + break; + case "mm-dd-yyyy" : + case "dd-mm-yyyy" : + var re = /^\d{1,2}(-)\d{1,2}\1\d{4}$/ + } + } + + + if (type.toUpperCase()=="TIMESECONDS") + { + //TIME validation.optional hour, min and seconds + //var re = new RegExp("^([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$"); + var re = new RegExp("^(([0-1]?[0-9])|([2][0-3]))(:([0-5]?[0-9]))?(:([0-5]?[0-9]))?$"); + } + else if (type.toUpperCase()=="TIME") + { + //TIME validation. optional hours and minutes only. dont accept second. added for calendar start and end time field. + var re = new RegExp("^(([0-1]?[0-9])|([2][0-3]))(:([0-5]?[0-9]))$"); + } + if (!re.test(fldval)) { + alert(alert_arr.ENTER_VALID + fldLabel) + return false + } + else return true + + + + +} +//added to hide date selection option, if a user doesn't have permission for not permitter standard filter column +//added to fix the ticket #5117 +function standardFilterDisplay() +{ + if(getObj("stdDateFilterField")) + { + if(document.CustomView.stdDateFilterField.selectedIndex > -1 && document.CustomView.stdDateFilterField.options[document.CustomView.stdDateFilterField.selectedIndex].value == "not_accessible") + { + getObj('stdDateFilter').disabled = true; + getObj('startdate').disabled = true; getObj('enddate').disabled = true; + getObj('jscal_trigger_date_start').style.visibility="hidden"; + getObj('jscal_trigger_date_end').style.visibility="hidden"; + } + else + { + getObj('stdDateFilter').disabled = false; + getObj('startdate').disabled = false; + getObj('enddate').disabled = false; + getObj('jscal_trigger_date_start').style.visibility="visible"; + getObj('jscal_trigger_date_end').style.visibility="visible"; + } + } +} + diff --git a/oss/vtiger/trunk/modules/CustomView/CustomView.php b/oss/vtiger/trunk/modules/CustomView/CustomView.php new file mode 100644 index 00000000..45af420b --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/CustomView.php @@ -0,0 +1,2019 @@ +"".$mod_strings['equals']."", + "n"=>"".$mod_strings['not equal to']."", + "s"=>"".$mod_strings['starts with']."", + "ew"=>"".$mod_strings['ends with']."", + "c"=>"".$mod_strings['contains']."", + "k"=>"".$mod_strings['does not contain']."", + "l"=>"".$mod_strings['less than']."", + "g"=>"".$mod_strings['greater than']."", + "m"=>"".$mod_strings['less or equal']."", + "h"=>"".$mod_strings['greater or equal']."", + ); + +class CustomView extends CRMEntity{ + + + + var $module_list = Array(); + + var $customviewmodule; + + var $list_fields; + + var $list_fields_name; + + var $setdefaultviewid; + + var $escapemodule; + + var $mandatoryvalues; + + var $showvalues; + + var $data_type; + + // Information as defined for this instance in the database table. + protected $_status = false; + protected $_userid = false; + + /** This function sets the currentuser id to the class variable smownerid, + * modulename to the class variable customviewmodule + * @param $module -- The module Name:: Type String(optional) + * @returns nothing + */ + function CustomView($module="") + { + global $current_user,$adb; + $this->customviewmodule = $module; + $this->escapemodule[] = $module."_"; + $this->escapemodule[] = "_"; + $this->smownerid = $current_user->id; + } + + + /** To get the customViewId of the specified module + * @param $module -- The module Name:: Type String + * @returns customViewId :: Type Integer + */ + function getViewId($module) + { + global $adb,$current_user; + $now_action = vtlib_purify($_REQUEST['action']); + if(isset($_REQUEST['viewname']) == false) { + if (isset($_SESSION['lvs'][$module]["viewname"]) && $_SESSION['lvs'][$module]["viewname"]!='') { + $viewid = $_SESSION['lvs'][$module]["viewname"]; + } + elseif($this->setdefaultviewid != "") { + $viewid = $this->setdefaultviewid; + } else { + $defcv_result = $adb->pquery("select default_cvid from vtiger_user_module_preferences where userid = ? and tabid =?", array($current_user->id, getTabid($module))); + if($adb->num_rows($defcv_result) > 0) { + $viewid = $adb->query_result($defcv_result,0,'default_cvid'); + } else { + $query="select cvid from vtiger_customview where setdefault=1 and entitytype=?"; + $cvresult=$adb->pquery($query, array($module)); + if($adb->num_rows($cvresult) > 0) { + $viewid = $adb->query_result($cvresult,0,'cvid'); + } else $viewid = ''; + } + } + + if($viewid == '' || $viewid == 0 || $this->isPermittedCustomView($viewid,$now_action,$module) != 'yes') { + $query="select cvid from vtiger_customview where viewname='All' and entitytype=?"; + $cvresult=$adb->pquery($query, array($module)); + $viewid = $adb->query_result($cvresult,0,'cvid'); + } + } + else { + $viewname = vtlib_purify($_REQUEST['viewname']); + if((is_string($viewname) && strtolower($viewname) == 'all') || $viewname == 0) { + $viewid = $this->getViewIdByName('All', $module); + } else { + $viewid = $viewname; + } + if($this->isPermittedCustomView($viewid,$now_action,$this->customviewmodule) != 'yes') + $viewid = 0; + } + $_SESSION['lvs'][$module]["viewname"] = $viewid; + return $viewid; + + } + //Return id of a view : Added by Pavani + function getViewIdByName($viewname, $module) + { + global $adb; + if(isset($viewname)) { + $query="select cvid from vtiger_customview where viewname=? and entitytype=?"; + $cvresult=$adb->pquery($query, array($viewname,$module)); + $viewid = $adb->query_result($cvresult,0,'cvid');; + return $viewid; + } else { + return 0; + } + } + + // return type array + /** to get the details of a customview + * @param $cvid :: Type Integer + * @returns $customviewlist Array in the following format + * $customviewlist = Array('viewname'=>value, + * 'setdefault'=>defaultchk, + * 'setmetrics'=>setmetricschk) + */ + + function getCustomViewByCvid($cvid) + { + global $adb,$current_user; + $tabid = getTabid($this->customviewmodule); + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $ssql = "select vtiger_customview.* from vtiger_customview inner join vtiger_tab on vtiger_tab.name = vtiger_customview.entitytype"; + $ssql .= " where vtiger_customview.cvid=?"; + $sparams = array($cvid); + + if($is_admin == false) { + $ssql .= " and (vtiger_customview.status=0 or vtiger_customview.userid = ? or vtiger_customview.status = 3 or vtiger_customview.userid 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."::%'))"; + array_push($sparams, $current_user->id); + } + $result = $adb->pquery($ssql, $sparams); + + $usercv_result = $adb->pquery("select default_cvid from vtiger_user_module_preferences where userid = ? and tabid = ?", array($current_user->id, $tabid)); + $def_cvid = $adb->query_result($usercv_result, 0, 'default_cvid'); + + while($cvrow=$adb->fetch_array($result)) + { + $customviewlist["viewname"] = $cvrow["viewname"]; + if((isset($def_cvid) || $def_cvid != '') && $def_cvid == $cvid) { + $customviewlist["setdefault"] = 1; + } else { + $customviewlist["setdefault"] = $cvrow["setdefault"]; + } + $customviewlist["setmetrics"] = $cvrow["setmetrics"]; + $customviewlist["userid"] = $cvrow["userid"]; + $customviewlist["status"] = $cvrow["status"]; + } + return $customviewlist; + } + + /** to get the customviewCombo for the class variable customviewmodule + * @param $viewid :: Type Integer + * $viewid will make the corresponding selected + * @returns $customviewCombo :: Type String + */ + + function getCustomViewCombo($viewid='', $markselected=true) + { + global $adb,$current_user; + global $app_strings; + $tabid = getTabid($this->customviewmodule); + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $shtml_user = ''; + $shtml_pending = ''; + $shtml_public = ''; + $shtml_others = ''; + + $selected = 'selected'; + if ($markselected == false) $selected = ''; + + $ssql = "select vtiger_customview.*, vtiger_users.user_name from vtiger_customview inner join vtiger_tab on vtiger_tab.name = vtiger_customview.entitytype + left join vtiger_users on vtiger_customview.userid = vtiger_users.id "; + $ssql .= " where vtiger_tab.tabid=?"; + $sparams = array($tabid); + + if($is_admin == false){ + $ssql .= " and (vtiger_customview.status=0 or vtiger_customview.userid = ? or vtiger_customview.status = 3 or vtiger_customview.userid 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."::%'))"; + array_push($sparams, $current_user->id); + } + $result = $adb->pquery($ssql, $sparams); + while($cvrow=$adb->fetch_array($result)) + { + if($cvrow['viewname'] == 'All') + { + $cvrow['viewname'] = $app_strings['COMBO_ALL']; + } + + $option = ''; + $viewname = $cvrow['viewname']; + if ($cvrow['status'] == CV_STATUS_DEFAULT || $cvrow['userid'] == $current_user->id) { + $disp_viewname = $viewname; + } else { + $disp_viewname = $viewname . " [" . $cvrow['user_name'] . "] "; + } + + + if($cvrow['setdefault'] == 1 && $viewid =='') + { + $option = ""; + $this->setdefaultviewid = $cvrow['cvid']; + } + elseif($cvrow['cvid'] == $viewid) + { + $option = ""; + $this->setdefaultviewid = $cvrow['cvid']; + } + else + { + $option = ""; + } + + // Add the option to combo box at appropriate section + if($option != '') { + if ($cvrow['status'] == CV_STATUS_DEFAULT || $cvrow['userid'] == $current_user->id) { + $shtml_user .= $option; + } elseif ($cvrow['status'] == CV_STATUS_PUBLIC) { + if ($shtml_public == '') + $shtml_public = ""; + $shtml_public .= $option; + } elseif ($cvrow['status'] == CV_STATUS_PENDING) { + if ($shtml_pending == '') + $shtml_pending = ""; + $shtml_pending .= $option; + } else { + if ($shtml_others == '') + $shtml_others = ""; + $shtml_others .= $option; + } + } + } + $shtml = $shtml_user; + if ($is_admin == true) $shtml .= $shtml_pending; + $shtml = $shtml . $shtml_public . $shtml_others; + return $shtml; + } + + /** to get the getColumnsListbyBlock for the given module and Block + * @param $module :: Type String + * @param $block :: Type Integer + * @returns $columnlist Array in the format + * $columnlist = Array ($fieldlabel =>'$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata', + $fieldlabel1 =>'$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1', + | + $fieldlabeln =>'$fieldtablenamen:$fieldcolnamen:$fieldnamen:$module_$fieldlabel1n:$fieldtypeofdatan') + */ + + function getColumnsListbyBlock($module,$block) + { + global $adb,$mod_strings,$app_strings; + $block_ids = explode(",", $block); + $tabid = getTabid($module); + if($tabid == 9) + $tabid ="9,16"; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $display_type = " vtiger_field.displaytype in (1,2,3)"; + + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $tab_ids = explode(",", $tabid); + $sql = "select * from vtiger_field "; + $sql.= " where vtiger_field.tabid in (". generateQuestionMarks($tab_ids) .") and vtiger_field.block in (". generateQuestionMarks($block_ids) .") and vtiger_field.presence in (0,2) and"; + $sql.= $display_type; + if($tabid == 9 || $tabid==16) + { + $sql.= " and vtiger_field.fieldname not in('notime','duration_minutes','duration_hours')"; + } + $sql.= " order by sequence"; + $params = array($tab_ids, $block_ids); + } + else + { + $tab_ids = explode(",", $tabid); + $profileList = getCurrentUserProfileList(); + $sql = "select * from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid "; + $sql.= " where vtiger_field.tabid in (". generateQuestionMarks($tab_ids) .") and vtiger_field.block in (". generateQuestionMarks($block_ids) .") and"; + $sql.= "$display_type and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + + $params = array($tab_ids, $block_ids); + + if (count($profileList) > 0) { + $sql.= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + if($tabid == 9 || $tabid==16) + { + $sql.= " and vtiger_field.fieldname not in('notime','duration_minutes','duration_hours')"; + } + + $sql.= " group by columnname order by sequence"; + } + if($tabid == '9,16') + $tabid = "9"; + $result = $adb->pquery($sql, $params); + $noofrows = $adb->num_rows($result); + //Added on 14-10-2005 -- added ticket id in list + if($module == 'HelpDesk' && $block == 25) + { + $module_columnlist['vtiger_crmentity:crmid::HelpDesk_Ticket_ID:I'] = 'Ticket ID'; + } + //Added to include vtiger_activity type in vtiger_activity vtiger_customview list + if($module == 'Calendar' && $block == 19) + { + $module_columnlist['vtiger_activity:activitytype:activitytype:Calendar_Activity_Type:V'] = 'Activity Type'; + } + + if($module == 'SalesOrder' && $block == 63) + $module_columnlist['vtiger_crmentity:crmid::SalesOrder_Order_No:I'] = $app_strings['Order No']; + + if($module == 'PurchaseOrder' && $block == 57) + $module_columnlist['vtiger_crmentity:crmid::PurchaseOrder_Order_No:I'] = $app_strings['Order No']; + + if($module == 'Quotes' && $block == 51) + $module_columnlist['vtiger_crmentity:crmid::Quotes_Quote_No:I'] = $app_strings['Quote No']; + + for($i=0; $i<$noofrows; $i++) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldtype = $adb->query_result($result,$i,"typeofdata"); + $fieldtype = explode("~",$fieldtype); + $fieldtypeofdata = $fieldtype[0]; + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + //Here we Changing the displaytype of the field. So that its criteria will be displayed Correctly in Custom view Advance Filter. + $fieldtypeofdata=ChangeTypeOfData_Filter($fieldtablename,$fieldcolname,$fieldtypeofdata); + if($fieldlabel == "Related To") + { + $fieldlabel = "Related to"; + } + if($fieldlabel == "Start Date & Time") + { + $fieldlabel = "Start Date"; + if($module == 'Calendar' && $block == 19) + $module_columnlist['vtiger_activity:time_start::Calendar_Start_Time:I'] = 'Start Time'; + + } + $fieldlabel1 = str_replace(" ","_",$fieldlabel); + if($fieldname == 'account_id' && $fieldtablename != 'vtiger_account')//Potential,Contacts,Invoice,SalesOrder & Quotes records sort by Account Name . But for account member of we have to avoid this + $optionvalue = "vtiger_account:accountname:accountname:".$module."_".$fieldlabel1.":".$fieldtypeofdata; + else if($fieldname == 'contact_id' && $module != "Contacts")//Calendar,Documents,PurchaseOrder,SalesOrder,Quotes,and Invoice records sort by Contact Name + $optionvalue = "vtiger_contactdetails:lastname:lastname:".$module."_".$fieldlabel1.":".$fieldtypeofdata; + else if($fieldname == 'product_id' && ($module != 'Products' && $module != 'HelpDesk' && $module !="Faq"))//Campaign records sort by Product Name. + $optionvalue = "vtiger_products:productname:productname:".$module."_".$fieldlabel1.":".$fieldtypeofdata; + else + $optionvalue = $fieldtablename.":".$fieldcolname.":".$fieldname.":".$module."_".$fieldlabel1.":".$fieldtypeofdata; + //added to escape attachments fields in customview as we have multiple attachments + $fieldlabel = getTranslatedString($fieldlabel); //added to support i18n issue + if($module != 'HelpDesk' || $fieldname !='filename') + $module_columnlist[$optionvalue] = $fieldlabel; + if($fieldtype[1] == "M") + { + $this->mandatoryvalues[] = "'".$optionvalue."'"; + $this->showvalues[] = $fieldlabel; + $this->data_type[$fieldlabel] = $fieldtype[1]; + } + } + return $module_columnlist; + } + + /** to get the getModuleColumnsList for the given module + * @param $module :: Type String + * @returns $ret_module_list Array in the following format + * $ret_module_list = + Array ('module' => + Array('BlockLabel1' => + Array('$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata'=>$fieldlabel, + Array('$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1'=>$fieldlabel1, + Array('BlockLabel2' => + Array('$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata'=>$fieldlabel, + Array('$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1'=>$fieldlabel1, + | + Array('BlockLabeln' => + Array('$fieldtablename:$fieldcolname:$fieldname:$module_$fieldlabel1:$fieldtypeofdata'=>$fieldlabel, + Array('$fieldtablename1:$fieldcolname1:$fieldname1:$module_$fieldlabel11:$fieldtypeofdata1'=>$fieldlabel1, + + + */ + + + function getModuleColumnsList($module) + { + + $module_info = $this->getCustomViewModuleInfo($module); + foreach($this->module_list[$module] as $key=>$value) + { + $columnlist = $this->getColumnsListbyBlock($module,$value); + + if(isset($columnlist)) + { + $ret_module_list[$module][$key] = $columnlist; + } + } + return $ret_module_list; + } + + /** to get the getModuleColumnsList for the given customview + * @param $cvid :: Type Integer + * @returns $columnlist Array in the following format + * $columnlist = Array( $columnindex => $columnname, + * $columnindex1 => $columnname1, + * | + * $columnindexn => $columnnamen) + */ + function getColumnsListByCvid($cvid) + { + global $adb; + + $sSQL = "select vtiger_cvcolumnlist.* from vtiger_cvcolumnlist"; + $sSQL .= " inner join vtiger_customview on vtiger_customview.cvid = vtiger_cvcolumnlist.cvid"; + $sSQL .= " where vtiger_customview.cvid =? order by vtiger_cvcolumnlist.columnindex"; + $result = $adb->pquery($sSQL, array($cvid)); + while($columnrow = $adb->fetch_array($result)) + { + $columnlist[$columnrow['columnindex']] = $columnrow['columnname']; + } + return $columnlist; + } + + /** to get the standard filter fields or the given module + * @param $module :: Type String + * @returns $stdcriteria_list Array in the following format + * $stdcriteria_list = Array( $tablename:$columnname:$fieldname:$module_$fieldlabel => $fieldlabel, + * $tablename1:$columnname1:$fieldname1:$module_$fieldlabel1 => $fieldlabel1, + * | + * $tablenamen:$columnnamen:$fieldnamen:$module_$fieldlabeln => $fieldlabeln) + */ + function getStdCriteriaByModule($module) + { + global $adb; + $tabid = getTabid($module); + + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $module_info = $this->getCustomViewModuleInfo($module); + foreach($this->module_list[$module] as $key=>$blockid) + { + $blockids[] = $blockid; + } + + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + $sql = "select * from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid "; + $sql.= " where vtiger_field.tabid=? and vtiger_field.block in (". generateQuestionMarks($blockids) .") + and (vtiger_field.uitype in (5,6,23) or vtiger_field.displaytype=2) "; + $sql.= " and vtiger_field.presence in (0,2) order by vtiger_field.sequence"; + $params = array($tabid, $blockids); + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "select * from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid "; + $sql.= " where vtiger_field.tabid=? and vtiger_field.block in (". generateQuestionMarks($blockids) .") and (vtiger_field.uitype in (5,6,23) or vtiger_field.displaytype=2)"; + $sql.= " and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + + $params = array($tabid, $blockids); + + if (count($profileList) > 0) { + $sql.= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + + $sql.= " order by vtiger_field.sequence"; + } + + $result = $adb->pquery($sql, $params); + + while($criteriatyperow = $adb->fetch_array($result)) + { + $fieldtablename = $criteriatyperow["tablename"]; + $fieldcolname = $criteriatyperow["columnname"]; + $fieldlabel = $criteriatyperow["fieldlabel"]; + $fieldname = $criteriatyperow["fieldname"]; + $fieldlabel1 = str_replace(" ","_",$fieldlabel); + $optionvalue = $fieldtablename.":".$fieldcolname.":".$fieldname.":".$module."_".$fieldlabel1; + $stdcriteria_list[$optionvalue] = $fieldlabel; + } + + return $stdcriteria_list; + + } + + /** to get the standard filter criteria + * @param $selcriteria :: Type String (optional) + * @returns $filter Array in the following format + * $filter = Array( 0 => array('value'=>$filterkey,'text'=>$mod_strings[$filterkey],'selected'=>$selected) + * 1 => array('value'=>$filterkey1,'text'=>$mod_strings[$filterkey1],'selected'=>$selected) + * | + * n => array('value'=>$filterkeyn,'text'=>$mod_strings[$filterkeyn],'selected'=>$selected) + */ + function getStdFilterCriteria($selcriteria = "") + { + global $mod_strings; + $filter = array(); + + $stdfilter = Array("custom"=>"".$mod_strings['Custom']."", + "prevfy"=>"".$mod_strings['Previous FY']."", + "thisfy"=>"".$mod_strings['Current FY']."", + "nextfy"=>"".$mod_strings['Next FY']."", + "prevfq"=>"".$mod_strings['Previous FQ']."", + "thisfq"=>"".$mod_strings['Current FQ']."", + "nextfq"=>"".$mod_strings['Next FQ']."", + "yesterday"=>"".$mod_strings['Yesterday']."", + "today"=>"".$mod_strings['Today']."", + "tomorrow"=>"".$mod_strings['Tomorrow']."", + "lastweek"=>"".$mod_strings['Last Week']."", + "thisweek"=>"".$mod_strings['Current Week']."", + "nextweek"=>"".$mod_strings['Next Week']."", + "lastmonth"=>"".$mod_strings['Last Month']."", + "thismonth"=>"".$mod_strings['Current Month']."", + "nextmonth"=>"".$mod_strings['Next Month']."", + "last7days"=>"".$mod_strings['Last 7 Days']."", + "last30days"=>"".$mod_strings['Last 30 Days']."", + "last60days"=>"".$mod_strings['Last 60 Days']."", + "last90days"=>"".$mod_strings['Last 90 Days']."", + "last120days"=>"".$mod_strings['Last 120 Days']."", + "next30days"=>"".$mod_strings['Next 30 Days']."", + "next60days"=>"".$mod_strings['Next 60 Days']."", + "next90days"=>"".$mod_strings['Next 90 Days']."", + "next120days"=>"".$mod_strings['Next 120 Days']."", + ); + + foreach($stdfilter as $FilterKey=>$FilterValue) + { + if($FilterKey == $selcriteria) + { + $shtml['value'] = $FilterKey; + $shtml['text'] = $FilterValue; + $shtml['selected'] = "selected"; + }else + { + $shtml['value'] = $FilterKey; + $shtml['text'] = $FilterValue; + $shtml['selected'] = ""; + } + $filter[] = $shtml; + } + return $filter; + + } + + /** to get the standard filter criteria scripts + * @returns $jsStr : Type String + * This function will return the script to set the start data and end date + * for the standard selection criteria + */ + function getCriteriaJS() + { + + + $today = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d"), date("Y"))); + $tomorrow = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); + $yesterday = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-1, date("Y"))); + + $currentmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y"))); + $currentmonth1 = date("Y-m-t"); + $lastmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")-1, "01", date("Y"))); + $lastmonth1 = date("Y-m-t", strtotime("-1 Month")); + $nextmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")+1, "01", date("Y"))); + $nextmonth1 = date("Y-m-t", strtotime("+1 Month")); + + $lastweek0 = date("Y-m-d",strtotime("-2 week Sunday")); + $lastweek1 = date("Y-m-d",strtotime("-1 week Saturday")); + + $thisweek0 = date("Y-m-d",strtotime("-1 week Sunday")); + $thisweek1 = date("Y-m-d",strtotime("this Saturday")); + + $nextweek0 = date("Y-m-d",strtotime("this Sunday")); + $nextweek1 = date("Y-m-d",strtotime("+1 week Saturday")); + + $next7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+6, date("Y"))); + $next30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+29, date("Y"))); + $next60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+59, date("Y"))); + $next90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+89, date("Y"))); + $next120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+119, date("Y"))); + + $last7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-6, date("Y"))); + $last30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-29, date("Y"))); + $last60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-59, date("Y"))); + $last90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-89, date("Y"))); + $last120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-119, date("Y"))); + + $currentFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y"))); + $currentFY1 = date("Y-m-t",mktime(0, 0, 0, "12", date("d"), date("Y"))); + $lastFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")-1)); + $lastFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")-1)); + + $nextFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")+1)); + $nextFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")+1)); + + if(date("m") <= 3) + { + $cFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y")-1)); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y")-1)); + }else if(date("m") > 3 and date("m") <= 6) + { + $pFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + + }else if(date("m") > 6 and date("m") <= 9) + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + } + else if(date("m") > 9 and date("m") <= 12) + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y")+1)); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y")+1)); + $pFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + + } + + $sjsStr = ''; + + return $sjsStr; + } + + /** to get the standard filter for the given customview Id + * @param $cvid :: Type Integer + * @returns $stdfilterlist Array in the following format + * $stdfilterlist = Array( 'columnname' => $tablename:$columnname:$fieldname:$module_$fieldlabel,'stdfilter'=>$stdfilter,'startdate'=>$startdate,'enddate'=>$enddate) + */ + + function getStdFilterByCvid($cvid) + { + global $adb; + + $sSQL = "select vtiger_cvstdfilter.* from vtiger_cvstdfilter inner join vtiger_customview on vtiger_customview.cvid = vtiger_cvstdfilter.cvid"; + $sSQL .= " where vtiger_cvstdfilter.cvid=?"; + + $result = $adb->pquery($sSQL, array($cvid)); + $stdfilterrow = $adb->fetch_array($result); + + $stdfilterlist["columnname"] = $stdfilterrow["columnname"]; + $stdfilterlist["stdfilter"] = $stdfilterrow["stdfilter"]; + + if($stdfilterrow["stdfilter"] == "custom" || $stdfilterrow["stdfilter"] == "") + { + if($stdfilterrow["startdate"] != "0000-00-00" && $stdfilterrow["startdate"] != "") + { + $stdfilterlist["startdate"] = $stdfilterrow["startdate"]; + } + if($stdfilterrow["enddate"] != "0000-00-00" && $stdfilterrow["enddate"] != "") + { + $stdfilterlist["enddate"] = $stdfilterrow["enddate"]; + } + }else //if it is not custom get the date according to the selected duration + { + $datefilter = $this->getDateforStdFilterBytype($stdfilterrow["stdfilter"]); + $stdfilterlist["startdate"] = $datefilter[0]; + $stdfilterlist["enddate"] = $datefilter[1]; + } + return $stdfilterlist; + } + + /** to get the Advanced filter for the given customview Id + * @param $cvid :: Type Integer + * @returns $stdfilterlist Array in the following format + * $stdfilterlist = Array( 0=>Array('columnname' => $tablename:$columnname:$fieldname:$module_$fieldlabel,'comparator'=>$comparator,'value'=>$value), + * 1=>Array('columnname' => $tablename1:$columnname1:$fieldname1:$module_$fieldlabel1,'comparator'=>$comparator1,'value'=>$value1), + * | + * 4=>Array('columnname' => $tablename4:$columnname4:$fieldname4:$module_$fieldlabel4,'comparator'=>$comparatorn,'value'=>$valuen), + */ + function getAdvFilterByCvid($cvid) + { + global $adb; + global $modules; + + $sSQL = "select vtiger_cvadvfilter.* from vtiger_cvadvfilter inner join vtiger_customview on vtiger_cvadvfilter.cvid = vtiger_customview.cvid"; + $sSQL .= " where vtiger_cvadvfilter.cvid=?"; + $result = $adb->pquery($sSQL, array($cvid)); + + while($advfilterrow = $adb->fetch_array($result)) + { + $advft["columnname"] = $advfilterrow["columnname"]; + $advft["comparator"] = $advfilterrow["comparator"]; + $advft["value"] = $advfilterrow["value"]; + $advfilterlist[] = $advft; + } + return $advfilterlist; + } + + + /** + * Cache information to perform re-lookups + * + * @var String + */ + protected $_fieldby_tblcol_cache = array(); + + /** + * Function to check if field is present based on + * + * @param String $columnname + * @param String $tablename + */ + function isFieldPresent_ByColumnTable($columnname, $tablename) { + global $adb; + + if(!isset($this->_fieldby_tblcol_cache[$tablename])) { + $query = 'SELECT columnname FROM vtiger_field WHERE tablename = ? and presence in (0,2)'; + + $result = $adb->pquery($query,array($tablename)); + $numrows = $adb->num_rows($result); + + if($numrows) { + $this->_fieldby_tblcol_cache[$tablename] = array(); + for($index = 0; $index < $numrows; ++$index) { + $this->_fieldby_tblcol_cache[$tablename][] = $adb->query_result($result, $index, 'columnname'); + } + } + } + // If still the field was not found (might be disabled or deleted?) + if(!isset($this->_fieldby_tblcol_cache[$tablename])) { + return false; + } + return in_array($columnname, $this->_fieldby_tblcol_cache[$tablename]); + } + + + /** to get the customview Columnlist Query for the given customview Id + * @param $cvid :: Type Integer + * @returns $getCvColumnList as a string + * This function will return the columns for the given customfield in comma seperated values in the format + * $tablename.$columnname,$tablename1.$columnname1, ------ $tablenamen.$columnnamen + * + */ + function getCvColumnListSQL($cvid) + { + global $adb; + $columnslist = $this->getColumnsListByCvid($cvid); + if(isset($columnslist)) + { + foreach($columnslist as $columnname=>$value) + { + $tablefield = ""; + if($value != "") + { + $list = explode(":",$value); + + //Added For getting status for Activities -Jaguar + $sqllist_column = $list[0].".".$list[1]; + if($this->customviewmodule == "Calendar") + { + if($list[1] == "status" || $list[1] == "eventstatus") + { + $sqllist_column = "case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end as activitystatus"; + } + } + //Added for assigned to sorting + if($list[1] == "smownerid") + { + $sqllist_column = "case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name"; + } + if($list[0] == "vtiger_contactdetails" && $list[1] == "lastname") + $sqllist_column = "vtiger_contactdetails.lastname,vtiger_contactdetails.firstname"; + $sqllist[] = $sqllist_column; + //Ends + + $tablefield[$list[0]] = $list[1]; + + //Changed as the replace of module name may replace the string if the fieldname has module name in it -- Jeri + $fieldinfo = explode('_',$list[3],2); + $fieldlabel = $fieldinfo[1]; + $fieldlabel = str_replace("_"," ",$fieldlabel); + + if($this->isFieldPresent_ByColumnTable($list[1], $list[0])){ + + $this->list_fields[$fieldlabel] = $tablefield; + $this->list_fields_name[$fieldlabel] = $list[2]; + } + } + } + $returnsql = implode(",",$sqllist); + } + return $returnsql; + } + + /** to get the customview stdFilter Query for the given customview Id + * @param $cvid :: Type Integer + * @returns $stdfiltersql as a string + * This function will return the standard filter criteria for the given customfield + * + */ + function getCVStdFilterSQL($cvid) + { + global $adb; + $stdfilterlist = $this->getStdFilterByCvid($cvid); + if(isset($stdfilterlist)) + { + foreach($stdfilterlist as $columnname=>$value) + { + if($columnname == "columnname") + { + $filtercolumn = $value; + }elseif($columnname == "stdfilter") + { + $filtertype = $value; + }elseif($columnname == "startdate") + { + $startdate = $value; + }elseif($columnname == "enddate") + { + $enddate = $value; + } + } + if($filtertype != "custom") + { + $datearray = $this->getDateforStdFilterBytype($filtertype); + $startdate = $datearray[0]; + $enddate = $datearray[1]; + } + if($startdate != "" && $enddate != "") { + $columns = explode(":",$filtercolumn); + // Fix for http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/5423 + if ($columns[1] != 'birthday') { + $stdfiltersql = $columns[0].".".$columns[1]." between '".$startdate." 00:00:00' and '".$enddate." 23:59:00'"; + } else { + $stdfiltersql = "DATE_FORMAT(".$columns[0].".".$columns[1].", '%m%d') between DATE_FORMAT('".$startdate."', '%m%d') and DATE_FORMAT('".$enddate."', '%m%d')"; + } + } + } + return $stdfiltersql; + } + /** to get the customview AdvancedFilter Query for the given customview Id + * @param $cvid :: Type Integer + * @returns $advfiltersql as a string + * This function will return the advanced filter criteria for the given customfield + * + */ + function getCVAdvFilterSQL($cvid) + { + global $current_user; + $advfilter = $this->getAdvFilterByCvid($cvid); + if(isset($advfilter)) + { + foreach($advfilter as $key=>$advfltrow) + { + if(isset($advfltrow)) + { + $columns = explode(":",$advfltrow["columnname"]); + $datatype = (isset($columns[4])) ? $columns[4] : ""; + if($advfltrow["columnname"] != "" && $advfltrow["comparator"] != "") + { + + $valuearray = explode(",",trim($advfltrow["value"])); + if(isset($valuearray) && count($valuearray) > 1) + { + $advorsql = ""; + for($n=0;$ngetRealValues($columns[0],$columns[1],$advfltrow["comparator"],trim($valuearray[$n]),$datatype); + } + //If negative logic filter ('not equal to', 'does not contain') is used, 'and' condition should be applied instead of 'or' + if($advfltrow["comparator"] == 'n' || $advfltrow["comparator"] == 'k') + $advorsqls = implode(" and ",$advorsql); + else + $advorsqls = implode(" or ",$advorsql); + $advfiltersql[] = " (".$advorsqls.") "; + }else + { + //Added for getting vtiger_activity Status -Jaguar + if($this->customviewmodule == "Calendar" && ($columns[1] == "status" || $columns[1] == "eventstatus")) + { + if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0') + { + $advfiltersql[] = "case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end".$this->getAdvComparator($advfltrow["comparator"],trim($advfltrow["value"]),$datatype); + } + else + $advfiltersql[] = "vtiger_activity.eventstatus".$this->getAdvComparator($advfltrow["comparator"],trim($advfltrow["value"]),$datatype); + } + elseif($this->customviewmodule == "Documents" && $columns[1]=='folderid'){ + $advfiltersql[] = "vtiger_attachmentsfolder.foldername".$this->getAdvComparator($advfltrow["comparator"],trim($advfltrow["value"]),$datatype); + } + else + { + $advfiltersql[] = $this->getRealValues($columns[0],$columns[1],$advfltrow["comparator"],trim($advfltrow["value"]),$datatype); + } + } + } + } + } + } + if(isset($advfiltersql)) + { + $advfsql = implode(" and ",$advfiltersql); + } + return $advfsql; + } + + /** to get the realvalues for the given value + * @param $tablename :: type string + * @param $fieldname :: type string + * @param $comparator :: type string + * @param $value :: type string + * @returns $value as a string in the following format + * $tablename.$fieldname comparator + */ + function getRealValues($tablename,$fieldname,$comparator,$value,$datatype) + { + //we have to add the fieldname/tablename.fieldname and the corresponding value (which we want) we can add here. So that when these LHS field comes then RHS value will be replaced for LHS in the where condition of the query + global $adb, $mod_strings, $currentModule, $current_user; + //Added for proper check of contact name in advance filter + if($tablename == "vtiger_contactdetails" && $fieldname == "lastname") + $fieldname = "contactid"; + + $contactid = "vtiger_contactdetails.lastname"; + if ($currentModule != "Contacts" && $currentModule != "Leads" && getFieldVisibilityPermission("Contacts", $current_user->id, 'firstname') == '0' && $currentModule != 'Campaigns') { + $contactid = "concat(vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname)"; + } + $change_table_field = Array( + + "product_id"=>"vtiger_products.productname", + "contactid"=>$contactid, + "contact_id"=>$contactid, + "accountid"=>"",//in cvadvfilter accountname is stored for Contact, Potential, Quotes, SO, Invoice + "account_id"=>"",//Same like accountid. No need to change + "vendorid"=>"vtiger_vendor.vendorname", + "vendor_id"=>"vtiger_vendor.vendorname", + "potentialid"=>"vtiger_potential.potentialname", + + "vtiger_account.parentid"=>"vtiger_account2.accountname", + "quoteid"=>"vtiger_quotes.subject", + "salesorderid"=>"vtiger_salesorder.subject", + "campaignid"=>"vtiger_campaign.campaignname", + "vtiger_contactdetails.reportsto"=>"concat(vtiger_contactdetails2.lastname,' ',vtiger_contactdetails2.firstname)", + "vtiger_pricebook.currency_id"=>"vtiger_currency_info.currency_name", + ); + + if($fieldname == "smownerid") + { + $temp_value = "( vtiger_users.user_name".$this->getAdvComparator($comparator,$value,$datatype); + $temp_value.= " OR vtiger_groups.groupname".$this->getAdvComparator($comparator,$value,$datatype); + $value=$temp_value.")"; + }elseif( $fieldname == "inventorymanager") + { + $value = $tablename.".".$fieldname.$this->getAdvComparator($comparator,getUserId_Ol($value),$datatype); + } + elseif($change_table_field[$fieldname] != '')//Added to handle special cases + { + $value = $change_table_field[$fieldname].$this->getAdvComparator($comparator,$value,$datatype); + } + elseif($change_table_field[$tablename.".".$fieldname] != '')//Added to handle special cases + { + $tmp_value = ''; + if((($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($value) == '') || (($comparator == 'n' || $comparator == 'k') && trim($value) != '')) + { + $tmp_value = $change_table_field[$tablename.".".$fieldname].' IS NULL or '; + } + $value = $tmp_value.$change_table_field[$tablename.".".$fieldname].$this->getAdvComparator($comparator,$value,$datatype); + } + elseif($fieldname == "handler") + { + $value = "vtiger_users.user_name".$this->getAdvComparator($comparator,$value,$datatype); + } + elseif(($fieldname == "crmid" && $tablename != 'vtiger_crmentity') || $fieldname == "parent_id" || $fieldname == 'parentid') + { + //For crmentity.crmid the control should not come here. This is only to get the related to modules + $value = $this->getSalesRelatedName($comparator,$value,$datatype,$tablename,$fieldname); + } + else + { + //For checkbox type values, we have to convert yes/no as 1/0 to get the values + $field_uitype = getUItype($this->customviewmodule, $fieldname); + if($field_uitype == 56) + { + if(strtolower($value) == 'yes') $value = 1; + elseif(strtolower($value) == 'no') $value = 0; + } else if(is_uitype($field_uitype, '_picklist_')) { /* Fix for tickets 4465 and 4629 */ + // Get all the keys for the for the Picklist value + $mod_keys = array_keys($mod_strings, $value); + + // Iterate on the keys, to get the first key which doesn't start with LBL_ (assuming it is not used in PickList) + foreach($mod_keys as $mod_idx=>$mod_key) { + $stridx = strpos($mod_key, 'LBL_'); + // Use strict type comparision, refer strpos for more details + if ($stridx !== 0) { + $value = $mod_key; + break; + } + } + } + //added to fix the ticket + if($this->customviewmodule == "Calendar" && ($fieldname=="status" || $fieldname=="taskstatus" || $fieldname=="eventstatus")) + { + if(getFieldVisibilityPermission("Calendar", $current_user->id,'taskstatus') == '0') + { + $value = " (case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end)".$this->getAdvComparator($comparator,$value,$datatype); + } + else + $value = " vtiger_activity.eventstatus ".$this->getAdvComparator($comparator,$value,$datatype); + } elseif ($comparator == 'e' && (trim($value) == "NULL" || trim($value) == '')) { + $value = '('.$tablename.".".$fieldname.' IS NULL OR '.$tablename.".".$fieldname.' = \'\')'; + } else { + $value = $tablename.".".$fieldname.$this->getAdvComparator($comparator,$value,$datatype); + } + //end + } + return $value; + } + + /** to get the related name for the given module + * @param $comparator :: type string, + * @param $value :: type string, + * @param $datatype :: type string, + * @returns $value :: string + */ + + function getSalesRelatedName($comparator,$value,$datatype,$tablename,$fieldname) + { + global $log; + $log->info("in getSalesRelatedName ".$comparator."==".$value."==".$datatype."==".$tablename."==".$fieldname); + global $adb; + + $adv_chk_value = $value; + $value = '('; + $sql = "select distinct(setype) from vtiger_crmentity c INNER JOIN ".$adb->sql_escape_string($tablename)." t ON t.".$adb->sql_escape_string($fieldname)." = c.crmid"; + $res=$adb->pquery($sql, array()); + for($s=0;$s<$adb->num_rows($res);$s++) + { + $modulename=$adb->query_result($res,$s,"setype"); + if($modulename == 'Vendors') + { + continue; + } + if($s != 0) + $value .= ' or '; + if($modulename == 'Accounts') + { + //By Pavani : Related to problem in calender, Ticket: 4284 and 4675 + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + if($tablename == 'vtiger_seactivityrel' && $fieldname == 'crmid') + { + $value .= 'vtiger_account2.accountname IS NULL or '; + } + else{ + $value .= 'vtiger_account.accountname IS NULL or '; + } + } + if($tablename == 'vtiger_seactivityrel' && $fieldname == 'crmid') + { + $value .= 'vtiger_account2.accountname'; + } + else{ + $value .= 'vtiger_account.accountname'; + } + } + if($modulename == 'Leads') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= " concat(vtiger_leaddetails.lastname,' ',vtiger_leaddetails.firstname) IS NULL or "; + } + $value .= " concat(vtiger_leaddetails.lastname,' ',vtiger_leaddetails.firstname)"; + } + if($modulename == 'Potentials') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + + $value .= ' vtiger_potential.potentialname IS NULL or '; + } + $value .= ' vtiger_potential.potentialname'; + } + if($modulename == 'Products') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_products.productname IS NULL or '; + } + $value .= ' vtiger_products.productname'; + } + if($modulename == 'Invoice') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_invoice.subject IS NULL or '; + } + $value .= ' vtiger_invoice.subject'; + } + if($modulename == 'PurchaseOrder') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_purchaseorder.subject IS NULL or '; + } + $value .= ' vtiger_purchaseorder.subject'; + } + if($modulename == 'SalesOrder') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_salesorder.subject IS NULL or '; + } + $value .= ' vtiger_salesorder.subject'; + } + if($modulename == 'Quotes') + { + + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_quotes.subject IS NULL or '; + } + $value .= ' vtiger_quotes.subject'; + } + if($modulename == 'Contacts') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= " concat(vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname) IS NULL or "; + } + $value .= " concat(vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname)"; + } + if($modulename == 'HelpDesk') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_troubletickets.title IS NULL or '; + } + $value .= ' vtiger_troubletickets.title'; + + } + if($modulename == 'Campaigns') + { + if(($comparator == 'e' || $comparator == 's' || $comparator == 'c') && trim($adv_chk_value) == '') + { + $value .= ' vtiger_campaign.campaignname IS NULL or '; + } + $value .= ' vtiger_campaign.campaignname'; + } + + $value .= $this->getAdvComparator($comparator,$adv_chk_value,$datatype); + } + $value .= ")"; + $log->info("in getSalesRelatedName ".$comparator."==".$value."==".$datatype."==".$tablename."==".$fieldname); + return $value; + } + + /** to get the comparator value for the given comparator and value + * @param $comparator :: type string + * @param $value :: type string + * @returns $rtvalue in the format $comparator $value + */ + + function getAdvComparator($comparator,$value,$datatype = '') + { + + global $adb, $default_charset; + $value=html_entity_decode(trim($value),ENT_QUOTES,$default_charset); + $value = $adb->sql_escape_string($value); + if($comparator == "e") + { + if(trim($value) == "NULL") + { + $rtvalue = " is NULL"; + }elseif(trim($value) != "") + { + $rtvalue = " = ".$adb->quote($value); + }elseif(trim($value) == "" && ($datatype == "V" || $datatype == "E")) + { + $rtvalue = " = ".$adb->quote($value); + }else + { + $rtvalue = " is NULL"; + } + } + if($comparator == "n") + { + if(trim($value) == "NULL") + { + $rtvalue = " is NOT NULL"; + }elseif(trim($value) != "") + { + $rtvalue = " <> ".$adb->quote($value); + }elseif(trim($value) == "" && $datatype == "V") + { + $rtvalue = " <> ".$adb->quote($value); + }elseif(trim($value) == "" && $datatype == "E") + { + $rtvalue = " <> ".$adb->quote($value); + }else + { + $rtvalue = " is NOT NULL"; + } + } + if($comparator == "s") + { + if(trim($value) == "" && ($datatype == "V" || $datatype == "E")) + { + $rtvalue = " like '". formatForSqlLike($value, 3) ."'"; + }else + { + $rtvalue = " like '". formatForSqlLike($value, 2) ."'"; + } + } + if($comparator == "ew") + { + if(trim($value) == "" && ($datatype == "V" || $datatype == "E")) + { + $rtvalue = " like '". formatForSqlLike($value, 3) ."'"; + }else + { + $rtvalue = " like '". formatForSqlLike($value, 1) ."'"; + } + } + if($comparator == "c") + { + if(trim($value) == "" && ($datatype == "V" || $datatype == "E")) + { + $rtvalue = " like '". formatForSqlLike($value, 3) ."'"; + }else + { + $rtvalue = " like '". formatForSqlLike($value) ."'"; + } + } + if($comparator == "k") + { + if(trim($value) == "" && ($datatype == "V" || $datatype == "E")) + { + $rtvalue = " not like ''"; + }else + { + $rtvalue = " not like '". formatForSqlLike($value) ."'"; + } + } + if($comparator == "l") + { + $rtvalue = " < ".$adb->quote($value); + } + if($comparator == "g") + { + $rtvalue = " > ".$adb->quote($value); + } + if($comparator == "m") + { + $rtvalue = " <= ".$adb->quote($value); + } + if($comparator == "h") + { + $rtvalue = " >= ".$adb->quote($value); + } + + return $rtvalue; + } + + /** to get the date value for the given type + * @param $type :: type string + * @returns $datevalue array in the following format + * $datevalue = Array(0=>$startdate,1=>$enddate) + */ + + function getDateforStdFilterBytype($type) + { + $thisyear = date("Y"); + $today = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d"), date("Y"))); + $tomorrow = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); + $yesterday = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-1, date("Y"))); + + $currentmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y"))); + $currentmonth1 = date("Y-m-t"); + $lastmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")-1, "01", date("Y"))); + $lastmonth1 = date("Y-m-t", strtotime("-1 Month")); + $nextmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")+1, "01", date("Y"))); + $nextmonth1 = date("Y-m-t", strtotime("+1 Month")); + + $lastweek0 = date("Y-m-d",strtotime("-2 week Sunday")); + $lastweek1 = date("Y-m-d",strtotime("-1 week Saturday")); + + $thisweek0 = date("Y-m-d",strtotime("-1 week Sunday")); + $thisweek1 = date("Y-m-d",strtotime("this Saturday")); + + $nextweek0 = date("Y-m-d",strtotime("this Sunday")); + $nextweek1 = date("Y-m-d",strtotime("+1 week Saturday")); + + $next7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+6, date("Y"))); + $next30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+29, date("Y"))); + $next60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+59, date("Y"))); + $next90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+89, date("Y"))); + $next120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+119, date("Y"))); + + $last7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-6, date("Y"))); + $last30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-29, date("Y"))); + $last60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-59, date("Y"))); + $last90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-89, date("Y"))); + $last120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-119, date("Y"))); + + $currentFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y"))); + $currentFY1 = date("Y-m-t",mktime(0, 0, 0, "12", date("d"), date("Y"))); + $lastFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")-1)); + $lastFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")-1)); + $nextFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")+1)); + $nextFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")+1)); + + if(date("m") <= 4) + { + $cFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "04","30",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "05","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "08","31",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "09","01",date("Y")-1)); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y")-1)); + }else if(date("m") > 4 and date("m") <= 8) + { + $pFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "04","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "05","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "08","31",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "09","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + + }else + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y")+1)); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "04","30",date("Y")+1)); + $pFq = date("Y-m-d",mktime(0, 0, 0, "05","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "08","31",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "09","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + } + + if($type == "today" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $today; + } + elseif($type == "yesterday" ) + { + + $datevalue[0] = $yesterday; + $datevalue[1] = $yesterday; + } + elseif($type == "tomorrow" ) + { + + $datevalue[0] = $tomorrow; + $datevalue[1] = $tomorrow; + } + elseif($type == "thisweek" ) + { + + $datevalue[0] = $thisweek0; + $datevalue[1] = $thisweek1; + } + elseif($type == "lastweek" ) + { + + $datevalue[0] = $lastweek0; + $datevalue[1] = $lastweek1; + } + elseif($type == "nextweek" ) + { + + $datevalue[0] = $nextweek0; + $datevalue[1] = $nextweek1; + } + elseif($type == "thismonth" ) + { + + $datevalue[0] =$currentmonth0; + $datevalue[1] = $currentmonth1; + } + + elseif($type == "lastmonth" ) + { + + $datevalue[0] = $lastmonth0; + $datevalue[1] = $lastmonth1; + } + elseif($type == "nextmonth" ) + { + + $datevalue[0] = $nextmonth0; + $datevalue[1] = $nextmonth1; + } + elseif($type == "next7days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next7days; + } + elseif($type == "next30days" ) + { + + $datevalue[0] =$today; + $datevalue[1] =$next30days; + } + elseif($type == "next60days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next60days; + } + elseif($type == "next90days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next90days; + } + elseif($type == "next120days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next120days; + } + elseif($type == "last7days" ) + { + + $datevalue[0] = $last7days; + $datevalue[1] = $today; + } + elseif($type == "last30days" ) + { + + $datevalue[0] = $last30days; + $datevalue[1] = $today; + } + elseif($type == "last60days" ) + { + + $datevalue[0] = $last60days; + $datevalue[1] = $today; + } + else if($type == "last90days" ) + { + + $datevalue[0] = $last90days; + $datevalue[1] = $today; + } + elseif($type == "last120days" ) + { + + $datevalue[0] = $last120days; + $datevalue[1] = $today; + } + elseif($type == "thisfy" ) + { + + $datevalue[0] = $currentFY0; + $datevalue[1] = $currentFY1; + } + elseif($type == "prevfy" ) + { + + $datevalue[0] = $lastFY0; + $datevalue[1] = $lastFY1; + } + elseif($type == "nextfy" ) + { + + $datevalue[0] = $nextFY0; + $datevalue[1] = $nextFY1; + } + elseif($type == "nextfq" ) + { + + $datevalue[0] = $nFq; + $datevalue[1] = $nFq1; + } + elseif($type == "prevfq" ) + { + + $datevalue[0] = $pFq; + $datevalue[1] = $pFq1; + } + elseif($type == "thisfq") + { + $datevalue[0] = $cFq; + $datevalue[1] = $cFq1; + } + else + { + $datevalue[0] = ""; + $datevalue[1] = ""; + } + + return $datevalue; + } + + /** to get the customview query for the given customview + * @param $viewid (custom view id):: type Integer + * @param $listquery (List View Query):: type string + * @param $module (Module Name):: type string + * @returns $query + */ + + //CHANGE : TO IMPROVE PERFORMANCE + function getModifiedCvListQuery($viewid,$listquery,$module) + { + if($viewid != "" && $listquery != "") + { + + $listviewquery = substr($listquery, strpos($listquery,'FROM'),strlen($listquery)); + if($module == "Calendar" || $module == "Emails") + { + $query = "select ".$this->getCvColumnListSQL($viewid).", vtiger_activity.activityid, vtiger_activity.activitytype as type, vtiger_activity.priority, case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end as status, vtiger_crmentity.crmid,vtiger_contactdetails.contactid ".$listviewquery; + if($module == "Calendar") + $query = str_replace('vtiger_seactivityrel.crmid,','',$query); + }else if($module == "Documents") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid,vtiger_notes.* ".$listviewquery; + } + else if($module == "Products") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid,vtiger_products.* ".$listviewquery; + } + else if($module == "Vendors") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid ".$listviewquery; + } + else if($module == "PriceBooks") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid ".$listviewquery; + } + else if($module == "Faq") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid ".$listviewquery; + } + else if($module == "Potentials" || $module == "Contacts") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid,vtiger_account.accountid ".$listviewquery; + } + else if($module == "Invoice" || $module == "SalesOrder" || $module == "Quotes") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid,vtiger_contactdetails.contactid,vtiger_account.accountid ".$listviewquery; + } + else if($module == "PurchaseOrder") + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid,vtiger_contactdetails.contactid ".$listviewquery; + } + + else + { + $query = "select ".$this->getCvColumnListSQL($viewid)." ,vtiger_crmentity.crmid ".$listviewquery; + } + $stdfiltersql = $this->getCVStdFilterSQL($viewid); + $advfiltersql = $this->getCVAdvFilterSQL($viewid); + if(isset($stdfiltersql) && $stdfiltersql != '') + { + $query .= ' and '.$stdfiltersql; + } + if(isset($advfiltersql) && $advfiltersql != '') + { + $query .= ' and '.$advfiltersql; + } + } + return $query; + } + + /** to get the Key Metrics for the home page query for the given customview to find the no of records + * @param $viewid (custom view id):: type Integer + * @param $listquery (List View Query):: type string + * @param $module (Module Name):: type string + * @returns $query + */ + function getMetricsCvListQuery($viewid,$listquery,$module) + { + if($viewid != "" && $listquery != "") + { + $listviewquery = substr($listquery, strpos($listquery,'FROM'),strlen($listquery)); + + $query = "select count(*) AS count ".$listviewquery; + + $stdfiltersql = $this->getCVStdFilterSQL($viewid); + $advfiltersql = $this->getCVAdvFilterSQL($viewid); + if(isset($stdfiltersql) && $stdfiltersql != '') + { + $query .= ' and '.$stdfiltersql; + } + if(isset($advfiltersql) && $advfiltersql != '') + { + $query .= ' and '.$advfiltersql; + } + + } + + return $query; + } + + /** to get the custom action details for the given customview + * @param $viewid (custom view id):: type Integer + * @returns $calist array in the following format + * $calist = Array ('subject'=>$subject, + 'module'=>$module, + 'content'=>$content, + 'cvid'=>$custom view id) + */ + function getCustomActionDetails($cvid) + { + global $adb; + + $sSQL = "select vtiger_customaction.* from vtiger_customaction inner join vtiger_customview on vtiger_customaction.cvid = vtiger_customview.cvid"; + $sSQL .= " where vtiger_customaction.cvid=?"; + $result = $adb->pquery($sSQL, array($cvid)); + + while($carow = $adb->fetch_array($result)) + { + $calist["subject"] = $carow["subject"]; + $calist["module"] = $carow["module"]; + $calist["content"] = $carow["content"]; + $calist["cvid"] = $carow["cvid"]; + } + return $calist; + } + + + /* This function sets the block information for the given module to the class variable module_list + * and return the array + */ + + function getCustomViewModuleInfo($module) + { + global $adb; + global $current_language; + $current_mod_strings = return_specified_module_language($current_language, $module); + $block_info = Array(); + $modules_list = explode(",", $module); + if($module == "Calendar") { + $module = "Calendar','Events"; + $modules_list = array('Calendar', 'Events'); + } + + // Tabid mapped to the list of block labels to be skipped for that tab. + $skipBlocksList = array( + getTabid('Contacts') => array('LBL_IMAGE_INFORMATION'), + getTabid('HelpDesk') => array('LBL_COMMENTS'), + getTabid('Products') => array('LBL_IMAGE_INFORMATION'), + getTabid('Faq') => array('LBL_COMMENT_INFORMATION'), + getTabid('Quotes') => array('LBL_RELATED_PRODUCTS'), + getTabid('PurchaseOrder') => array('LBL_RELATED_PRODUCTS'), + getTabid('SalesOrder') => array('LBL_RELATED_PRODUCTS'), + getTabid('Invoice') => array('LBL_RELATED_PRODUCTS') + ); + + $Sql = "select distinct block,vtiger_field.tabid,name,blocklabel from vtiger_field inner join vtiger_blocks on vtiger_blocks.blockid=vtiger_field.block inner join vtiger_tab on vtiger_tab.tabid=vtiger_field.tabid where displaytype != 3 and vtiger_tab.name in (". generateQuestionMarks($modules_list) .") and vtiger_field.presence in (0,2) order by block"; + $result = $adb->pquery($Sql, array($modules_list)); + if($module == "Calendar','Events") + $module = "Calendar"; + + $pre_block_label = ''; + while($block_result = $adb->fetch_array($result)) + { + $block_label = $block_result['blocklabel']; + $tabid = $block_result['tabid']; + // Skip certain blocks of certain modules + if(array_key_exists($tabid, $skipBlocksList) && in_array($block_label, $skipBlocksList[$tabid])) continue; + + if (trim($block_label) == '') + { + $block_info[$pre_block_label] = $block_info[$pre_block_label].",".$block_result['block']; + }else + { + $lan_block_label = $current_mod_strings[$block_label]; + if (isset($block_info[$lan_block_label]) && $block_info[$lan_block_label] != '') { + $block_info[$lan_block_label] = $block_info[$lan_block_label].",".$block_result['block']; + } else { + $block_info[$lan_block_label] = $block_result['block']; + } + } + $pre_block_label = $lan_block_label; + } + $this->module_list[$module] = $block_info; + return $this->module_list; + } + + /** + * Get the userid, status information of this custom view. + * + * @param Integer $viewid + * @return Array + */ + + function getStatusAndUserid($viewid) { + global $adb; + + if($this->_status === false || $this->_userid === false) { + $query = "SELECT status, userid FROM vtiger_customview WHERE cvid=?"; + $result = $adb->pquery($query, array($viewid)); + if($result && $adb->num_rows($result)) { + $this->_status = $adb->query_result($result, 0, 'status'); + $this->_userid = $adb->query_result($result, 0, 'userid'); + } else { + return false; + } + } + return array('status' => $this->_status, 'userid' => $this->_userid); + + } + + //Function to check if the current user is able to see the customView + function isPermittedCustomView($record_id, $action, $module) + { + global $log, $adb; + global $current_user; + $log->debug("Entering isPermittedCustomView($record_id,$action,$module) method...."); + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $permission = "yes"; + + if($record_id != '') + { + $status_userid_info = $this->getStatusAndUserid($record_id); + + if($status_userid_info) + { + $status = $status_userid_info['status']; + $userid = $status_userid_info['userid']; + + if($status == CV_STATUS_DEFAULT) + { + $log->debug("Entering when status=0"); + if($action == 'ListView' || $action == $module."Ajax" || $action == 'index' || $action == 'DetailView') + { + $permission = "yes"; + } + else + $permission = "no"; + } + elseif($is_admin) + { + $permission = 'yes'; + } + elseif ($action != 'ChangeStatus') + { + if($userid == $current_user->id) + { + $log->debug("Entering when $userid=$current_user->id"); + $permission = "yes"; + } + elseif($status == CV_STATUS_PUBLIC) + { + $log->debug("Entering when status=3"); + if($action == 'ListView' || $action == $module."Ajax" || $action == 'index') + { + $permission = "yes"; + } + else + $permission = "no"; + } + elseif($status == CV_STATUS_PRIVATE || $status == CV_STATUS_PENDING) + { + $log->debug("Entering when status=1 or 2"); + if($userid == $current_user->id) + $permission = "yes"; + else + { + /*if($action == 'ListView' || $action == $module."Ajax" || $action == 'index') + {*/ + $log->debug("Entering when status=1 or status=2 & action = ListView or $module.Ajax or index"); + $sql="select vtiger_users.id from vtiger_customview inner join vtiger_users where vtiger_customview.cvid = ? and vtiger_customview.userid 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."::%')"; + $result = $adb->pquery($sql, array($record_id)); + + while($row = $adb->fetchByAssoc($result)) + { + $temp_result[] = $row['id']; + } + $user_array = $temp_result; + if(sizeof($user_array) > 0) + { + if(!in_array($current_user->id,$user_array)) + $permission = "no"; + else + $permission = "yes"; + } + else + $permission = "no"; + /*} + else + { + $log->debug("Entering when status=1 or 2 & action = Editview or Customview"); + $permission = "no"; + }*/ + } + } + else + $permission = "yes"; + } + else + { + $log->debug("Entering else condition............"); + $permission = "no"; + } + } + else + { + $log->debug("Enters when count =0"); + $permission = 'no'; + } + } + $log->debug("Permission @@@@@@@@@@@@@@@@@@@@@@@@@@@ : $permission"); + $log->debug("Exiting isPermittedCustomView($record_id,$action,$module) method...."); + return $permission; + } + + function isPermittedChangeStatus($status) + { + global $current_user,$log; + global $current_language; + $custom_strings = return_module_language($current_language, "CustomView"); + + $log->debug("Entering isPermittedChangeStatus($status) method.............."); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $status_details = Array(); + if($is_admin) + { + if($status == CV_STATUS_PENDING) + { + $changed_status = CV_STATUS_PUBLIC; + $status_label = $custom_strings['LBL_STATUS_PUBLIC_APPROVE']; + } + elseif($status == CV_STATUS_PUBLIC) + { + $changed_status = CV_STATUS_PENDING; + $status_label = $custom_strings['LBL_STATUS_PUBLIC_DENY']; + } + $status_details = Array('Status'=>$status,'ChangedStatus'=>$changed_status,'Label'=>$status_label); + } + $log->debug("Exiting isPermittedChangeStatus($status) method.............."); + return $status_details; + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/CustomViewAjax.php b/oss/vtiger/trunk/modules/CustomView/CustomViewAjax.php new file mode 100644 index 00000000..de74ef2f --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/CustomViewAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/CustomView/Delete.php b/oss/vtiger/trunk/modules/CustomView/Delete.php new file mode 100644 index 00000000..ae42e0f7 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/Delete.php @@ -0,0 +1,31 @@ +pquery($deletesql, array($cvid)); + $_SESSION['lvs'][$module]["viewname"] = ''; +} +if(isset($smodule) && $smodule != '') +{ + $smodule_url = "&smodule=".$smodule; +} + +header("Location: index.php?action=ListView&parenttab=$parenttab&module=$module".$smodule_url); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/EditView.php b/oss/vtiger/trunk/modules/CustomView/EditView.php new file mode 100644 index 00000000..2ba836b4 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/EditView.php @@ -0,0 +1,391 @@ +>>>>> +global $oCustomView; +//<<<<<>>>>>> + +$error_msg = ''; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +require_once('modules/CustomView/CustomView.php'); + +$cv_module = vtlib_purify($_REQUEST['module']); + +$recordid = vtlib_purify($_REQUEST['record']); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("CATEGORY", getParentTab()); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("MODULE",$cv_module); +$smarty->assign("MODULELABEL",getTranslatedString($cv_module,$cv_module)); +$smarty->assign("CVMODULE", $cv_module); +$smarty->assign("CUSTOMVIEWID",$recordid); +$smarty->assign("DATEFORMAT",$current_user->date_format); +$smarty->assign("JS_DATEFORMAT",parse_calendardate($app_strings['NTC_DATE_FORMAT'])); +$smarty->assign("DATE_JS", ''); +if($recordid == "") +{ + $oCustomView = new CustomView(); + $modulecollist = $oCustomView->getModuleColumnsList($cv_module); + $log->info('CustomView :: Successfully got ColumnsList for the module'.$cv_module); + if(isset($modulecollist)) + { + $choosecolhtml = getByModule_ColumnsHTML($cv_module,$modulecollist); + } + //step2 + $stdfilterhtml = $oCustomView->getStdFilterCriteria(); + $log->info('CustomView :: Successfully got StandardFilter for the module'.$cv_module); + $stdfiltercolhtml = getStdFilterHTML($cv_module); + $stdfilterjs = $oCustomView->getCriteriaJS(); + + //step4 + $advfilterhtml = getAdvCriteriaHTML(); + for($i=1;$i<10;$i++) + { + $smarty->assign("CHOOSECOLUMN".$i,$choosecolhtml); + } + $log->info('CustomView :: Successfully got AdvancedFilter for the module'.$cv_module); + for($i=1;$i<6;$i++) + { + $smarty->assign("FOPTION".$i,$advfilterhtml); + $smarty->assign("BLOCK".$i,$choosecolhtml); + } + + $smarty->assign("STDFILTERCOLUMNS",$stdfiltercolhtml); + $smarty->assign("STDCOLUMNSCOUNT",count($stdfiltercolhtml)); + $smarty->assign("STDFILTERCRITERIA",$stdfilterhtml); + $smarty->assign("STDFILTER_JAVASCRIPT",$stdfilterjs); + + $smarty->assign("MANDATORYCHECK",implode(",",array_unique($oCustomView->mandatoryvalues))); + $smarty->assign("SHOWVALUES",implode(",",$oCustomView->showvalues)); + $data_type[] = $oCustomView->data_type; + $smarty->assign("DATATYPE",$data_type); + +} +else +{ + $oCustomView = new CustomView($cv_module); + $now_action = vtlib_purify($_REQUEST['action']); + if($oCustomView->isPermittedCustomView($recordid,$now_action,$oCustomView->customviewmodule) == 'yes') + { + $customviewdtls = $oCustomView->getCustomViewByCvid($recordid); + $log->info('CustomView :: Successfully got ViewDetails for the Viewid'.$recordid); + $modulecollist = $oCustomView->getModuleColumnsList($cv_module); + $selectedcolumnslist = $oCustomView->getColumnsListByCvid($recordid); + $log->info('CustomView :: Successfully got ColumnsList for the Viewid'.$recordid); + + $smarty->assign("VIEWNAME",$customviewdtls["viewname"]); + + if($customviewdtls["setdefault"] == 1) + { + $smarty->assign("CHECKED","checked"); + } + if($customviewdtls["setmetrics"] == 1) + { + $smarty->assign("MCHECKED","checked"); + } + $status = $customviewdtls["status"]; + $smarty->assign("STATUS",$status); + + for($i=1;$i<10;$i++) + { + $choosecolhtml = getByModule_ColumnsHTML($cv_module,$modulecollist,$selectedcolumnslist[$i-1]); + $smarty->assign("CHOOSECOLUMN".$i,$choosecolhtml); + } + + $stdfilterlist = $oCustomView->getStdFilterByCvid($recordid); + $log->info('CustomView :: Successfully got Standard Filter for the Viewid'.$recordid); + $stdfilterlist["stdfilter"] = ($stdfilterlist["stdfilter"] != "") ? ($stdfilterlist["stdfilter"]) : ("custom"); + $stdfilterhtml = $oCustomView->getStdFilterCriteria($stdfilterlist["stdfilter"]); + $stdfiltercolhtml = getStdFilterHTML($cv_module,$stdfilterlist["columnname"]); + $stdfilterjs = $oCustomView->getCriteriaJS(); + + if(isset($stdfilterlist["startdate"]) && isset($stdfilterlist["enddate"])) + { + $smarty->assign("STARTDATE",getDisplayDate($stdfilterlist["startdate"])); + $smarty->assign("ENDDATE",getDisplayDate($stdfilterlist["enddate"])); + } + else{ + $smarty->assign("STARTDATE",$stdfilterlist["startdate"]); + $smarty->assign("ENDDATE",$stdfilterlist["enddate"]); + } + + $advfilterlist = $oCustomView->getAdvFilterByCvid($recordid); + $log->info('CustomView :: Successfully got Advanced Filter for the Viewid'.$recordid,'info'); + for($i=1;$i<6;$i++) + { + $advfilterhtml = getAdvCriteriaHTML($advfilterlist[$i-1]["comparator"]); + $advcolumnhtml = getByModule_ColumnsHTML($cv_module,$modulecollist,$advfilterlist[$i-1]["columnname"]); + $smarty->assign("FOPTION".$i,$advfilterhtml); + $smarty->assign("BLOCK".$i,$advcolumnhtml); + $col = explode(":",$advfilterlist[$i-1]["columnname"]); + $temp_val = explode(",",$advfilterlist[$i-1]["value"]); + $and_text = " ".$mod_strings['LBL_AND']; + if($col[4] == 'D' || ($col[4] == 'T' && $col[1] != 'time_start' && $col[1] != 'time_end') || $col[4] == 'DT') + { + $val = Array(); + for($x=0;$xdate_format.") ".$mod_strings['LBL_AND']; + } + $smarty->assign("VALUE".$i,$advfilterlist[$i-1]["value"]); + $smarty->assign("AND_TEXT".$i,$and_text); + } + $smarty->assign("STDFILTERCOLUMNS",$stdfiltercolhtml); + $smarty->assign("STDCOLUMNSCOUNT",count($stdfiltercolhtml)); + $smarty->assign("STDFILTERCRITERIA",$stdfilterhtml); + $smarty->assign("STDFILTER_JAVASCRIPT",$stdfilterjs); + $smarty->assign("MANDATORYCHECK",implode(",",array_unique($oCustomView->mandatoryvalues))); + $smarty->assign("SHOWVALUES",implode(",",$oCustomView->showvalues)); + $smarty->assign("EXIST","true"); + $cactionhtml = ""; + + if($cv_module == "Leads" || $cv_module == "Accounts" || $cv_module == "Contacts") + { + $smarty->assign("CUSTOMACTIONBUTTON",$cactionhtml); + } + $data_type[] = $oCustomView->data_type; + $smarty->assign("DATATYPE",$data_type); + } + else + { + echo "
"; + echo "
+ + + + + + + + +
$app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; + } +} + +$smarty->assign("RETURN_MODULE", $cv_module); +if($cv_module == "Calendar") + $return_action = "ListView"; +else + $return_action = "index"; + +if($recordid == '') + $act = $mod_strings['LBL_NEW']; +else + $act = $mod_strings['LBL_EDIT']; + +$smarty->assign("ACT", $act); +$smarty->assign("RETURN_ACTION", $return_action); + +$smarty->display("CustomView.tpl"); + +function getByModule_ColumnsHTML($module,$columnslist,$selected="") +{ + global $oCustomView, $current_language,$theme; + global $app_list_strings; + $advfilter = array(); + $mod_strings = return_specified_module_language($current_language,$module); + + $check_dup = Array(); + foreach($oCustomView->module_list[$module] as $key=>$value) + { + $advfilter = array(); + $label = $key; + if(isset($columnslist[$module][$key])) + { + foreach($columnslist[$module][$key] as $field=>$fieldlabel) + { + if(!in_array($fieldlabel,$check_dup)) + { + if(isset($mod_strings[$fieldlabel])) + { + if($selected == $field) + { + $advfilter_option['value'] = $field; + $advfilter_option['text'] = $mod_strings[$fieldlabel]; + $advfilter_option['selected'] = "selected"; + }else + { + $advfilter_option['value'] = $field; + $advfilter_option['text'] = $mod_strings[$fieldlabel]; + $advfilter_option['selected'] = ""; + } + }else + { + if($selected == $field) + { + $advfilter_option['value'] = $field; + $advfilter_option['text'] = $fieldlabel; + $advfilter_option['selected'] = "selected"; + }else + { + $advfilter_option['value'] = $field; + $advfilter_option['text'] = $fieldlabel; + $advfilter_option['selected'] = ""; + } + } + $advfilter[] = $advfilter_option; + $check_dup [] = $fieldlabel; + } + } + $advfilter_out[$label]= $advfilter; + } + } + // Special case handling only for Calendar moudle - Not required for other modules. + if($module == 'Calendar') { + $finalfield = Array(); + $finalfield1 = Array(); + $finalfield2 = Array(); + $newLabel = $mod_strings['LBL_CALENDAR_INFORMATION']; + + if(isset($advfilter_out[$mod_strings['LBL_TASK_INFORMATION']])) { + $finalfield1 = $advfilter_out[$mod_strings['LBL_TASK_INFORMATION']]; + } + if(isset($advfilter_out[$mod_strings['LBL_EVENT_INFORMATION']])) { + $finalfield2 = $advfilter_out[$mod_strings['LBL_EVENT_INFORMATION']]; + } + $finalfield[$newLabel] = array_merge($finalfield1,$finalfield2); + if (isset ($advfilter_out[$mod_strings['LBL_CUSTOM_INFORMATION']])) { + $finalfield[$mod_strings['LBL_CUSTOM_INFORMATION']] = $advfilter_out[$mod_strings['LBL_CUSTOM_INFORMATION']]; + } + $advfilter_out=$finalfield; + } + return $advfilter_out; +} + + /** to get the standard filter criteria + * @param $module(module name) :: Type String + * @param $elected (selection status) :: Type String (optional) + * @returns $filter Array in the following format + * $filter = Array( 0 => array('value'=>$tablename:$colname:$fieldname:$fieldlabel,'text'=>$mod_strings[$field label],'selected'=>$selected), + * 1 => array('value'=>$$tablename1:$colname1:$fieldname1:$fieldlabel1,'text'=>$mod_strings[$field label1],'selected'=>$selected), + */ +function getStdFilterHTML($module,$selected="") +{ + global $app_list_strings, $current_language,$app_strings,$current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + global $oCustomView; + $stdfilter = array(); + $result = $oCustomView->getStdCriteriaByModule($module); + $mod_strings = return_module_language($current_language,$module); + + if(isset($result)) + { + foreach($result as $key=>$value) + { + if($value == 'Start Date & Time') + { + $value = 'Start Date'; + } + $use_module_label = getTranslatedString($module, $module); + if(isset($app_list_strings['moduleList'][$module])) { + $use_module_label = $app_list_strings['moduleList'][$module]; + } + if(isset($mod_strings[$value])) + { + if($key == $selected) + { + + $filter['value'] = $key; + $filter['text'] = $use_module_label." - ".getTranslatedString($value); + $filter['selected'] = "selected"; + }else + { + $filter['value'] = $key; + $filter['text'] = $use_module_label." - ".getTranslatedString($value); + $filter['selected'] =""; + } + } + else + { + if($key == $selected) + { + $filter['value'] = $key; + + $filter['text'] = $use_module_label." - ".$value; + $filter['selected'] = 'selected'; + }else + { + $filter['value'] = $key; + $filter['text'] = $use_module_label." - ".$value; + $filter['selected'] =''; + } + } + $stdfilter[]=$filter; + //added to fix ticket #5117. If a user doesn't have permission for a field and it has been used to fileter a custom view, it should be get displayed to him as Not Accessible. + if(!$is_admin && $selected != '' && $filter['selected'] == '') + { + $keys = explode(":",$selected); + if(getFieldVisibilityPermission($module,$current_user->id,$keys[2]) != '0') + { + $filter['value'] = "not_accessible"; + $filter['text'] = $app_strings["LBL_NOT_ACCESSIBLE"]; + $filter['selected'] = "selected"; + $stdfilter[]=$filter; + } + } + + } + + } + return $stdfilter; +} + + /** to get the Advanced filter criteria + * @param $selected :: Type String (optional) + * @returns $AdvCriteria Array in the following format + * $AdvCriteria = Array( 0 => array('value'=>$tablename:$colname:$fieldname:$fieldlabel,'text'=>$mod_strings[$field label],'selected'=>$selected), + * 1 => array('value'=>$$tablename1:$colname1:$fieldname1:$fieldlabel1,'text'=>$mod_strings[$field label1],'selected'=>$selected), + * | + * n => array('value'=>$$tablenamen:$colnamen:$fieldnamen:$fieldlabeln,'text'=>$mod_strings[$field labeln],'selected'=>$selected)) + */ +function getAdvCriteriaHTML($selected="") +{ + global $adv_filter_options; + global $app_list_strings; + $AdvCriteria = array(); + foreach($adv_filter_options as $key=>$value) + { + if($selected == $key) + { + $advfilter_criteria['value'] = $key; + $advfilter_criteria['text'] = $value; + $advfilter_criteria['selected'] = "selected"; + }else + { + $advfilter_criteria['value'] = $key; + $advfilter_criteria['text'] = $value; + $advfilter_criteria['selected'] = ""; + } + $AdvCriteria[] = $advfilter_criteria; + } + + return $AdvCriteria; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/Forms.php b/oss/vtiger/trunk/modules/CustomView/Forms.php new file mode 100644 index 00000000..6de4e159 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/Forms.php @@ -0,0 +1,253 @@ +$unused) + { + $print_required_array .= "required['$required'] = '". $all_fields[$required] . "';\n"; + + } + + $the_script = << + + + +EOQ; + + return $the_script; +} + + + + +function get_validate_upload_js () +{ + global $mod_strings; + + $err_missing_required_fields = $mod_strings['ERR_MISSING_REQUIRED_FIELDS']; + $lbl_select_file = $mod_strings['ERR_SELECT_FILE']; + $lbl_custom = $mod_strings['LBL_CUSTOM']; + + $the_script = << + + + +EOQ; + + return $the_script; +} + +function getFieldSelect(&$column_fields,$colnum,&$required_fields,$suggest_field,$translated_fields,$module) +{ + global $mod_strings; + global $app_strings; + global $outlook_contacts_field_map; + require_once('include/database/PearDatabase.php'); + global $adb; + + $output = "\n"; + + return $output; + +} + + +function get_readonly_js () +{ +?> + + + diff --git a/oss/vtiger/trunk/modules/CustomView/ListViewTop.php b/oss/vtiger/trunk/modules/CustomView/ListViewTop.php new file mode 100644 index 00000000..8e739d88 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/ListViewTop.php @@ -0,0 +1,173 @@ +Array(0=>'image name', + * 1=>'Key Metrics', + * 2=>'home_metrics' + * ), + * 'Header'=>Array(0=>'Metrics', + * 1=>'Count' + * ), + * 'Entries'=>Array($cvid=>Array( + * 0=>$customview name, + * 1=>$no of records for the view + * ), + * $cvid=>Array( + * 0=>$customview name, + * 1=>$no of records for the view + * ), + * | + * | + * $cvid=>Array( + * 0=>$customview name, + * 1=>$no of records for the view + * ) + * ) + * + */ +function getKeyMetrics($maxval,$calCnt) +{ + require_once("data/Tracker.php"); + require_once('modules/CustomView/CustomView.php'); + require_once('include/logging.php'); + require_once('include/ListView/ListView.php'); + + global $app_strings; + global $adb; + global $log; + global $current_language; + $metricviewnames = "'Hot Leads'"; + + $current_module_strings = return_module_language($current_language, "CustomView"); + $log = LoggerManager::getLogger('metrics'); + + $metriclists = getMetricList(); + + // Determine if the KeyMetrics widget should appear or not? + if($calCnt == 'calculateCnt') { + return count($metriclists); + } + + $log->info("Metrics :: Successfully got MetricList to be displayed"); + if(isset($metriclists)) + { + foreach ($metriclists as $key => $metriclist) + { + $listquery = getListQuery($metriclist['module']); + if($metriclist['module'] == 'Calendar') + $listquery .= " AND vtiger_activity.activitytype != 'Emails' "; + $oCustomView = new CustomView($metriclist['module']); + $metricsql = $oCustomView->getMetricsCvListQuery($metriclist['id'],$listquery,$metriclist['module']); + if($metriclist['module'] == "Calendar" and !$adb->isPostgres()) + $metricsql.=" group by vtiger_activity.activityid "; + + $metricresult = $adb->query($metricsql); + if($metricresult) + { + if($metriclist['module'] == "Calendar") + $metriclists[$key]['count'] = $adb->num_rows($metricresult); + else + { + $rowcount = $adb->fetch_array($metricresult); + if(isset($rowcount)) + { + $metriclists[$key]['count'] = $rowcount['count']; + } + } + } + } + $log->info("Metrics :: Successfully build the Metrics"); + } + $title=array(); + $title[]='keyMetrics.gif'; + $title[]=$app_strings['LBL_HOME_KEY_METRICS']; + $title[]='home_metrics'; + $header=Array(); + $header[]=$app_strings['LBL_HOME_METRICS']; + $header[]=$app_strings['LBL_MODULE']; + $header[]=$app_strings['LBL_HOME_COUNT']; + $entries=Array(); + if(isset($metriclists)) + { + $oddRow = true; + foreach($metriclists as $metriclist) + { + $value=array(); + $CVname = (strlen($metriclist['name']) > 20) ? (substr($metriclist['name'],0,20).'...') : $metriclist['name']; + $value[]=''.$CVname . ' ('. $metriclist['user'] .')'; + $value[]=''.getTranslatedString($metriclist['module']). ''; + $value[]=''.$metriclist['count'].''; + $entries[$metriclist['id']]=$value; + } + + } + $values=Array('Title'=>$title,'Header'=>$header,'Entries'=>$entries); + if ( ($display_empty_home_blocks ) || (count($value)!= 0) ) + return $values; + +} + + /** to get the details of a customview Entries + * @returns $metriclists Array in the following format + * $customviewlist []= Array('id'=>custom view id, + * 'name'=>custom view name, + * 'module'=>modulename, + 'count'=>'' + ) + */ +function getMetricList() +{ + global $adb, $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $ssql = "select vtiger_customview.* from vtiger_customview inner join vtiger_tab on vtiger_tab.name = vtiger_customview.entitytype"; + $ssql .= " where vtiger_customview.setmetrics = 1 "; + $sparams = array(); + + if($is_admin == false){ + $ssql .= " and (vtiger_customview.status=0 or vtiger_customview.userid = ? or vtiger_customview.status =3 or vtiger_customview.userid 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."::%'))"; + array_push($sparams, $current_user->id); + } + $ssql .= " order by vtiger_customview.entitytype"; + $result = $adb->pquery($ssql, $sparams); + while($cvrow=$adb->fetch_array($result)) + { + $metricslist = Array(); + + if(vtlib_isModuleActive($cvrow['entitytype'])){ + $metricslist['id'] = $cvrow['cvid']; + $metricslist['name'] = $cvrow['viewname']; + $metricslist['module'] = $cvrow['entitytype']; + $metricslist['user'] = getUserName($cvrow['userid']); + $metricslist['count'] = ''; + if(isPermitted($cvrow['entitytype'],"index") == "yes"){ + $metriclists[] = $metricslist; + } + } + } + + return $metriclists; +} + +?> diff --git a/oss/vtiger/trunk/modules/CustomView/PopulateCustomView.php b/oss/vtiger/trunk/modules/CustomView/PopulateCustomView.php new file mode 100644 index 00000000..0556ff37 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/PopulateCustomView.php @@ -0,0 +1,644 @@ +'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Leads','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Hot Leads', + 'setdefault'=>'0','setmetrics'=>'1','status'=>'3','userid'=>'1', + 'cvmodule'=>'Leads','stdfilterid'=>'','advfilterid'=>'0'), + + Array('viewname'=>'This Month Leads', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Leads','stdfilterid'=>'0','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Accounts','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Prospect Accounts', + 'setdefault'=>'0','setmetrics'=>'1','status'=>'3','userid'=>'1', + 'cvmodule'=>'Accounts','stdfilterid'=>'','advfilterid'=>'1'), + + Array('viewname'=>'New This Week', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Accounts','stdfilterid'=>'1','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Contacts','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Contacts Address', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Contacts','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Todays Birthday', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Contacts','stdfilterid'=>'2','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Potentials','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Potentials Won', + 'setdefault'=>'0','setmetrics'=>'1','status'=>'3','userid'=>'1', + 'cvmodule'=>'Potentials','stdfilterid'=>'','advfilterid'=>'2'), + + Array('viewname'=>'Prospecting', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Potentials','stdfilterid'=>'','advfilterid'=>'3'), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'HelpDesk','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Open Tickets', + 'setdefault'=>'0','setmetrics'=>'1','status'=>'3','userid'=>'1', + 'cvmodule'=>'HelpDesk','stdfilterid'=>'','advfilterid'=>'4'), + + Array('viewname'=>'High Prioriy Tickets', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'HelpDesk','stdfilterid'=>'','advfilterid'=>'5'), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Quotes','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Open Quotes', + 'setdefault'=>'0','setmetrics'=>'1','status'=>'3','userid'=>'1', + 'cvmodule'=>'Quotes','stdfilterid'=>'','advfilterid'=>'6'), + + Array('viewname'=>'Rejected Quotes', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Quotes','stdfilterid'=>'','advfilterid'=>'7'), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Calendar','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Emails','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Invoice','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Documents','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'PriceBooks','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Products','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'PurchaseOrder','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'SalesOrder','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Vendors','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Faq','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Campaigns','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'All', + 'setdefault'=>'1','setmetrics'=>'0','status'=>'0','userid'=>'1', + 'cvmodule'=>'Webmails','stdfilterid'=>'','advfilterid'=>''), + + Array('viewname'=>'Drafted FAQ', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Faq','stdfilterid'=>'','advfilterid'=>'8'), + + Array('viewname'=>'Published FAQ', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Faq','stdfilterid'=>'','advfilterid'=>'9'), + + Array('viewname'=>'Open Purchase Orders', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'PurchaseOrder','stdfilterid'=>'','advfilterid'=>'10'), + + Array('viewname'=>'Received Purchase Orders', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'PurchaseOrder','stdfilterid'=>'','advfilterid'=>'11'), + + Array('viewname'=>'Open Invoices', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Invoice','stdfilterid'=>'','advfilterid'=>'12'), + + Array('viewname'=>'Paid Invoices', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'Invoice','stdfilterid'=>'','advfilterid'=>'13'), + + Array('viewname'=>'Pending Sales Orders', + 'setdefault'=>'0','setmetrics'=>'0','status'=>'3','userid'=>'1', + 'cvmodule'=>'SalesOrder','stdfilterid'=>'','advfilterid'=>'14'), + ); + + +$cvcolumns = Array(Array('vtiger_leaddetails:lead_no:lead_no:Leads_Lead_No:V', + 'vtiger_leaddetails:lastname:lastname:Leads_Last_Name:V', + 'vtiger_leaddetails:firstname:firstname:Leads_First_Name:V', + 'vtiger_leaddetails:company:company:Leads_Company:V', + 'vtiger_leadaddress:phone:phone:Leads_Phone:V', + 'vtiger_leadsubdetails:website:website:Leads_Website:V', + 'vtiger_leaddetails:email:email:Leads_Email:E', + 'vtiger_crmentity:smownerid:assigned_user_id:Leads_Assigned_To:V'), + + Array('vtiger_leaddetails:firstname:firstname:Leads_First_Name:V', + 'vtiger_leaddetails:lastname:lastname:Leads_Last_Name:V', + 'vtiger_leaddetails:company:company:Leads_Company:V', + 'vtiger_leaddetails:leadsource:leadsource:Leads_Lead_Source:V', + 'vtiger_leadsubdetails:website:website:Leads_Website:V', + 'vtiger_leaddetails:email:email:Leads_Email:E'), + + Array('vtiger_leaddetails:firstname:firstname:Leads_First_Name:V', + 'vtiger_leaddetails:lastname:lastname:Leads_Last_Name:V', + 'vtiger_leaddetails:company:company:Leads_Company:V', + 'vtiger_leaddetails:leadsource:leadsource:Leads_Lead_Source:V', + 'vtiger_leadsubdetails:website:website:Leads_Website:V', + 'vtiger_leaddetails:email:email:Leads_Email:E'), + + Array('vtiger_account:account_no:account_no:Accounts_Account_No:V', + 'vtiger_account:accountname:accountname:Accounts_Account_Name:V', + 'vtiger_accountbillads:bill_city:bill_city:Accounts_City:V', + 'vtiger_account:website:website:Accounts_Website:V', + 'vtiger_account:phone:phone:Accounts_Phone:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Accounts_Assigned_To:V'), + + Array('vtiger_account:accountname:accountname:Accounts_Account_Name:V', + 'vtiger_account:phone:phone:Accounts_Phone:V', + 'vtiger_account:website:website:Accounts_Website:V', + 'vtiger_account:rating:rating:Accounts_Rating:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Accounts_Assigned_To:V'), + + Array('vtiger_account:accountname:accountname:Accounts_Account_Name:V', + 'vtiger_account:phone:phone:Accounts_Phone:V', + 'vtiger_account:website:website:Accounts_Website:V', + 'vtiger_accountbillads:bill_city:bill_city:Accounts_City:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Accounts_Assigned_To:V'), + + Array('vtiger_contactdetails:contact_no:contact_no:Contacts_Contact_Id:V', + 'vtiger_contactdetails:firstname:firstname:Contacts_First_Name:V', + 'vtiger_contactdetails:lastname:lastname:Contacts_Last_Name:V', + 'vtiger_contactdetails:title:title:Contacts_Title:V', + 'vtiger_account:accountname:accountname:Contacts_Account_Name:V', + 'vtiger_contactdetails:email:email:Contacts_Email:E', + 'vtiger_contactdetails:phone:phone:Contacts_Office_Phone:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Contacts_Assigned_To:V'), + + Array('vtiger_contactdetails:firstname:firstname:Contacts_First_Name:V', + 'vtiger_contactdetails:lastname:lastname:Contacts_Last_Name:V', + 'vtiger_contactaddress:mailingstreet:mailingstreet:Contacts_Mailing_Street:V', + 'vtiger_contactaddress:mailingcity:mailingcity:Contacts_Mailing_City:V', + 'vtiger_contactaddress:mailingstate:mailingstate:Contacts_Mailing_State:V', + 'vtiger_contactaddress:mailingzip:mailingzip:Contacts_Mailing_Zip:V', + 'vtiger_contactaddress:mailingcountry:mailingcountry:Contacts_Mailing_Country:V'), + + Array('vtiger_contactdetails:firstname:firstname:Contacts_First_Name:V', + 'vtiger_contactdetails:lastname:lastname:Contacts_Last_Name:V', + 'vtiger_contactdetails:title:title:Contacts_Title:V', + 'vtiger_account:accountname:accountname:Contacts_Account_Name:V', + 'vtiger_contactdetails:email:email:Contacts_Email:E', + 'vtiger_contactsubdetails:otherphone:otherphone:Contacts_Phone:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Contacts_Assigned_To:V'), + + Array('vtiger_potential:potential_no:potential_no:Potentials_Potential_No:V', + 'vtiger_potential:potentialname:potentialname:Potentials_Potential_Name:V', + 'vtiger_potential:related_to:related_to:Potentials_Related_To:V', + 'vtiger_potential:sales_stage:sales_stage:Potentials_Sales_Stage:V', + 'vtiger_potential:leadsource:leadsource:Potentials_Lead_Source:V', + 'vtiger_potential:closingdate:closingdate:Potentials_Expected_Close_Date:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Potentials_Assigned_To:V'), + + Array('vtiger_potential:potentialname:potentialname:Potentials_Potential_Name:V', + 'vtiger_potential:related_to:related_to:Potentials_Related_To:V', + 'vtiger_potential:amount:amount:Potentials_Amount:N', + 'vtiger_potential:closingdate:closingdate:Potentials_Expected_Close_Date:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Potentials_Assigned_To:V'), + + Array('vtiger_potential:potentialname:potentialname:Potentials_Potential_Name:V', + 'vtiger_potential:related_to:related_to:Potentials_Related_To:V', + 'vtiger_potential:amount:amount:Potentials_Amount:N', + 'vtiger_potential:leadsource:leadsource:Potentials_Lead_Source:V', + 'vtiger_potential:closingdate:closingdate:Potentials_Expected_Close_Date:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Potentials_Assigned_To:V'), + + Array(//'vtiger_crmentity:crmid::HelpDesk_Ticket_ID:I', + 'vtiger_troubletickets:ticket_no:ticket_no:HelpDesk_Ticket_No:V', + 'vtiger_troubletickets:title:ticket_title:HelpDesk_Title:V', + 'vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_To:I', + 'vtiger_troubletickets:status:ticketstatus:HelpDesk_Status:V', + 'vtiger_troubletickets:priority:ticketpriorities:HelpDesk_Priority:V', + 'vtiger_crmentity:smownerid:assigned_user_id:HelpDesk_Assigned_To:V'), + + Array('vtiger_troubletickets:title:ticket_title:HelpDesk_Title:V', + 'vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_To:I', + 'vtiger_troubletickets:priority:ticketpriorities:HelpDesk_Priority:V', + 'vtiger_troubletickets:product_id:product_id:HelpDesk_Product_Name:I', + 'vtiger_crmentity:smownerid:assigned_user_id:HelpDesk_Assigned_To:V'), + + Array('vtiger_troubletickets:title:ticket_title:HelpDesk_Title:V', + 'vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_To:I', + 'vtiger_troubletickets:status:ticketstatus:HelpDesk_Status:V', + 'vtiger_troubletickets:product_id:product_id:HelpDesk_Product_Name:I', + 'vtiger_crmentity:smownerid:assigned_user_id:HelpDesk_Assigned_To:V'), + + Array('vtiger_quotes:quote_no:quote_no:Quotes_Quote_No:V', + 'vtiger_quotes:subject:subject:Quotes_Subject:V', + 'vtiger_quotes:quotestage:quotestage:Quotes_Quote_Stage:V', + 'vtiger_quotes:potentialid:potential_id:Quotes_Potential_Name:I', + 'vtiger_account:accountname:accountname:Quotes_Account_Name:V', + 'vtiger_quotes:total:hdnGrandTotal:Quotes_Total:I', + 'vtiger_crmentity:smownerid:assigned_user_id:Quotes_Assigned_To:V'), + + Array('vtiger_quotes:subject:subject:Quotes_Subject:V', + 'vtiger_quotes:quotestage:quotestage:Quotes_Quote_Stage:V', + 'vtiger_quotes:potentialid:potential_id:Quotes_Potential_Name:I', + 'vtiger_account:accountname:accountname:Quotes_Account_Name:V', + 'vtiger_quotes:validtill:validtill:Quotes_Valid_Till:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Quotes_Assigned_To:V'), + + Array('vtiger_quotes:subject:subject:Quotes_Subject:V', + 'vtiger_quotes:potentialid:potential_id:Quotes_Potential_Name:I', + 'vtiger_account:accountname:accountname:Quotes_Account_Name:V', + 'vtiger_quotes:validtill:validtill:Quotes_Valid_Till:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Quotes_Assigned_To:V'), + + Array('vtiger_activity:status:taskstatus:Calendar_Status:V', + 'vtiger_activity:activitytype:activitytype:Calendar_Type:V', + 'vtiger_activity:subject:subject:Calendar_Subject:V', + 'vtiger_seactivityrel:crmid:parent_id:Calendar_Related_to:V', + 'vtiger_activity:date_start:date_start:Calendar_Start_Date:D', + 'vtiger_activity:due_date:due_date:Calendar_End_Date:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Calendar_Assigned_To:V'), + + Array('vtiger_activity:subject:subject:Emails_Subject:V', + 'vtiger_emaildetails:to_email:saved_toid:Emails_To:V', + 'vtiger_activity:date_start:date_start:Emails_Date_Sent:D'), + + Array('vtiger_invoice:invoice_no:invoice_no:Invoice_Invoice_No:V', + 'vtiger_invoice:subject:subject:Invoice_Subject:V', + 'vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:I', + 'vtiger_invoice:invoicestatus:invoicestatus:Invoice_Status:V', + 'vtiger_invoice:total:hdnGrandTotal:Invoice_Total:I', + 'vtiger_crmentity:smownerid:assigned_user_id:Invoice_Assigned_To:V'), + + Array('vtiger_notes:note_no:note_no:Notes_Note_No:V', + 'vtiger_notes:title:notes_title:Notes_Title:V', + 'vtiger_notes:filename:filename:Notes_File:V', + 'vtiger_crmentity:modifiedtime:modifiedtime:Notes_Modified_Time:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Notes_Assigned_To:V'), + + Array('vtiger_pricebook:pricebook_no:pricebook_no:PriceBooks_PriceBook_No:V', + 'vtiger_pricebook:bookname:bookname:PriceBooks_Price_Book_Name:V', + 'vtiger_pricebook:active:active:PriceBooks_Active:V', + 'vtiger_pricebook:currency_id:currency_id:PriceBooks_Currency:I'), + + Array('vtiger_products:product_no:product_no:Products_Product_No:V', + 'vtiger_products:productname:productname:Products_Product_Name:V', + 'vtiger_products:productcode:productcode:Products_Part_Number:V', + 'vtiger_products:commissionrate:commissionrate:Products_Commission_Rate:V', + 'vtiger_products:qtyinstock:qtyinstock:Products_Quantity_In_Stock:V', + 'vtiger_products:qty_per_unit:qty_per_unit:Products_Qty/Unit:V', + 'vtiger_products:unit_price:unit_price:Products_Unit_Price:V'), + + Array('vtiger_purchaseorder:purchaseorder_no:purchaseorder_no:PurchaseOrder_PurchaseOrder_No:V', + 'vtiger_purchaseorder:subject:subject:PurchaseOrder_Subject:V', + 'vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:I', + 'vtiger_purchaseorder:tracking_no:tracking_no:PurchaseOrder_Tracking_Number:V', + 'vtiger_purchaseorder:total:hdnGrandTotal:PurchaseOrder_Total:V', + 'vtiger_crmentity:smownerid:assigned_user_id:PurchaseOrder_Assigned_To:V'), + + Array('vtiger_salesorder:salesorder_no:salesorder_no:SalesOrder_SalesOrder_No:V', + 'vtiger_salesorder:subject:subject:SalesOrder_Subject:V', + 'vtiger_account:accountname:accountname:SalesOrder_Account_Name:V', + 'vtiger_quotes:quoteid:quote_id:SalesOrder_Quote_Name:I', + 'vtiger_salesorder:total:hdnGrandTotal:SalesOrder_Total:V', + 'vtiger_crmentity:smownerid:assigned_user_id:SalesOrder_Assigned_To:V'), + + Array('vtiger_vendor:vendor_no:vendor_no:Vendors_Vendor_No:V', + 'vtiger_vendor:vendorname:vendorname:Vendors_Vendor_Name:V', + 'vtiger_vendor:phone:phone:Vendors_Phone:V', + 'vtiger_vendor:email:email:Vendors_Email:E', + 'vtiger_vendor:category:category:Vendors_Category:V'), + + + + + Array(//'vtiger_faq:id::Faq_FAQ_Id:I', + 'vtiger_faq:faq_no:faq_no:Faq_Faq_No:V', + 'vtiger_faq:question:question:Faq_Question:V', + 'vtiger_faq:category:faqcategories:Faq_Category:V', + 'vtiger_faq:product_id:product_id:Faq_Product_Name:I', + 'vtiger_crmentity:createdtime:createdtime:Faq_Created_Time:D', + 'vtiger_crmentity:modifiedtime:modifiedtime:Faq_Modified_Time:D'), + //this sequence has to be maintained + Array('vtiger_campaign:campaign_no:campaign_no:Campaigns_Campaign_No:V', + 'vtiger_campaign:campaignname:campaignname:Campaigns_Campaign_Name:V', + 'vtiger_campaign:campaigntype:campaigntype:Campaigns_Campaign_Type:N', + 'vtiger_campaign:campaignstatus:campaignstatus:Campaigns_Campaign_Status:N', + 'vtiger_campaign:expectedrevenue:expectedrevenue:Campaigns_Expected_Revenue:V', + 'vtiger_campaign:closingdate:closingdate:Campaigns_Expected_Close_Date:D', + 'vtiger_crmentity:smownerid:assigned_user_id:Campaigns_Assigned_To:V'), + + + Array('subject:subject:subject:Subject:V', + 'from:fromname:fromname:From:N', + 'to:tpname:toname:To:N', + 'body:body:body:Body:V'), + + Array ('vtiger_faq:question:question:Faq_Question:V', + 'vtiger_faq:status:faqstatus:Faq_Status:V', + 'vtiger_faq:product_id:product_id:Faq_Product_Name:I', + 'vtiger_faq:category:faqcategories:Faq_Category:V', + 'vtiger_crmentity:createdtime:createdtime:Faq_Created_Time:T'), + + Array( 'vtiger_faq:question:question:Faq_Question:V', + 'vtiger_faq:answer:faq_answer:Faq_Answer:V', + 'vtiger_faq:status:faqstatus:Faq_Status:V', + 'vtiger_faq:product_id:product_id:Faq_Product_Name:I', + 'vtiger_faq:category:faqcategories:Faq_Category:V', + 'vtiger_crmentity:createdtime:createdtime:Faq_Created_Time:T'), + + Array( 'vtiger_purchaseorder:subject:subject:PurchaseOrder_Subject:V', + 'vtiger_purchaseorder:postatus:postatus:PurchaseOrder_Status:V', + 'vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:I', + 'vtiger_crmentity:smownerid:assigned_user_id:PurchaseOrder_Assigned_To:V', + 'vtiger_purchaseorder:duedate:duedate:PurchaseOrder_Due_Date:V'), + + Array ('vtiger_purchaseorder:subject:subject:PurchaseOrder_Subject:V', + 'vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:I', + 'vtiger_crmentity:smownerid:assigned_user_id:PurchaseOrder_Assigned_To:V', + 'vtiger_purchaseorder:postatus:postatus:PurchaseOrder_Status:V', + 'vtiger_purchaseorder:carrier:carrier:PurchaseOrder_Carrier:V', + 'vtiger_poshipads:ship_street:ship_street:PurchaseOrder_Shipping_Address:V'), + + Array( 'vtiger_invoice:invoice_no:invoice_no:Invoice_Invoice_No:V', + 'vtiger_invoice:subject:subject:Invoice_Subject:V', + 'vtiger_account:accountname:accountname:Invoice_Account_Name:V', + 'vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:I', + 'vtiger_invoice:invoicestatus:invoicestatus:Invoice_Status:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Invoice_Assigned_To:V', + 'vtiger_crmentity:createdtime:createdtime:Invoice_Created_Time:T'), + + Array( 'vtiger_invoice:invoice_no:invoice_no:Invoice_Invoice_No:V', + 'vtiger_invoice:subject:subject:Invoice_Subject:V', + 'vtiger_account:accountname:accountname:Invoice_Account_Name:V', + 'vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:I', + 'vtiger_invoice:invoicestatus:invoicestatus:Invoice_Status:V', + 'vtiger_invoiceshipads:ship_street:ship_street:Invoice_Shipping_Address:V', + 'vtiger_crmentity:smownerid:assigned_user_id:Invoice_Assigned_To:V'), + + Array( 'vtiger_salesorder:subject:subject:SalesOrder_Subject:V', + 'vtiger_account:accountname:accountname:SalesOrder_Account_Name:V', + 'vtiger_salesorder:sostatus:sostatus:SalesOrder_Status:V', + 'vtiger_crmentity:smownerid:assigned_user_id:SalesOrder_Assigned_To:V', + 'vtiger_soshipads:ship_street:ship_street:SalesOrder_Shipping_Address:V', + 'vtiger_salesorder:carrier:carrier:SalesOrder_Carrier:V'), + + ); + + + +$cvstdfilters = Array(Array('columnname'=>'vtiger_crmentity:modifiedtime:modifiedtime:Leads_Modified_Time', + 'datefilter'=>'thismonth', + 'startdate'=>'2005-06-01', + 'enddate'=>'2005-06-30'), + + Array('columnname'=>'vtiger_crmentity:createdtime:createdtime:Accounts_Created_Time', + 'datefilter'=>'thisweek', + 'startdate'=>'2005-06-19', + 'enddate'=>'2005-06-25'), + + Array('columnname'=>'vtiger_contactsubdetails:birthday:birthday:Contacts_Birthdate', + 'datefilter'=>'today', + 'startdate'=>'2005-06-25', + 'enddate'=>'2005-06-25') + ); + +$cvadvfilters = Array( + Array( + Array('columnname'=>'vtiger_leaddetails:leadstatus:leadstatus:Leads_Lead_Status:V', + 'comparator'=>'e', + 'value'=>'Hot' + ) + ), + Array( + Array('columnname'=>'vtiger_account:account_type:accounttype:Accounts_Type:V', + 'comparator'=>'e', + 'value'=>'Prospect' + ) + ), + Array( + Array('columnname'=>'vtiger_potential:sales_stage:sales_stage:Potentials_Sales_Stage:V', + 'comparator'=>'e', + 'value'=>'Closed Won' + ) + ), + Array( + Array('columnname'=>'vtiger_potential:sales_stage:sales_stage:Potentials_Sales_Stage:V', + 'comparator'=>'e', + 'value'=>'Prospecting' + ) + ), + Array( + Array('columnname'=>'vtiger_troubletickets:status:ticketstatus:HelpDesk_Status:V', + 'comparator'=>'n', + 'value'=>'Closed' + ) + ), + Array( + Array('columnname'=>'vtiger_troubletickets:priority:ticketpriorities:HelpDesk_Priority:V', + 'comparator'=>'e', + 'value'=>'High' + ) + ), + Array( + Array('columnname'=>'vtiger_quotes:quotestage:quotestage:Quotes_Quote_Stage:V', + 'comparator'=>'n', + 'value'=>'Accepted' + ), + Array('columnname'=>'vtiger_quotes:quotestage:quotestage:Quotes_Quote_Stage:V', + 'comparator'=>'n', + 'value'=>'Rejected' + ) + ), + Array( + Array('columnname'=>'vtiger_quotes:quotestage:quotestage:Quotes_Quote_Stage:V', + 'comparator'=>'e', + 'value'=>'Rejected' + ) + ), + + Array( + Array('columnname'=>'vtiger_faq:status:faqstatus:Faq_Status:V', + 'comparator'=>'e', + 'value'=>'Draft' + ) + ), + + Array( + Array('columnname'=>'vtiger_faq:status:faqstatus:Faq_Status:V', + 'comparator'=>'e', + 'value'=>'Published' + ) + ), + + Array( + Array('columnname'=>'vtiger_purchaseorder:postatus:postatus:PurchaseOrder_Status:V', + 'comparator'=>'e', + 'value'=>'Created, Approved, Delivered' + ) + ), + + Array( + Array('columnname'=>'vtiger_purchaseorder:postatus:postatus:PurchaseOrder_Status:V', + 'comparator'=>'e', + 'value'=>'Received Shipment' + ) + ), + + Array( + Array('columnname'=>'vtiger_invoice:invoicestatus:invoicestatus:Invoice_Status:V', + 'comparator'=>'e', + 'value'=>'Created, Approved, Sent' + ) + ), + + Array( + Array('columnname'=>'vtiger_invoice:invoicestatus:invoicestatus:Invoice_Status:V', + 'comparator'=>'e', + 'value'=>'Paid' + ) + ), + + Array( + Array('columnname'=>'vtiger_salesorder:sostatus:sostatus:SalesOrder_Status:V', + 'comparator'=>'e', + 'value'=>'Created, Approved' + ) + ) + + ); + +foreach($customviews as $key=>$customview) +{ + $queryid = insertCustomView($customview['viewname'],$customview['setdefault'],$customview['setmetrics'],$customview['cvmodule'],$customview['status'],$customview['userid']); + insertCvColumns($queryid,$cvcolumns[$key]); + + if(isset($cvstdfilters[$customview['stdfilterid']])) + { + $i = $customview['stdfilterid']; + insertCvStdFilter($queryid,$cvstdfilters[$i]['columnname'],$cvstdfilters[$i]['datefilter'],$cvstdfilters[$i]['startdate'],$cvstdfilters[$i]['enddate']); + } + if(isset($cvadvfilters[$customview['advfilterid']])) + { + insertCvAdvFilter($queryid,$cvadvfilters[$customview['advfilterid']]); + } +} + + /** to store the details of the customview in vtiger_customview table + * @param $viewname :: Type String + * @param $setdefault :: Type Integer + * @param $setmetrics :: Type Integer + * @param $cvmodule :: Type String + * @returns $customviewid of the stored custom view :: Type integer + */ +function insertCustomView($viewname,$setdefault,$setmetrics,$cvmodule,$status,$userid) +{ + global $adb; + + $genCVid = $adb->getUniqueID("vtiger_customview"); + + if($genCVid != "") + { + + $customviewsql = "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype,status,userid) values(?,?,?,?,?,?,?)"; + $customviewparams = array($genCVid, $viewname, $setdefault, $setmetrics, $cvmodule, $status, $userid); + $customviewresult = $adb->pquery($customviewsql, $customviewparams); + } + return $genCVid; +} + + /** to store the custom view columns of the customview in vtiger_cvcolumnlist table + * @param $cvid :: Type Integer + * @param $columnlist :: Type Array of columnlists + */ +function insertCvColumns($CVid,$columnslist) +{ + global $adb; + if($CVid != "") + { + for($i=0;$ipquery($columnsql, $columnparams); + } + } +} + + /** to store the custom view stdfilter of the customview in vtiger_cvstdfilter table + * @param $cvid :: Type Integer + * @param $filtercolumn($tablename:$columnname:$fieldname:$fieldlabel) :: Type String + * @param $filtercriteria(filter name) :: Type String + * @param $startdate :: Type String + * @param $enddate :: Type String + * returns nothing + */ +function insertCvStdFilter($CVid,$filtercolumn,$filtercriteria,$startdate,$enddate) +{ + global $adb; + if($CVid != "") + { + $stdfiltersql = "insert into vtiger_cvstdfilter(cvid,columnname,stdfilter,startdate,enddate) values (?,?,?,?,?)"; + $stdfilterparams = array($CVid, $filtercolumn, $filtercriteria, $startdate, $enddate); + $stdfilterresult = $adb->pquery($stdfiltersql, $stdfilterparams); + } +} + + /** to store the custom view advfilter of the customview in vtiger_cvadvfilter table + * @param $cvid :: Type Integer + * @param $filters :: Type Array('columnname'=>$tablename:$columnname:$fieldname:$fieldlabel,'comparator'=>$comparator,'value'=>$value) + * returns nothing + */ + +function insertCvAdvFilter($CVid,$filters) +{ + global $adb; + if($CVid != "") + { + foreach($filters as $i=>$filter) + { + $advfiltersql = "insert into vtiger_cvadvfilter(cvid,columnindex,columnname,comparator,value) values (?,?,?,?,?)"; + $advfilterparams = array($CVid, $i, $filter['columnname'], $filter['comparator'], $filter['value']); + $advfilterresult = $adb->pquery($advfiltersql, $advfilterparams); + } + } +} +?> diff --git a/oss/vtiger/trunk/modules/CustomView/Save.php b/oss/vtiger/trunk/modules/CustomView/Save.php new file mode 100644 index 00000000..d01e8699 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/Save.php @@ -0,0 +1,247 @@ +id; + + if(isset($_REQUEST["setDefault"])) { + $setdefault = 1; + } else { + $setdefault = 0; + } + + if(isset($_REQUEST["setMetrics"])) { + $setmetrics = 1; + } else { + $setmetrics = 0; + } + + //$allKeys = array_keys($HTTP_POST_VARS); + //this is will cause only the chosen fields to be added to the vtiger_cvcolumnlist table + $allKeys = array_keys($_REQUEST); + + //<<<<<<>>>>>>>>> + for ($i=0;$i>>>>>>>> + + //<<<<<<>>>>>>>> + $stdfiltercolumn = $_REQUEST["stdDateFilterField"]; + $std_filter_list["columnname"] = $stdfiltercolumn; + $stdcriteria = $_REQUEST["stdDateFilter"]; + $std_filter_list["stdfilter"] = $stdcriteria; + $startdate = $_REQUEST["startdate"]; + $enddate = $_REQUEST["enddate"]; + if($stdcriteria == "custom") { + $startdate = getDBInsertDateValue($startdate); + $enddate = getDBInsertDateValue($enddate); + } + $std_filter_list["startdate"] = $startdate; + $std_filter_list["enddate"]=$enddate; + if(empty($startdate) && empty($enddate)) + unset($std_filter_list); + //<<<<<<>>>>>>>> + + //<<<<<<>>>>>>>> + for ($i=0;$i>>>>>>> + + if(!$cvid) { + $genCVid = $adb->getUniqueID("vtiger_customview"); + if($genCVid != "") { + $customviewsql = "INSERT INTO vtiger_customview(cvid, viewname, setdefault, setmetrics, entitytype, status, userid) + VALUES (?,?,?,?,?,?,?)"; + $customviewparams = array($genCVid, $viewname, 0, $setmetrics, $cvmodule, $status, $userid); + $customviewresult = $adb->pquery($customviewsql, $customviewparams); + $log->info("CustomView :: Save :: vtiger_customview created successfully"); + + if($setdefault == 1) { + $sql_result = $adb->pquery("SELECT * FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?",array($current_user->id, $cv_tabid)); + if($adb->num_rows($sql_result) > 0) { + $updatedefaultsql = "UPDATE vtiger_user_module_preferences SET default_cvid = ? WHERE userid = ? and tabid = ?"; + $updatedefaultresult = $adb->pquery($updatedefaultsql, array($genCVid, $current_user->id, $cv_tabid)); + } else { + $insertdefaultsql = "INSERT INTO vtiger_user_module_preferences(userid, tabid, default_cvid) values (?,?,?)"; + $insertdefaultresult = $adb->pquery($insertdefaultsql, array($userid, $cv_tabid, $genCVid)); + } + } else { + $sql_result = $adb->pquery("SELECT * FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?",array($current_user->id, $cv_tabid)); + if($adb->num_rows($sql_result) > 0) { + $deletedefaultsql = "DELETE FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?"; + $deletedefaultresult = $adb->pquery($deletedefaultsql, array($current_user->id, $cv_tabid)); + } + } + + $log->info("CustomView :: Save :: setdefault upated successfully"); + + if($customviewresult) { + if(isset($columnslist)) { + for($i=0;$ipquery($columnsql, $columnparams); + } + $log->info("CustomView :: Save :: vtiger_cvcolumnlist created successfully"); + if($std_filter_list["columnname"] !="") { + $stdfiltersql = "INSERT INTO vtiger_cvstdfilter(cvid,columnname,stdfilter,startdate,enddate) VALUES (?,?,?,?,?)"; + $stdfilterparams = array($genCVid, $std_filter_list["columnname"], $std_filter_list["stdfilter"], $adb->formatDate($std_filter_list["startdate"], true), $adb->formatDate($std_filter_list["enddate"], true)); + $stdfilterresult = $adb->pquery($stdfiltersql, $stdfilterparams); + $log->info("CustomView :: Save :: vtiger_cvstdfilter created successfully"); + } + for($i=0;$ipquery($advfiltersql, $advfilterparams); + } + $log->info("CustomView :: Save :: vtiger_cvadvfilter created successfully"); + } + } + $cvid = $genCVid; + } + } else { + if($is_admin == true || $current_user->id) { + $updatecvsql = "UPDATE vtiger_customview + SET viewname = ?, setmetrics = ?, status = ? WHERE cvid = ?"; + $updatecvparams = array($viewname, $setmetrics, $status, $cvid); + $updatecvresult = $adb->pquery($updatecvsql, $updatecvparams); + $log->info("CustomView :: Save :: vtiger_customview upated successfully".$cvid); + + if($setdefault == 1) { + $sql_result = $adb->pquery("SELECT * FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?",array($current_user->id, $cv_tabid)); + if($adb->num_rows($sql_result) > 0) { + $updatedefaultsql = "UPDATE vtiger_user_module_preferences SET default_cvid = ? WHERE userid = ? and tabid = ?"; + $updatedefaultresult = $adb->pquery($updatedefaultsql, array($cvid, $current_user->id, $cv_tabid)); + } else { + $insertdefaultsql = "INSERT INTO vtiger_user_module_preferences(userid, tabid, default_cvid) values (?,?,?)"; + $insertdefaultresult = $adb->pquery($insertdefaultsql, array($userid, $cv_tabid, $cvid)); + } + } else { + $sql_result = $adb->pquery("SELECT * FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?",array($current_user->id, $cv_tabid)); + if($adb->num_rows($sql_result) > 0) { + $deletedefaultsql = "DELETE FROM vtiger_user_module_preferences WHERE userid = ? and tabid = ?"; + $deletedefaultresult = $adb->pquery($deletedefaultsql, array($current_user->id, $cv_tabid)); + } + } + $log->info("CustomView :: Save :: setdefault upated successfully".$cvid); + + $deletesql = "DELETE FROM vtiger_cvcolumnlist WHERE cvid = ?"; + $deleteresult = $adb->pquery($deletesql, array($cvid)); + + $deletesql = "DELETE FROM vtiger_cvstdfilter WHERE cvid = ?"; + $deleteresult = $adb->pquery($deletesql, array($cvid)); + + $deletesql = "DELETE FROM vtiger_cvadvfilter WHERE cvid = ?"; + $deleteresult = $adb->pquery($deletesql, array($cvid)); + $log->info("CustomView :: Save :: vtiger_cvcolumnlist,cvstdfilter,cvadvfilter deleted successfully before update".$genCVid); + + $genCVid = $cvid; + if($updatecvresult) { + if(isset($columnslist)) { + for($i=0;$ipquery($columnsql, $columnparams); + } + $log->info("CustomView :: Save :: vtiger_cvcolumnlist update successfully".$genCVid); + if($std_filter_list["columnname"] !="") { + $stdfiltersql = "INSERT INTO vtiger_cvstdfilter (cvid,columnname,stdfilter,startdate,enddate) VALUES (?,?,?,?,?)"; + $stdfilterparams = array($genCVid, $std_filter_list["columnname"], $std_filter_list["stdfilter"], $adb->formatDate($std_filter_list["startdate"], true), $adb->formatDate($std_filter_list["enddate"], true)); + $stdfilterresult = $adb->pquery($stdfiltersql, $stdfilterparams); + $log->info("CustomView :: Save :: vtiger_cvstdfilter update successfully".$genCVid); + } + for($i=0;$ipquery($advfiltersql, $advfilterparams); + } + $log->info("CustomView :: Save :: vtiger_cvadvfilter update successfully".$cvid); + } + } + } + } +} + +header("Location: index.php?action=$return_action&parenttab=$parenttab&module=$cvmodule&viewname=$cvid"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/SaveAction.php b/oss/vtiger/trunk/modules/CustomView/SaveAction.php new file mode 100644 index 00000000..221b74c8 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/SaveAction.php @@ -0,0 +1,52 @@ +pquery($customactionsql, $customactionparams); + if($customactionresult == false) + { + include('themes/'.$theme.'/header.php'); + $errormessage = "Error Message
    +
  • Error while inserting the record +

" ; + echo $errormessage; + + } + + }elseif($mode == "edit") + { + $updatecasql = "update vtiger_customaction set subject=?, content=? where cvid=?"; + $updatecaresult = $adb->pquery($updatecasql, array($subject, $body, $cvid)); + if($updatecaresult == false) + { + include('themes/'.$theme.'/header.php'); + $errormessage = "Error Message
    +
  • Error while inserting the record +

" ; + echo $errormessage; + } + } +} +header("Location: index.php?action=index&module=$cvmodule&viewname=$cvid"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/SendMailAction.php b/oss/vtiger/trunk/modules/CustomView/SendMailAction.php new file mode 100644 index 00000000..fe613206 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/SendMailAction.php @@ -0,0 +1,172 @@ +getCustomActionDetails($viewid); + if(isset($CustomActionDtls)) + { + $subject = $CustomActionDtls["subject"]; + $contents = $CustomActionDtls["content"]; + } +} + +if(trim($subject) != "") +{ + if(isset($storearray) && $camodule != "") + { + foreach($storearray as $id) + { + if($id == '') continue; + if($camodule == "Contacts") + { + $sql="select * from vtiger_contactdetails inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid where vtiger_crmentity.deleted =0 and vtiger_contactdetails.contactid=?"; + $result = $adb->pquery($sql, array($id)); + $camodulerow = $adb->fetch_array($result); + if(isset($camodulerow)) + { + $emailid = $camodulerow["email"]; + $otheremailid = $camodulerow["otheremail"]; + $yahooid = $camodulerow["yahooid"]; + + if(trim($emailid) != "") + { + SendMailtoCustomView($camodule,$id,$emailid,$current_user->id,$subject,$contents); + }elseif(trim($otheremailid) != "") + { + SendMailtoCustomView($camodule,$id,$otheremailid,$current_user->id,$subject,$contents); + }elseif(trim($yahooid) != "") + { + SendMailtoCustomView($camodule,$id,$yahooid,$current_user->id,$subject,$contents); + } + else + { + $adb->println("There is no email id for this Contact. Please give any email id."); + } + } + + }elseif($camodule == "Leads") + { + $sql="select * from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_leaddetails.leadid where vtiger_crmentity.deleted =0 and vtiger_leaddetails.leadid=?"; + $result = $adb->pquery($sql, array($id)); + $camodulerow = $adb->fetch_array($result); + if(isset($camodulerow)) + { + $emailid = $camodulerow["email"]; + $yahooid = $camodulerow["yahooid"]; + + if(trim($emailid) != "") + { + SendMailtoCustomView($camodule,$id,$emailid,$current_user->id,$subject,$contents); + } + elseif($trim($yahooid) != "") + { + SendMailtoCustomView($camodule,$id,$yahooid,$current_user->id,$subject,$contents); + } + else + { + $adb->println("There is no email id for this Lead. Please give any email id."); + } + } + }elseif($camodule == "Accounts") + { + $sql="select * from vtiger_account inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_account.accountid where vtiger_crmentity.deleted =0 and vtiger_account.accountid=?"; + $result = $adb->pquery($sql, array($id)); + $camodulerow = $adb->fetch_array($result); + if(isset($camodulerow)) + { + $emailid = $camodulerow["email1"]; + $otheremailid = $camodulerow["email2"]; + + if(trim($emailid) != "") + { + SendMailtoCustomView($camodule,$id,$emailid,$current_user->id,$subject,$contents); + } + elseif(trim($otheremailid) != "") + { + SendMailtoCustomView($camodule,$id,$otheremailid,$current_user->id,$subject,$contents); + } + else + { + $adb->println("There is no email id for this Account. Please give any email id."); + } + } + } + } + } +} + +function SendMailtoCustomView($module,$id,$to,$current_user_id,$subject,$contents) +{ + + require_once("modules/Emails/class.phpmailer.php"); + + $mail = new PHPMailer(); + + $mail->Subject = $subject; + $mail->Body = nl2br($contents); + $mail->IsSMTP(); + + if($current_user_id != '') + { + global $adb; + $sql = "select * from vtiger_users where id= ?"; + $result = $adb->pquery($sql, array($current_user_id)); + $from = $adb->query_result($result,0,'email1'); + $initialfrom = $adb->query_result($result,0,'user_name'); + } + global $adb; + $mailserverresult=$adb->pquery("select * from vtiger_systems where server_type=?", array('email')); + $mail_server = $adb->query_result($mailserverresult,0,'server'); + $mail_server_username = $adb->query_result($mailserverresult,0,'server_username'); + $mail_server_password = $adb->query_result($mailserverresult,0,'server_password'); + $smtp_auth = $adb->query_result($mailserverresult,0,'smtp_auth'); + + $adb->println("Mail Server Details : '".$mail_server."','".$mail_server_username."','".$mail_server_password."'"); + $_REQUEST['server']=$mail_server; + + $mail->Host = $mail_server; + $mail->SMTPAuth = $smtp_auth; + $mail->Username = $mail_server_username; + $mail->Password = $mail_server_password; + $mail->From = $from; + $mail->FromName = $initialfrom; + + $mail->AddAddress($to); + $mail->AddReplyTo($from); + $mail->WordWrap = 50; + + $mail->IsHTML(true); + $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; + + $adb->println("Mail sending process : To => '".$to."', From => '".$from."'"); + if(!$mail->Send()) + { + $adb->println("(CustomView/SendMailAction.php) Error in Mail Sending : ".$mail->ErrorInfo); + $errormsg = "Mail Could not be sent..."; + } + else + { + $adb->println("(CustomView/SendMailAction.php) Mail has been Sent to => ".$to); + } + +} +header("Location: index.php?action=index&module=$camodule&viewname=$viewid"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomView/index.php b/oss/vtiger/trunk/modules/CustomView/index.php new file mode 100644 index 00000000..1b6d9296 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/index.php @@ -0,0 +1,17 @@ + diff --git a/oss/vtiger/trunk/modules/CustomView/language/en_us.lang.php b/oss/vtiger/trunk/modules/CustomView/language/en_us.lang.php new file mode 100644 index 00000000..48a6ff9b --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/language/en_us.lang.php @@ -0,0 +1,285 @@ +'Custom View', +'LBL_STEP_1_TITLE'=>'View Information', +'LBL_VIEW_NAME'=>'View Name:', +'LBL_SETDEFAULT'=>'Set as Default', +'LBL_LIST_IN_METRICS'=>'List in Metrics', +'LBL_STEP_2_TITLE'=>'Choose Columns', +'LBL_STEP_3_TITLE'=>'Standard Filters', +'LBL_STEP_4_TITLE'=>'Advanced Filters', +'LBL_STEP_5_TITLE'=>'Access Information', +'LBL_SF_COLUMNS'=>'Column', +'LBL_SF_STARTDATE'=>'Start Date', +'LBL_SF_ENDDATE'=>'End Date', +'LBL_AF_HDR1'=>'Set the search conditions to further restrict the list.', +'LBL_AF_HDR2'=>'You can use "or" filters by entering multiple +items in the third column.', +'LBL_AF_HDR3'=>'You can enter up to 10 items, separated by commas. For +example: CA, NY, TX, FL searches for CA or NY or TX or FL.', +'LBL_AF_HDR4'=>'If "Activity Type" is selected, give any one of the +following values "Call","Meeting" or "Task".', + +//strings added for vtiger 5, date format... +'LBL_NONE'=>'None', +'View_Name'=>'View_Name', +'LBL_AND'=>'And', +'LBL_DATE_FORMAT_CUSTOMVIEW'=>'Y-m-d', +//Strings added for filter +'Custom'=>'Custom', +'Previous FY'=>'Previous FY', +'Current FY'=>'Current FY', +'Next FY'=>'Next FY', +'Previous FQ'=>'Previous FQ', +'Current FQ'=>'Current FQ', +'Next FQ'=>'Next FQ', +'Yesterday'=>'Yesterday', +'Today'=>'Today', +'Tomorrow'=>'Tomorrow', +'Last Week'=>'Last Week', +'Current Week'=>'Current Week', +'Next Week'=>'Next Week', +'Last Month'=>'Last Month', +'Current Month'=>'Current Month', +'Next Month'=>'Next Month', +'Last 7 Days'=>'Last 7 Days', +'Last 30 Days'=>'Last 30 Days', +'Last 60 Days'=>'Last 60 Days', +'Last 90 Days'=>'Last 90 Days', +'Last 120 Days'=>'Last 120 Days', +'Next 30 Days'=>'Next 30 Days', +'Next 60 Days'=>'Next 60 Days', +'Next 90 Days'=>'Next 90 Days', +'Next 120 Days'=>'Next 120 Days', + +'equals'=>'equals', +'contains'=>'Contains', +'does not contain'=>'does not contain', +'less than'=>'less than', +'greater than'=>'greater than', +'less or equal'=>'less or equal', +'greater or equal'=>'greater or equal', + +//Strings added to translate field label vtiger_groups +'Address'=>'Address', +'Information'=>'Information', +'Description'=>'Description', +'Custom Information'=>'Custom Information', +'- Event Information'=>'- Event Information', +'- Event Description'=>'- Event Description', +'- Task Information'=>'- Task Information', +'- Task Description'=>'- Task Description', + +//Strings added for helpdesk module fields +'Title'=>'Title', +'Assigned To'=>'Assigned To', +'Related to'=>'Related to', +'Priority'=>'Priority', +'Product Name'=>'Product Name', +'Severity'=>'Severity', +'Status'=>'Status', +'Category'=>'Category', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Attachment'=>'Attachment', + +//Strings added for Leads module fields +'First Name'=>'First Name', +'Phone'=>'Phone', +'Last Name'=>'Last Name', +'Company'=>'Company', +'Lead Source'=>'Lead Source', +'Website'=>'Website', +'Industry'=>'Industry', +'Lead Status'=>'Lead Status', +'Annual Revenue'=>'Annual Revenue', +'Rating'=>'Rating', +'No Of Employees'=>'No of Employees', +'Street'=>'Street', +'Po Box'=>'PO Box', +'Postal Code'=>'Postal Code', +'City'=>'City', +'Country'=>'Country', +'State'=>'State', + +//Strings added for Accounts module fields +'Account Name'=>'Account Name', +'Ticker Symbol'=>'Ticker Symbol', +'Other Phone'=>'Other Phone', +'Member Of'=>'Member Of', +'Employees'=>'Employees', +'Other Email'=>'Other Email', +'Ownership'=>'Ownership', +'industry'=>'industry', +'SIC Code'=>'SIC Code', +'Email Opt Out'=>'Email Opt Out', +'Billing Address'=>'Billing Address', +'Shipping Address'=>'Shipping Address', +'Shipping Po Box'=>'Shipping PO Box', +'Billing Po Box'=>'Billing PO Box', +'Billing City'=>'Billing City', +'Shipping City'=>'Shipping City', +'Billing State'=>'Billing State', +'Shipping State'=>'Shipping State', +'Billing Code'=>'Billing Code', +'Shipping Code'=>'Shipping Code', +'Shipping Country'=>'Shipping Country', +'Billing Country'=>'Billing Country', + + +//Strings added for Contacts module fields + +'Office Phone'=>'Office Phone', +'Home Phone'=>'Home Phone', +'Birthdate'=>'Birthdate', +'Reports To'=>'Reports To', +'Assistant Phone'=>'Assistant Phone', +'Do Not Call'=>'Do Not Call', +'Mailing Street'=>'Mailing Street', +'Other Street'=>'Other Street', +'Mailing Po Box'=>'Mailing PO Box', +'Other Po Box'=>'Other PO Box', +'Mailing City'=>'Mailing City', +'Other City'=>'Other City', +'Mailing State'=>'Mailing State', +'Other State'=>'Other State', +'Mailing Zip'=>'Mailing Zip', +'Other Zip'=>'Other Zip', +'Mailing Country'=>'Mailing Country', +'Other Country'=>'Other Country', + + +//Strings added for Potential module fields + +'Potential Name'=>'Potential Name', +'Amount'=>'Amount', +'Expected Close Date'=>'Expected Close Date', +'Next Step'=>'Next Step', +'Sales Stage'=>'Sales Stage', +'Probability'=>'Probability', + + +//Strings added for Quotes module fields +'Subject'=>'Subject', +'Quote Stage'=>'Quote Stage', +'Valid Till'=>'Valid Till', +'Team'=>'Team', +'Contact Name'=>'Contact Name', +'Carrier'=>'Carrier', +'Shipping'=>'Shipping', +'Inventory Manager'=>'Inventory Manager', + +//Strings added for Sales Orders module fields +'Customer No'=>'Customer No', +'Quote Name'=>'Quote Name', +'Purchase Order'=>'Purchase Order', +'Due Date'=>'Due Date', +'Pending'=>'Pending', +'Sales Commission'=>'Sales Commission', +'Excise Duty'=>'Excise Duty', + +//Strings added for Invoices module fields +'Sales Order'=>'Sales Order', +'Invoice Date'=>'Invoice Date', + +//Strings added for Product module fields +'Product Active'=>'Product Active', +'Product Category'=>'Product Category', +'Sales Start Date'=>'Sales Start Date', +'Sales End Date'=>'Sales End Date', +'Support Start Date'=>'Support Start Date', +'Support Expiry Date'=>'Support Expiry Date', +'Vendor Name'=>'Vendor Name', +'Mfr PartNo'=>'Mfr PartNo', +'Vendor PartNo'=>'Vendor PartNo', + +'Serial No'=>'Serial No', +'Product Sheet'=>'Product Sheet', +'GL Account'=>'GL Account', + +//Strings added for Price book module fields +'Price Book Name'=>'Price Book Name', +'Active'=>'Active', + +//Strings added for tasks & events module fields +'Start Date & Time'=>'Start Date & Time', + +//error message +'Missing required fields'=>'Missing required vtiger_fields', +//Strings added for campaigns +'Campaign Name'=>'Campaign Name', +'Campaign Type'=>'Campaign Type', +'Product'=>'Product', +'Campaign Status'=>'Campaign Status', +'Expected Revenue'=>'Expected Revenue', +'Budget Cost'=>'Budget Cost', +'Actual Cost'=>'Actual Cost', +'Expected Response'=>'Expected Response', +'Num Sent'=>'Num Sent', +'Target Audience'=>'Target Audience', +'TargetSize'=>'TargetSize', +'Sponsor'=>'Sponsor', +'Expected Sales Count'=>'Expected Sales Count', +'Expected Response Count'=>'Expected Response Count', +'Expected ROI'=>'Expected ROI', +'Actual Sales Count'=>'Actual Sales Count', +'Actual Response Count'=>'Actual Response Count', +'Actual ROI'=>'Actual ROI', + + + +//Added for customview.tpl + +'LBL_Select_a_Column'=>'Select a Column', +'Missing_required_fields'=>'Missing required fields', +'Details'=>'Details', +'New_Custom_View'=>'New Custom view', +'Edit_Custom_View'=>'Edit Custom View', +'LBL_AF_HDR5'=>'Simple Time Filter allows you to select date based on +Account Created Time or Account Modified Time', +'Select_Duration'=>'Select Duration', +'Simple_Time_Filter'=>'Simple Time Filter', +'Start_Date'=>'Start Date', +'End_Date'=>'End Date', +'LBL_RULE'=>'RULE', + +// Added/Updated for vtiger CRM 5.0.4 +'not equal to'=>'Not equal to', +'starts with'=>'Starts with', +'ends with'=>'Ends with', +//'Product Code'=>'Product Code', + +// Added after 5.0.4 GA + +//Added for Role based Custom filters +'LBL_SET_AS_PUBLIC'=>'Set as Public ', +'LBL_NEW'=>'New', +'LBL_EDIT'=>'Edit', +'LBL_STATUS_PUBLIC_APPROVE'=>'Approve', +'LBL_STATUS_PUBLIC_DENY'=>'Deny' +); +?> diff --git a/oss/vtiger/trunk/modules/CustomView/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/CustomView/language/zh_cn.lang.php new file mode 100644 index 00000000..eca7e645 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomView/language/zh_cn.lang.php @@ -0,0 +1,282 @@ + '自订检视表', + 'LBL_STEP_1_TITLE' => '检视表信息', + 'LBL_VIEW_NAME' => '检视表名称:', + 'LBL_SETDEFAULT' => '默认值', + 'LBL_LIST_IN_METRICS' => '制式化列表', + 'LBL_STEP_2_TITLE' => '选择字段', + 'LBL_STEP_3_TITLE' => '标准规则', + 'LBL_STEP_4_TITLE' => '进阶规则', + 'LBL_STEP_5_TITLE' => '存取信息', + 'LBL_SF_COLUMNS' => '字段', + 'LBL_SF_STARTDATE' => '开始日期', + 'LBL_SF_ENDDATE' => '结束日期', + 'LBL_AF_HDR1' => '设定搜寻条件来缩小范围', + 'LBL_AF_HDR2' => '您可以在第三个字段输入多个项目,之前用"or"分开 ', + 'LBL_AF_HDR3' => '您最多可以输入10个项目,以逗号分隔。例如CA,NY,TX,FL会尝试搜寻CA或NY或TX或FL。', + 'LBL_AF_HDR4' => '如果选择了"活动类型",请输入 "Call"、"Meeting" 或是 "Task"。', + +//strings added for vtiger 5, date format... + 'LBL_NONE' => '无', + 'View_Name' => '检视名称', + 'LBL_AND' => '且', + 'LBL_DATE_FORMAT_CUSTOMVIEW' => '年-月-日', +//Strings added for filter + 'Custom' => '自订', + 'Previous FY' => '上一个财务年度', + 'Current FY' => '目前财务年度', + 'Next FY' => '下一个财务年度', + 'Previous FQ' => '上一个财务季', + 'Current FQ' => '目前财务季', + 'Next FQ' => '下一个财务季', + 'Yesterday' => '昨天', + 'Today' => '今天', + 'Tomorrow' => '明天', + 'Last Week' => '上周', + 'Current Week' => '这周', + 'Next Week' => '下周', + 'Last Month' => '上个月', + 'Current Month' => '这个月', + 'Next Month' => '下个月', + 'Last 7 Days' => '过去七天', + 'Last 30 Days' => '过去 30 天', + 'Last 60 Days' => '过去 60 天', + 'Last 90 Days' => '过去 90 天', + 'Last 120 Days' => '过去 120 天', + 'Next 30 Days' => '未来 30 天', + 'Next 60 Days' => '未来 60 天', + 'Next 90 Days' => '未来 90 天', + 'Next 120 Days' => '未来 120 天', + + 'equals' => '等于', + 'not_equal_to' => '不等于', + 'starts_with' => '开始于', + 'contains' => '包含', + 'does_not_contain' => '不包含', + 'less_than' => '少于', + 'greater_than' => '大于', + 'less_or_equal' => '少于或等于', + 'greater_or_equal' => '大于或等于', + +//Strings added to translate field label vtiger_groups + 'Address' => '住址', + 'Information' => '信息', + 'Description' => '说明', + 'Custom Information' => '自订信息', + '- Event Information' => '- 事件信息', + '- Event Description' => '- 事件说明', + '- Task Information' => '- 任务信息', + '- Task Description' => '- 任务说明', + +//Strings added for helpdesk module fields + 'Title' => '标题', + 'Assigned To' => '负责人', + 'Related to' => '关联', + 'Priority' => '优先序', + 'Product Name' => '产品名称', + 'Severity' => '严重', + 'Status' => '状态', + 'Category' => '类别', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Attachment' => '附加档案', + +//Strings added for Leads module fields + 'First Name' => '姓名', + 'Phone' => '电话', + 'Last Name' => '姓氏', + 'Company' => '公司', + 'Lead Source' => '准客户来源', + 'Website' => '网站', + 'Industry' => '行业', + 'Lead Status' => '准客户状态', + 'Annual Revenue' => '年营业额', + 'Rating' => '评比', + 'No Of Employees' => '员工人数', + 'Street' => '街道巷弄', + 'Po Box' => '邮政信箱', + 'Postal Code' => '邮政编码', + 'City' => '乡镇市区', + 'Country' => '国家', + 'State' => '县市', + +//Strings added for Accounts module fields +'Account Name' => '公司名称', + 'Ticker Symbol' => '传票符号', + 'Other Phone' => '其它电话', + 'Member Of' => '群组', + 'Employees' => '员工', + 'Other Email' => '其它信箱', + 'Ownership' => '负责人', + 'industry' => '产业', + 'SIC Code' => '统一编号', + 'Email Opt Out' => '拒绝邮件打扰', + 'Billing Address' => '付款住址', + 'Shipping Address' => '送货住址', + 'Shipping Po Box' => '[送货住址]邮政信箱', + 'Billing Po Box' => '[付款住址]邮政信箱', + 'Billing City' => '[付款住址]乡镇市区', + 'Shipping City' => '[送货住址]乡镇市区', + 'Billing State' => '[付款住址]县市', + 'Shipping State' => '[送货住址]县市', + 'Billing Code' => '[付款住址]邮政编码', + 'Shipping Code' => '[送货住址]邮政编码', + 'Shipping Country' => '[送货住址]国家', + 'Billing Country' => '[付款住址]国家', + + +//Strings added for Contacts module fields + + 'Office Phone' => '办公室电话', + 'Home Phone' => '住家电话', + 'Birthdate' => '生日', + 'Reports To' => '回报给', + 'Assistant Phone' => '助理电话', + 'Do Not Call' => '拒绝电话打扰', + 'Mailing Street' => '街道巷弄', + 'Other Street' => '[其它]街道巷弄', + 'Mailing Po Box' => '邮政信箱', + 'Other Po Box' => '[其它]邮政信箱', + 'Mailing City' => '乡镇市区', + 'Other City' => '[其它]乡镇市区', + 'Mailing State' => '县市', + 'Other State' => '[其它]县市', + 'Mailing Zip' => '邮政编码', + 'Other Zip' => '[其它]邮政编码', + 'Mailing Country' => '国家', + 'Other Country' => '[其它]国家', + + +//Strings added for Potential module fields + + 'Potential Name' => '潜在机会名称', + 'Amount' => '金额', + 'Expected Close Date' => '预期结案日期', + 'Next Step' => '下一步', + 'Sales Stage' => '销售策略', + 'Probability' => '可能性', + + +//Strings added for Quotes module fields + 'Subject' => '主旨', + 'Quote Stage' => '报价策略', + 'Valid Till' => '有效日期', + 'Team' => '团队', + 'Contact Name' => '联系人名称', + 'Carrier' => '货运商', + 'Shipping' => '船运商', + 'Inventory Manager' => '库存管理', + +//Strings added for Sales Orders module fields + 'Customer No' => '客户编号', + 'Quote Name' => '报价单名称', + 'Purchase Order' => '采购订单', + 'Due Date' => '结束日期', + 'Pending' => '暂缓', + 'Sales Commission' => '销售佣金', + 'Excise Duty' => '关税', + +//Strings added for Invoices module fields + 'Sales Order' => '销售订单', + 'Invoice Date' => '发票日期', + +//Strings added for Product module fields +'Product Code' => '产品代号', + 'Product Active' => '产品状态', + 'Product Category' => '产品类别', + 'Sales Start Date' => '开始销售日期', + 'Sales End Date' => '结束销售日期', + 'Support Start Date' => '开始支持日期', + 'Support Expiry Date' => '结束支持日期', + 'Vendor Name' => '厂商名称', + 'Mfr PartNo' => '工厂零件代号', + 'Vendor PartNo' => '厂商零件代号', + +'Serial No' => '序号', + 'Product Sheet' => '产品型录', + 'GL Account' => '会计科目', + +//Strings added for Price book module fields + 'Price Book Name' => '价格表名称', + 'Active' => '启用', + +//Strings added for tasks & events module fields + 'Start Date & Time' => '开始日期与时间', + +//error message + 'Missing required fields' => '缺少必要字段', +//Strings added for campaigns +'Campaign Name' => '活动名称', + 'Campaign Type' => '活动类型', + 'Product' => '产品', + 'Campaign Status' => '活动状态', + 'Expected Revenue' => '预期收益', + 'Budget Cost' => '预算', + 'Actual Cost' => '实际成本', + 'Expected Response' => '预期回应', + 'Num Sent' => '寄发数量', + 'Target Audience' => '目标族群', + 'TargetSize' => '目标数量', + 'Sponsor' => '赞助商', + 'Expected Sales Count' => '预期销售量', + 'Expected Response Count' => '预期回应量', + 'Expected ROI' => '预期收益', + 'Actual Sales Count' => '实际销售量', + 'Actual Response Count' => '实际回应量', + 'Actual ROI' => '实际收益', + + + +//Added for customview.tpl + + 'LBL_Select_a_Column' => '选择字段', + 'Missing_required_fields' => '缺少必要字段', + 'Details' => '细节', + 'New_Custom_View' => '新增自订检视', + 'LBL_AF_HDR5' => '简易时间过滤可以让您选择介于客户建立时间与异动时间之间的日期', + 'Select_Duration' => '选择期间', + 'Simple_Time_Filter' => '简易时间过滤', + 'Start_Date' => '开始日期', + 'End_Date' => '结束日期', + 'LBL_RULE' => '规则', +// Added/Updated for vtiger CRM 5.0.4 +'not equal to'=>'不等于', +'starts with'=>'开始于', +'ends with'=>'结束于', +//'Product Code'=>'产品编号', + +// Added after 5.0.4 GA + +//Added for Role based Custom filters +'LBL_SET_AS_PUBLIC'=>'设为公共 ', +'LBL_NEW'=>'新', +'LBL_EDIT'=>'修改', +'LBL_STATUS_PUBLIC_APPROVE'=>'批准', +'LBL_STATUS_PUBLIC_DENY'=>'拒绝' +); +?> diff --git a/oss/vtiger/trunk/modules/CustomerPortal/AdvancedSettings.php b/oss/vtiger/trunk/modules/CustomerPortal/AdvancedSettings.php new file mode 100644 index 00000000..7a1419e7 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/AdvancedSettings.php @@ -0,0 +1,57 @@ +id.'.php'); + +if(!$is_admin) { + echo "
"; + echo "
+ + + + + + + + + +
+ $app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} + +$mode = $_REQUEST['mode']; +if($mode !='' && $mode == 'save') { + cp_saveAdvancedSettings($_REQUEST); +} +$category = getParentTab(); +$smarty = new vtigerCRM_Smarty(); +$smarty->assign("THEME", $theme); +$smarty->assign('MOD', $mod_strings); +$smarty->assign('APP', $app_strings); +$smarty->assign('MODULE', $currentModule); +$smarty->assign('CATEGORY', $category); +$smarty->assign('BUTTONS', $list_buttons); +$smarty->assign('CHECK', $tool_buttons); +$smarty->assign('IMAGE_PATH', "themes/$theme/images/"); +$smarty->assign('MODULE_VIEWALL',cp_getContactsViewInfo()); + +$smarty->assign('USERS', cp_getUsers()); +$smarty->assign('USERID',cp_getCurrentUser()); +$smarty->display(vtlib_getModuleTemplate($currentModule,'AdvancedSettings.tpl')); +?> diff --git a/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortal.js b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortal.js new file mode 100644 index 00000000..3b178630 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortal.js @@ -0,0 +1,40 @@ +/********************************************************************************* + ** 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. + * + ********************************************************************************/ + +function move_module(tabid,move){ + + //$('vtbusy_info').style.display = "block"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=CustomerPortal&action=CustomerPortalAjax&file=ListView&sub_mode=movemodules&parenttab=Settings&tabid='+tabid+'&move='+move+'&ajax=true', + onComplete: function(response) { + $("portallist").innerHTML=response.responseText; + //$('vtbusy_info').style.display = "none"; + } + } + ); +} + +function toggleModule(tabid, action) { +var data = 'module=CustomerPortal&action=CustomerPortalAjax&file=ListView&tabid='+tabid+'&sub_mode=enable_disable&status='+action; +new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: data, + onComplete: function(response) { + // Reload the page to apply the effect of module setting + window.location.href = "index.php?module=CustomerPortal&action=index&parenttab=Settings"; + } + } + ); +} diff --git a/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortal.php b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortal.php new file mode 100644 index 00000000..c7ce6254 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortal.php @@ -0,0 +1,66 @@ +query("INSERT INTO vtiger_customerportal_tabs (tabid,visible,sequence) VALUES ($tabid,1,$i)"); + } + for($j = 0; $j< count($portalmodules); $j++) { + $tabid = getTabid($portalmodules[$j]); + $adb->query("INSERT INTO vtiger_customerportal_prefs(tabid,prefkey,prefvalue) VALUES ($tabid,'showrelatedinfo',1)"); + } + + $adb->query("INSERT INTO vtiger_customerportal_prefs(tabid,prefkey,prefvalue) VALUES (0,'userid',1)"); + + // Mark the module as Standard module + $adb->pquery('UPDATE vtiger_tab SET customized=0 WHERE name=?', array($moduleName)); + + $fieldid = $adb->getUniqueID('vtiger_settings_field'); + $blockid = getSettingsBlockId('LBL_OTHER_SETTINGS'); + $seq_res = $adb->pquery("SELECT max(sequence) AS max_seq FROM vtiger_settings_field WHERE blockid = ?", array($blockid)); + if ($adb->num_rows($seq_res) > 0) { + $cur_seq = $adb->query_result($seq_res, 0, 'max_seq'); + if ($cur_seq != null) $seq = $cur_seq + 1; + } + + $adb->pquery('INSERT INTO vtiger_settings_field(fieldid, blockid, name, iconpath, description, linkto, sequence) + VALUES (?,?,?,?,?,?,?)', array($fieldid, $blockid, 'LBL_CUSTOMER_PORTAL', 'portal_icon.png', 'PORTAL_EXTENSION_DESCRIPTION', 'index.php?module=CustomerPortal&action=index&parenttab=Settings', $seq)); + + + } else if($eventType == 'module.disabled') { + // TODO Handle actions when this module is disabled. + } else if($eventType == 'module.enabled') { + // TODO Handle actions when this module is enabled. + } else if($eventType == 'module.preuninstall') { + // TODO Handle actions when this module is about to be deleted. + } else if($eventType == 'module.preupdate') { + // TODO Handle actions before this module is updated. + } else if($eventType == 'module.postupdate') { + // TODO Handle actions after this module is updated. + } + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortalAjax.php b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortalAjax.php new file mode 100644 index 00000000..4529abde --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortalAjax.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortalHandler.php b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortalHandler.php new file mode 100644 index 00000000..729d97fa --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/CustomerPortalHandler.php @@ -0,0 +1,17 @@ + diff --git a/oss/vtiger/trunk/modules/CustomerPortal/ListView.php b/oss/vtiger/trunk/modules/CustomerPortal/ListView.php new file mode 100644 index 00000000..eb2c13d7 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/ListView.php @@ -0,0 +1,76 @@ +id.'.php'); + +if(!$is_admin) { + echo "
"; + echo "
+ + + + + + + + + +
+ $app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} + +if($_REQUEST['sub_mode'] != '' && isset($_REQUEST['sub_mode'])){ + $sub_mode =$_REQUEST['sub_mode']; +} +if($sub_mode == 'movemodules'){ + $tabid = $_REQUEST['tabid']; + $move = $_REQUEST['move']; + if($tabid != ''){ + cp_changeTabOrder($tabid,$move); + } +}elseif($sub_mode == 'enable_disable') { + $tabid = $_REQUEST['tabid']; + $status =$_REQUEST['status']; + if($status != '' && $tabid != ''){ + cp_changeModuleVisibility($tabid,$status); + } +} +$category = getParentTab(); +$smarty = new vtigerCRM_Smarty(); +$portalmodules = cp_getPortalModuleinfo(); + +$smarty->assign('PORTALMODULES',$portalmodules); +$smarty->assign("THEME", $theme); +$smarty->assign('MOD', $mod_strings); +$smarty->assign('APP', $app_strings); +$smarty->assign('MODULE', $currentModule); +$smarty->assign('CATEGORY', $category); +$smarty->assign('BUTTONS', $list_buttons); +$smarty->assign('CHECK', $tool_buttons); +$smarty->assign('IMAGE_PATH', "themes/$theme/images/"); +$smarty->assign('MODE',$mode); +if($_REQUEST['ajax'] != true) { + $smarty->display(vtlib_getModuleTemplate($currentModule,'BasicSetttings.tpl')); +} +else { + $smarty->display(vtlib_getModuleTemplate($currentModule,'BasicSetttingsContents.tpl')); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomerPortal/PortalUtils.php b/oss/vtiger/trunk/modules/CustomerPortal/PortalUtils.php new file mode 100644 index 00000000..99008664 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/PortalUtils.php @@ -0,0 +1,136 @@ +query("SELECT vtiger_customerportal_tabs.*,vtiger_tab.name from vtiger_customerportal_tabs + INNER JOIN vtiger_tab ON vtiger_customerportal_tabs.tabid = vtiger_tab.tabid and vtiger_tab.presence = 0 + ORDER BY vtiger_customerportal_tabs.sequence"); + $rows = $adb->num_rows($query); + for($i = 0;$i < $rows; $i++){ + $portalmodules[$i]['tabid'] = $adb->query_result($query,$i,'tabid'); + $portalmodules[$i]['visible'] = $adb->query_result($query,$i,'visible'); + $portalmodules[$i]['sequence'] = $adb->query_result($query,$i,'sequence'); + $portalmodules[$i]['name'] = $adb->query_result($query,$i,'name'); + } + return $portalmodules; +} + +/* Function is used to change the order of modules in Customer portal + * + */ +function cp_changeTabOrder($tabid,$move) { + global $adb,$log; + $log->fatal("$tabid,$move"); + if($move == 'Down'){ + $sequence = $adb->pquery("SELECT sequence FROM vtiger_customerportal_tabs WHERE tabid = ?", array($tabid)); + $oldsequence = $adb->query_result($sequence,0,'sequence'); + + $nexttab = $adb->pquery("SELECT sequence,tabid FROM vtiger_customerportal_tabs WHERE sequence > ? ORDER BY SEQUENCE LIMIT 0,1", array($oldsequence)); + $newsequence = $adb->query_result($nexttab,0,'sequence'); + $righttabid = $adb->query_result($nexttab,0,'tabid'); + + $adb->pquery("UPDATE vtiger_customerportal_tabs set sequence=? WHERE tabid = ?", array($newsequence, $tabid)); + $adb->pquery("UPDATE vtiger_customerportal_tabs set sequence=? WHERE tabid = ?", array($oldsequence, $righttabid)); + }elseif ($move == 'Up') { + $sequence = $adb->pquery("SELECT sequence FROM vtiger_customerportal_tabs WHERE tabid = ?", array($tabid)); + $oldsequence = $adb->query_result($sequence,0,'sequence'); + + $nexttab = $adb->pquery("SELECT sequence,tabid FROM vtiger_customerportal_tabs WHERE sequence < ? ORDER BY SEQUENCE DESC LIMIT 0,1", array($oldsequence)); + $newsequence = $adb->query_result($nexttab,0,'sequence'); + $lefttabid = $adb->query_result($nexttab,0,'tabid'); + + $adb->pquery("UPDATE vtiger_customerportal_tabs SET sequence=? WHERE tabid = ?", array($newsequence, $tabid)); + $adb->pquery("UPDATE vtiger_customerportal_tabs SET sequence=? WHERE tabid = ?", array($oldsequence, $lefttabid)); + + } + +} + +/* Function to obtain related info for Customer Portal(contacts can see other contacts info ar not) + */ + +function cp_getContactsViewInfo() { + global $adb; + $relatedinfo = $adb->query("SELECT vtiger_customerportal_prefs.*,vtiger_tab.name FROM vtiger_customerportal_prefs + INNER JOIN vtiger_tab ON vtiger_tab.tabid = vtiger_customerportal_prefs.tabid + WHERE prefkey = 'showrelatedinfo' AND vtiger_tab.presence = 0"); + $norows = $adb->num_rows($relatedinfo); + for($i = 0;$i < $norows;$i++) { + $module_viewall[$i]['module'] = $adb->query_result($relatedinfo,$i,'name'); + $module_viewall[$i]['value'] = $adb->query_result($relatedinfo,$i,'prefvalue'); + } + return $module_viewall; +} + +/* Function to show/hide the tabs(modules) in Customer Portal + */ +function cp_changeModuleVisibility($tabid,$status) { + global $adb,$log; + if($status == 'module_disable'){ + $updatevisibility = $adb->pquery("UPDATE vtiger_customerportal_tabs SET visible = 0 WHERE tabid = ?", array($tabid)); + }else { + $updatevisibility = $adb->pquery("UPDATE vtiger_customerportal_tabs SET visible = 1 WHERE tabid = ?", array($tabid)); + } +} + +/* Function to save Advanced info fro Customer Portal + */ +function cp_saveAdvancedSettings($input) { + global $adb; + + $portalmodules = array("Accounts","Contacts","HelpDesk","Invoice","Quotes","Documents","Faq","Services","Products"); + foreach($portalmodules as $modules) { + $view = $input['view_'.$modules]; + $tabid = getTabid($modules); + if($view == 'showall'){ + $adb->pquery("UPDATE vtiger_customerportal_prefs SET prefvalue = 1 WHERE prefkey = 'showrelatedinfo' and tabid = ?", array($tabid)); + }else { + $adb->pquery("UPDATE vtiger_customerportal_prefs SET prefvalue = 0 WHERE prefkey = 'showrelatedinfo' and tabid = ?", array($tabid)); + } + } + + //user update + $userid = $input['userid']; + $adb->pquery("UPDATE vtiger_customerportal_prefs SET prefvalue = ? WHERE prefkey = 'userid' and tabid = 0", array($userid)); + +} + +/* It gives you a list of users + * + */ +function cp_getUsers(){ + global $adb; + $res = $adb->query("SELECT id,user_name from vtiger_users"); + $norows = $adb->num_rows($res); + for($i = 0;$i < $norows;$i++) { + $users[$i]['id'] = $adb->query_result($res,$i,'id'); + $users[$i]['name'] = $adb->query_result($res,$i,'user_name'); + } + return $users; +} + +/* Function to get the customer portal user id + */ +function cp_getCurrentUser() { + global $adb; + $res = $adb->query("SELECT prefvalue FROM vtiger_customerportal_prefs WHERE prefkey = 'userid' AND tabid = 0"); + $userid = $adb->query_result($res,0,'prefvalue'); + if($userid != '') { + return $userid; + } + return false; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/CustomerPortal/index.php b/oss/vtiger/trunk/modules/CustomerPortal/index.php new file mode 100644 index 00000000..93f50e26 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/index.php @@ -0,0 +1,36 @@ +id.'.php'); + +if(!$is_admin) { + echo "
"; + echo "
+ + + + + + + + + +
+ $app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} +include_once("modules/$currentModule/ListView.php"); + +?> diff --git a/oss/vtiger/trunk/modules/CustomerPortal/language/en_us.lang.php b/oss/vtiger/trunk/modules/CustomerPortal/language/en_us.lang.php new file mode 100644 index 00000000..6fdc959f --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/language/en_us.lang.php @@ -0,0 +1,22 @@ + 'CustomerPortal', +'LBL_BASIC_SETTINGS'=>'Basic Settings', +'LBL_ADVANCED_SETTINGS'=>'Advanced Settings', +'LBL_MODULE'=>'Module', +'LBL_VIEW_ALL_RECORD'=>'View All Related Records ?', +'YES'=>'Yes', +'NO'=>'No', +'LBL_USER_DESCRIPTION'=>'The above selected User\'s profile will be selected to control the fields that appear in the Customer Portal + You can enable/disable the fields that show in the customer Portal.', +'SELECT_USERS'=>'Select the Users', +'LBL_DISABLE'=>'Disable', +'LBL_ENABLE' =>'Enable', +'Module' => 'Module', +'Sequence' =>'Sequence', +'Visible'=>'Visible' + +); + +?> diff --git a/oss/vtiger/trunk/modules/CustomerPortal/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/CustomerPortal/language/zh_cn.lang.php new file mode 100644 index 00000000..d8d8a084 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/language/zh_cn.lang.php @@ -0,0 +1,21 @@ + '客户门户 ', +'LBL_BASIC_SETTINGS'=>'基本设置', +'LBL_ADVANCED_SETTINGS'=>'高级设置', +'LBL_MODULE'=>'模块', +'LBL_VIEW_ALL_RECORD'=>'查看所有相关记录 ?', +'YES'=>'是', +'NO'=>'否', +'LBL_USER_DESCRIPTION'=>'您可以通过设置来决定上述选定的用户的相关权限,比如字段是否可见,模块是否可用等.', +'SELECT_USERS'=>'选择用户', +'LBL_DISABLE'=>'禁用', +'LBL_ENABLE' =>'启用', +'Module' => '模块', +'Sequence' =>'次序', +'Visible'=>'可见' + +); + +?> diff --git a/oss/vtiger/trunk/modules/CustomerPortal/schema.xml b/oss/vtiger/trunk/modules/CustomerPortal/schema.xml new file mode 100644 index 00000000..913b1a17 --- /dev/null +++ b/oss/vtiger/trunk/modules/CustomerPortal/schema.xml @@ -0,0 +1,34 @@ + + + + + vtiger_customerportal_tabs + +
+ + vtiger_customerportal_fields + +
+ + vtiger_customerportal_prefs + +
+ + vtiger_customerportal_prefs + +
+
+
diff --git a/oss/vtiger/trunk/modules/Dashboard/Chart_lead_source_by_outcome.php b/oss/vtiger/trunk/modules/Dashboard/Chart_lead_source_by_outcome.php new file mode 100644 index 00000000..12ffec0f --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Chart_lead_source_by_outcome.php @@ -0,0 +1,160 @@ +id.'.php'); +require('user_privileges/user_privileges_'.$current_user->id.'.php'); + +// Get _dom arrays from Database +$comboFieldNames = Array('leadsource'=>'lead_source_dom'); +$comboFieldArray = getComboArray($comboFieldNames); + +$log = LoggerManager::getLogger('lead_source_by_outcome'); + +if (isset($_REQUEST['lsbo_refresh'])) { $refresh = $_REQUEST['lsbo_refresh']; } +else { $refresh = false; } + +// added for auto refresh +$refresh = true; +// + +$tempx = array(); +$datax = array(); +//get list of sales stage keys to display +if (isset($_SESSION['lsbo_lead_sources']) && count($_SESSION['lsbo_lead_sources']) > 0 && !isset($_REQUEST['lsbo_lead_sources'])) { + $tempx = $_SESSION['lsbo_lead_sources']; + $log->debug("_SESSION['lsbo_lead_sources'] is:"); + $log->debug($_SESSION['lsbo_lead_sources']); +} +elseif (isset($_REQUEST['lsbo_lead_sources']) && count($_REQUEST['lsbo_lead_sources']) > 0) { + $tempx = $_REQUEST['lsbo_lead_sources']; + $current_user->setPreference('lsbo_lead_sources', $_REQUEST['lsbo_lead_sources']); + $log->debug("_REQUEST['lsbo_lead_sources'] is:"); + $log->debug($_REQUEST['lsbo_lead_sources']); + $log->debug("_SESSION['lsbo_lead_sources'] is:"); + $log->debug($_SESSION['lsbo_lead_sources']); +} + +//set $datax using selected sales stage keys +if (count($tempx) > 0) { + foreach ($tempx as $key) { + $datax[$key] = $comboFieldArray['lead_source_dom'][$key]; + } +} +else { + $datax = $comboFieldArray['lead_source_dom']; +} +$log->debug("datax is:"); +$log->debug($datax); + +$ids = array(); +//get list of user ids for which to display data +if (isset($_SESSION['lsbo_ids']) && count($_SESSION['lsbo_ids']) != 0 && !isset($_REQUEST['lsbo_ids'])) { + $ids = $_SESSION['lsbo_ids']; + $log->debug("_SESSION['lsbo_ids'] is:"); + $log->debug($_SESSION['lsbo_ids']); +} +elseif (isset($_REQUEST['lsbo_ids']) && count($_REQUEST['lsbo_ids']) > 0) { + $ids = $_REQUEST['lsbo_ids']; + $current_user->setPreference('lsbo_ids', $_REQUEST['lsbo_ids']); + $log->debug("_REQUEST['lsbo_ids'] is:"); + $log->debug($_REQUEST['lsbo_ids']); + $log->debug("_SESSION['lsbo_ids'] is:"); + $log->debug($_SESSION['lsbo_ids']); +} +else { + $ids = get_user_array(false); + $ids = array_keys($ids); +} + +//create unique prefix based on selected vtiger_users for image vtiger_files +$id_hash = ''; +if (isset($ids)) { + sort($ids); + $id_hash = crc32(implode('',$ids)); +} +$log->debug("ids is:"); +$log->debug($ids); + +$cache_file_name = $id_hash."_lead_source_by_outcome_".$current_language."_".crc32(implode('',$datax)).".png"; +$log->debug("cache file name is: $cache_file_name"); + +if(isPermitted('Potentials','index')=="yes") +{ +$draw_this = new jpgraph(); +$width = 850; +$height = 500; +if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') +{ + $width = 350; + $height = 250; +} + +echo $draw_this->lead_source_by_outcome($datax, $ids, $tmp_dir.$cache_file_name, $refresh,$width,$height); +echo "

".$current_module_strings['LBL_LEAD_SOURCE_BY_OUTCOME_DESC']."

"; +if (isset($_REQUEST['lsbo_edit']) && $_REQUEST['lsbo_edit'] == 'true') { +?> +
+ + + + + + + + + + + + + + + + + +

+
+ +
+ +[] +[] +
+ \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Dashboard/Chart_my_pipeline_by_sales_stage.php b/oss/vtiger/trunk/modules/Dashboard/Chart_my_pipeline_by_sales_stage.php new file mode 100644 index 00000000..a1fc62ed --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Chart_my_pipeline_by_sales_stage.php @@ -0,0 +1,184 @@ +'sales_stage_dom'); +$comboFieldArray = getComboArray($comboFieldNames); + +//get the dates to display +if (isset($_SESSION['mypbss_date_start']) && $_SESSION['mypbss_date_start'] != '' && !isset($_REQUEST['mypbss_date_start'])) { + $date_start = $_SESSION['mypbss_date_start']; + $log->debug("_SESSION['mypbss_date_start'] is:"); + $log->debug($_SESSION['mypbss_date_start']); +} +elseif (isset($_REQUEST['mypbss_date_start']) && $_REQUEST['mypbss_date_start'] != '') { + $date_start = $_REQUEST['mypbss_date_start']; + $current_user->setPreference('mypbss_date_start', $_REQUEST['mypbss_date_start']); + $log->debug("_REQUEST['mypbss_date_start'] is:"); + $log->debug($_REQUEST['mypbss_date_start']); + $log->debug("_SESSION['mypbss_date_start'] is:"); + $log->debug($_SESSION['mypbss_date_start']); +} +else { + $date_start = date("Y-m-d", time()); +} + +if (isset($_SESSION['mypbss_date_end']) && $_SESSION['mypbss_date_end'] != '' && !isset($_REQUEST['mypbss_date_end'])) { + $date_end = $_SESSION['mypbss_date_end']; + $log->debug("_SESSION['mypbss_date_end'] is:"); + $log->debug($_SESSION['mypbss_date_end']); +} +elseif (isset($_REQUEST['mypbss_date_end']) && $_REQUEST['mypbss_date_end'] != '') { + $date_end = $_REQUEST['mypbss_date_end']; + $current_user->setPreference('mypbss_date_end', $_REQUEST['mypbss_date_end']); + $log->debug("_REQUEST['mypbss_date_end'] is:"); + $log->debug($_REQUEST['mypbss_date_end']); + $log->debug("_SESSION['mypbss_date_end'] is:"); + $log->debug($_SESSION['mypbss_date_end']); +} +else { + $date_end = '2100-01-01'; +} + +$tempx = array(); +$datax = array(); +//get list of sales stage keys to display +if (isset($_SESSION['mypbss_sales_stages']) && count($_SESSION['mypbss_sales_stages']) > 0 && !isset($_REQUEST['mypbss_sales_stages'])) { + $tempx = $_SESSION['mypbss_sales_stages']; + $log->debug("_SESSION['mypbss_sales_stages'] is:"); + $log->debug($_SESSION['mypbss_sales_stages']); +} +elseif (isset($_REQUEST['mypbss_sales_stages']) && count($_REQUEST['mypbss_sales_stages']) > 0) { + $tempx = $_REQUEST['mypbss_sales_stages']; + $current_user->setPreference('mypbss_sales_stages', $_REQUEST['mypbss_sales_stages']); + $log->debug("_REQUEST['mypbss_sales_stages'] is:"); + $log->debug($_REQUEST['mypbss_sales_stages']); + $log->debug("_SESSION['mypbss_sales_stages'] is:"); + $log->debug($_SESSION['mypbss_sales_stages']); +} + +//set $datax using selected sales stage keys +if (count($tempx) > 0) { + foreach ($tempx as $key) { + $datax[$key] = $comboFieldArray['sales_stage_dom'][$key];//$app_list_strings['sales_stage_dom'][$key]; + } +} +else { + $datax = $comboFieldArray['sales_stage_dom'];//app_list_strings['sales_stage_dom']; +} +$log->debug("datax is:"); +$log->debug($datax); + +$ids = array($current_user->id); +//create unique prefix based on selected vtiger_users for image vtiger_files +$id_hash = ''; +if (isset($ids)) { + sort($ids); + $id_hash = crc32(implode('',$ids)); +} +$log->debug("ids is:"); +$log->debug($ids); + +$cache_file_name = $id_hash."_pipeline_".$current_language."_".crc32(implode('',$datax)).$date_start.$date_end.".png"; +$log->debug("cache file name is: $cache_file_name"); + +if (substr(phpversion(), 0, 1) == "5") { // php5 } + echo "Charts not supported in PHP 5."; +} +else { +$draw_this = new jpgraph(); +echo $draw_this->pipeline_by_sales_stage($datax, $date_start, $date_end, $ids, $tmp_dir.$cache_file_name, $refresh); +echo "

".$current_module_strings['LBL_PIPELINE_FORM_TITLE_DESC']."

"; +if (isset($_REQUEST['mypbss_edit']) && $_REQUEST['mypbss_edit'] == 'true') { + $cal_lang = "en"; + $cal_dateformat = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + $cal_dateformat = '%Y-%m-%d'; // fix providedd by Jlee for date bug in Dashboard + + +?> + + + + +
+ + + + + + + + + + + + + + + + + +

'>

'>

+
+ + + +
+ +[] +[] +
+ diff --git a/oss/vtiger/trunk/modules/Dashboard/Chart_outcome_by_month.php b/oss/vtiger/trunk/modules/Dashboard/Chart_outcome_by_month.php new file mode 100644 index 00000000..fc16aa6d --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Chart_outcome_by_month.php @@ -0,0 +1,197 @@ +id.'.php'); +require('user_privileges/user_privileges_'.$current_user->id.'.php'); + +$log = LoggerManager::getLogger('outcome_by_month'); + +if (isset($_REQUEST['obm_refresh'])) { $refresh = $_REQUEST['obm_refresh']; } +else { $refresh = false; } + +// added for auto refresh +$refresh = true; +// + +$date_start = array(); +$datax = array(); +//get the dates to display +//added to fix the issue4307 +if(isset($_REQUEST['obm_date_start']) && $_REQUEST['obm_date_start'] == '') +{ + $_SESSION['obm_date_start'] = ""; +} +elseif(isset($_REQUEST['obm_date_start']) && $_REQUEST['obm_date_start'] != '') + $_SESSION['obm_date_start'] = $_REQUEST['obm_date_start']; +if(isset($_REQUEST['obm_date_end']) && $_REQUEST['obm_date_end'] == '') +{ + $_SESSION['obm_date_end'] = ""; +} +elseif(isset($_REQUEST['obm_date_end']) && $_REQUEST['obm_date_end'] != '') + $_SESSION['obm_date_end'] = $_REQUEST['obm_date_end']; +if (isset($_SESSION['obm_date_start']) && $_SESSION['obm_date_start'] != '' && !isset($_REQUEST['obm_date_start'])) { + $date_start = $_SESSION['obm_date_start']; + $log->debug("_SESSION['obm_date_start'] is:"); + $log->debug($_SESSION['obm_date_start']); +} +elseif (isset($_REQUEST['obm_date_start']) && $_REQUEST['obm_date_start'] != '') { + $date_start = $_REQUEST['obm_date_start']; + $current_user->setPreference('obm_date_start', $_REQUEST['obm_date_start']); + $log->debug("_REQUEST['obm_date_start'] is:"); + $log->debug($_REQUEST['obm_date_start']); + $log->debug("_SESSION['obm_date_start'] is:"); + $log->debug($_SESSION['obm_date_start']); +} +else { + $date_start = '2000-01-01'; +} + +if (isset($_SESSION['obm_date_end']) && $_SESSION['obm_date_end'] != '' && !isset($_REQUEST['obm_date_end'])) { + $date_end = $_SESSION['obm_date_end']; + $log->debug("_SESSION['obm_date_end'] is:"); + $log->debug($_SESSION['obm_date_end']); +} +elseif (isset($_REQUEST['obm_date_end']) && $_REQUEST['obm_date_end'] != '') { + $date_end = $_REQUEST['obm_date_end']; + $current_user->setPreference('obm_date_end', $_REQUEST['obm_date_end']); + $log->debug("_REQUEST['obm_date_end'] is:"); + $log->debug($_REQUEST['obm_date_end']); + $log->debug("_SESSION['obm_date_end'] is:"); + $log->debug($_SESSION['obm_date_end']); +} +else { + $date_end = '2100-01-01'; +} + +$ids = array(); +//get list of user ids for which to display data +if (isset($_SESSION['obm_ids']) && count($_SESSION['obm_ids']) != 0 && !isset($_REQUEST['obm_ids'])) { + $ids = $_SESSION['obm_ids']; + $log->debug("_SESSION['obm_ids'] is:"); + $log->debug($_SESSION['obm_ids']); +} +elseif (isset($_REQUEST['obm_ids']) && count($_REQUEST['obm_ids']) > 0) { + $ids = $_REQUEST['obm_ids']; + $current_user->setPreference('obm_ids', $_REQUEST['obm_ids']); + $log->debug("_REQUEST['obm_ids'] is:"); + $log->debug($_REQUEST['obm_ids']); + $log->debug("_SESSION['obm_ids'] is:"); + $log->debug($_SESSION['obm_ids']); +} +else { + $ids = get_user_array(false); + $ids = array_keys($ids); +} + +//create unique prefix based on selected vtiger_users for image vtiger_files +$id_hash = ''; +if (isset($ids)) { + sort($ids); + $id_hash = crc32(implode('',$ids)); +} +$log->debug("ids is:"); +$log->debug($ids); + +$cache_file_name = $id_hash."_outcome_by_month_".$current_language."_".crc32($date_start.$date_end).".png"; +$log->debug("cache file name is: $cache_file_name"); + +if(isPermitted('Potentials','index')=="yes") +{ +$draw_this = new jpgraph(); +$width = 850; +$height = 500; +if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') +{ + $width = 350; + $height = 250; +} + +echo $draw_this->outcome_by_month($date_start, $date_end, $ids, $tmp_dir.$cache_file_name, $refresh,$width,$height); +echo "

".$current_module_strings['LBL_MONTH_BY_OUTCOME_DESC']."

"; +if (isset($_REQUEST['obm_edit']) && $_REQUEST['obm_edit'] == 'true') { + $cal_lang = "en"; + $cal_dateformat = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + $cal_dateformat = '%Y-%m-%d'; // fix providedd by Jlee for date bug in Dashboard + +?> + + + + +
+ + + + + + + + + + + + + + + + + + + + + +

'>

'>

+
+ + + +
+ +[] +[] +
+ \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Dashboard/Chart_pipeline_by_lead_source.php b/oss/vtiger/trunk/modules/Dashboard/Chart_pipeline_by_lead_source.php new file mode 100644 index 00000000..eb38df6b --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Chart_pipeline_by_lead_source.php @@ -0,0 +1,161 @@ +id.'.php'); +require('user_privileges/user_privileges_'.$current_user->id.'.php'); + +// Get _dom arrays from Database +$comboFieldNames = Array('leadsource'=>'lead_source_dom'); +$comboFieldArray = getComboArray($comboFieldNames); + +$log = LoggerManager::getLogger('CSIM_pipeline_by_lead_source'); + +if (isset($_REQUEST['pbls_refresh'])) { $refresh = $_REQUEST['pbls_refresh']; } +else { $refresh = false; } + +// added for auto refresh +$refresh = true; +// + +$tempx = array(); +$datax = array(); +//get list of sales stage keys to display +if (isset($_SESSION['pbls_lead_sources']) && count($_SESSION['pbls_lead_sources']) > 0 && !isset($_REQUEST['pbls_lead_sources'])) { + $tempx = $_SESSION['pbls_lead_sources']; + $log->debug("_SESSION['pbls_lead_sources'] is:"); + $log->debug($_SESSION['pbls_lead_sources']); +} +elseif (isset($_REQUEST['pbls_lead_sources']) && count($_REQUEST['pbls_lead_sources']) > 0) { + $tempx = $_REQUEST['pbls_lead_sources']; + $current_user->setPreference('pbls_lead_sources', $_REQUEST['pbls_lead_sources']); + $log->debug("_REQUEST['pbls_lead_sources'] is:"); + $log->debug($_REQUEST['pbls_lead_sources']); + $log->debug("_SESSION['pbls_lead_sources'] is:"); + $log->debug($_SESSION['pbls_lead_sources']); +} + +//set $datax using selected sales stage keys +if (count($tempx) > 0) { + foreach ($tempx as $key) { + $datax[$key] = $comboFieldArray['lead_source_dom'][$key]; + } +} +else { + $datax = $comboFieldArray['lead_source_dom']; +} +$log->debug("datax is:"); +$log->debug($datax); + +$ids = array(); +//get list of user ids for which to display data +if (isset($_SESSION['pbls_ids']) && count($_SESSION['pbls_ids']) != 0 && !isset($_REQUEST['pbls_ids'])) { + $ids = $_SESSION['pbls_ids']; + $log->debug("_SESSION['pbls_ids'] is:"); + $log->debug($_SESSION['pbls_ids']); +} +elseif (isset($_REQUEST['pbls_ids']) && count($_REQUEST['pbls_ids']) > 0) { + $ids = $_REQUEST['pbls_ids']; + $current_user->setPreference('pbls_ids', $ids); + $log->debug("_REQUEST['pbls_ids'] is:"); + $log->debug($_REQUEST['pbls_ids']); + $log->debug("_SESSION['pbls_ids'] is:"); + $log->debug($_SESSION['pbls_ids']); +} +else { + $ids = get_user_array(false); + $ids = array_keys($ids); +} + +//create unique prefix based on selected vtiger_users for image vtiger_files +$id_hash = ''; +if (isset($ids)) { + sort($ids); + $id_hash = crc32(implode('',$ids)); +} +$log->debug("ids is:"); +$log->debug($ids); + +$cache_file_name = $id_hash."_pipeline_by_lead_source_".$current_language."_".crc32(implode('',$datax)).".png"; +$log->debug("cache file name is: $cache_file_name"); + +if(isPermitted('Potentials','index')=="yes") +{ +$draw_this = new jpgraph(); +$width = 850; +$height = 500; +if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') +{ + $width = 350; + $height = 250; +} + + +echo $draw_this->pipeline_by_lead_source($datax, $ids, $tmp_dir.$cache_file_name, $refresh,$width,$height); +echo "

".$current_module_strings['LBL_LEAD_SOURCE_FORM_DESC']."

"; +if (isset($_REQUEST['pbls_edit']) && $_REQUEST['pbls_edit'] == 'true') { +?> +
+ + + + + + + + + + + + + + + + + +

+
+ +
+ +[] +[] +
+ \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Dashboard/Chart_pipeline_by_sales_stage.php b/oss/vtiger/trunk/modules/Dashboard/Chart_pipeline_by_sales_stage.php new file mode 100644 index 00000000..6ddb86b7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Chart_pipeline_by_sales_stage.php @@ -0,0 +1,235 @@ +id.'.php'); +require('user_privileges/user_privileges_'.$current_user->id.'.php'); +$log = LoggerManager::getLogger('pipeline_by_sales_stage'); + +if (isset($_REQUEST['pbss_refresh'])) { $refresh = $_REQUEST['pbss_refresh']; } +else { $refresh = false; } + +// added for auto refresh +$refresh = true; +// + +// Get _dom Arrays from Database +$comboFieldNames = Array('sales_stage'=>'sales_stage_dom'); +$comboFieldArray = getComboArray($comboFieldNames); +//added to fix the issue 4307 +if(isset($_REQUEST['pbss_date_start']) && $_REQUEST['pbss_date_start'] == '') +{ + $_SESSION['pbss_date_start'] = ""; +} +elseif(isset($_REQUEST['pbss_date_start']) && $_REQUEST['pbss_date_start'] != '') + $_SESSION['pbss_date_start']=$_REQUEST['pbss_date_start']; +if(isset($_REQUEST['pbss_date_end']) && $_REQUEST['pbss_date_end'] == '') +{ + $_SESSION['pbss_date_end'] = ""; +} +elseif(isset($_REQUEST['pbss_date_start']) && $_REQUEST['pbss_date_end'] != '') + $_SESSION['pbss_date_end'] = $_REQUEST['pbss_date_end']; +//get the dates to display +if (isset($_SESSION['pbss_date_start']) && $_SESSION['pbss_date_start'] != '' && !isset($_REQUEST['pbss_date_start'])) { + $date_start = $_SESSION['pbss_date_start']; + $log->debug("_SESSION['pbss_date_start'] is:"); + $log->debug($_SESSION['pbss_date_start']); +} +elseif (isset($_REQUEST['pbss_date_start']) && $_REQUEST['pbss_date_start'] != '') { + $date_start = $_REQUEST['pbss_date_start']; + $current_user->setPreference('pbss_date_start', $_REQUEST['pbss_date_start']); + $log->debug("_REQUEST['pbss_date_start'] is:"); + $log->debug($_REQUEST['pbss_date_start']); + $log->debug("_SESSION['pbss_date_start'] is:"); + $log->debug($_SESSION['pbss_date_start']); +} +else { + $date_start = "2001-01-01"; +} + +if (isset($_SESSION['pbss_date_end']) && $_SESSION['pbss_date_end'] != '' && !isset($_REQUEST['pbss_date_end'])) { + $date_end = $_SESSION['pbss_date_end']; + $log->debug("_SESSION['pbss_date_end'] is:"); + $log->debug($_SESSION['pbss_date_end']); +} +elseif (isset($_REQUEST['pbss_date_end']) && $_REQUEST['pbss_date_end'] != '') { + $date_end = $_REQUEST['pbss_date_end']; + $current_user->setPreference('pbss_date_end', $_REQUEST['pbss_date_end']); + $log->debug("_REQUEST['pbss_date_end'] is:"); + $log->debug($_REQUEST['pbss_date_end']); + $log->debug("_SESSION['pbss_date_end'] is:"); + $log->debug($_SESSION['pbss_date_end']); +} +else { + $date_end = '2100-01-01'; +} + +$tempx = array(); +$datax = array(); +//get list of sales stage keys to display +if (isset($_SESSION['pbss_sales_stages']) && count($_SESSION['pbss_sales_stages']) > 0 && !isset($_REQUEST['pbss_sales_stages'])) { + $tempx = $_SESSION['pbss_sales_stages']; + $log->debug("_SESSION['pbss_sales_stages'] is:"); + $log->debug($_SESSION['pbss_sales_stages']); +} +elseif (isset($_REQUEST['pbss_sales_stages']) && count($_REQUEST['pbss_sales_stages']) > 0) { + $tempx = $_REQUEST['pbss_sales_stages']; + $current_user->setPreference('pbss_sales_stages', $_REQUEST['pbss_sales_stages']); + $log->debug("_REQUEST['pbss_sales_stages'] is:"); + $log->debug($_REQUEST['pbss_sales_stages']); + $log->debug("_SESSION['pbss_sales_stages'] is:"); + $log->debug($_SESSION['pbss_sales_stages']); +} + +//set $datax using selected sales stage keys +if (count($tempx) > 0) { + foreach ($tempx as $key) { + $datax[$key] = $comboFieldArray['sales_stage_dom'][$key]; + } +} +else { + $datax = $comboFieldArray['sales_stage_dom']; +} +$log->debug("datax is:"); +$log->debug($datax); + +$ids = array(); +//get list of user ids for which to display data +if (isset($_SESSION['pbss_ids']) && count($_SESSION['pbss_ids']) != 0 && !isset($_REQUEST['pbss_ids'])) { + $ids = $_SESSION['pbss_ids']; + $log->debug("_SESSION['pbss_ids'] is:"); + $log->debug($_SESSION['pbss_ids']); +} +elseif (isset($_REQUEST['pbss_ids']) && count($_REQUEST['pbss_ids']) > 0) { + $ids = $_REQUEST['pbss_ids']; + $current_user->setPreference('pbss_ids', $_REQUEST['pbss_ids']); + $log->debug("_REQUEST['pbss_ids'] is:"); + $log->debug($_REQUEST['pbss_ids']); + $log->debug("_SESSION['pbss_ids'] is:"); + $log->debug($_SESSION['pbss_ids']); +} +else { + $ids = get_user_array(false); + $ids = array_keys($ids); +} + +//create unique prefix based on selected users for image files +$id_hash = ''; +if (isset($ids)) { + sort($ids); + $id_hash = crc32(implode('',$ids)); +} +$log->debug("ids is:"); +$log->debug($ids); + +$cache_file_name = $id_hash."_pipeline_".$current_language."_".crc32(implode('',$datax)).$date_start.$date_end.".png"; +$log->debug("cache file name is: $cache_file_name"); + +if(isPermitted('Potentials','index')=="yes") +{ +$draw_this = new jpgraph(); +$width = 850; +$height = 500; +if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') +{ + $width = 350; + $height = 250; +} + + +echo $draw_this->pipeline_by_sales_stage($datax, $date_start, $date_end, $ids, $tmp_dir.$cache_file_name, $refresh,$width,$height); +echo "

".$current_module_strings['LBL_SALES_STAGE_FORM_DESC']."

"; +if (isset($_REQUEST['pbss_edit']) && $_REQUEST['pbss_edit'] == 'true') { + $cal_lang = "en"; + $cal_dateformat = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + $cal_dateformat = '%Y-%m-%d'; // fix providedd by Jlee for date bug in Dashboard + +?> + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +

'>

'>

+
+ + + +
+ +[] +[] +
+ diff --git a/oss/vtiger/trunk/modules/Dashboard/DashboardAjax.php b/oss/vtiger/trunk/modules/Dashboard/DashboardAjax.php new file mode 100644 index 00000000..3dfc7b7a --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/DashboardAjax.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Dashboard/DashboardHome.php b/oss/vtiger/trunk/modules/Dashboard/DashboardHome.php new file mode 100644 index 00000000..ca8984e9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/DashboardHome.php @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + +
1  
+ +
+ + + + + + + + + +
1234
+
 
+ + + + + + + + +
2  
+
+ + + + + + + + + +
1234
+
 
+ + + + + + + + +
3  
+
+ + + + + + + + + +
1234
+
 
+ + + + + + + + +
4  
+
+ + + + + + + + + +
1234
+
 
+ diff --git a/oss/vtiger/trunk/modules/Dashboard/DashboardHome_matrix.php b/oss/vtiger/trunk/modules/Dashboard/DashboardHome_matrix.php new file mode 100644 index 00000000..c1786a8e --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/DashboardHome_matrix.php @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
+ + + + + + + + +
1  
+
+
+ + + + + + + +
+ + + + + + + + +
2  
+
+

+ + + + + + + + +
+ + + + + + + + +
3  
+
+
+ + + + + + + +
+ + + + + + + + +
4  
+
+

+ diff --git a/oss/vtiger/trunk/modules/Dashboard/Entity_charts.php b/oss/vtiger/trunk/modules/Dashboard/Entity_charts.php new file mode 100644 index 00000000..b8f47c51 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/Entity_charts.php @@ -0,0 +1,837 @@ +pquery($acc_qry, array($acc_id)); + $no_acc_rows=$adb->num_rows($acc_result); + + if($no_acc_rows!=0) + { + while($acc_row = $adb->fetch_array($acc_result)) + { + $name_val=$acc_row['accountname']; + } + $name=$name_val; + } + else + $name=""; + return $name; +} + + +/** + * Performance Optimization: Module Chart for Home Page Dashboard + */ +function module_Chart_HomePageDashboard($userinfo) { + + global $adb, $app_strings; + + $user_id = $userinfo->id; + + $graph_details = Array(); + $modrecords = Array(); + + // List of modules which needs to be considered for chart + $module_list = Array('Accounts','Potentials','Contacts','Leads','Quotes','SalesOrder','PurchaseOrder','Invoice','HelpDesk','Calendar','Campaigns'); + // List of special module to handle + $spl_modules = Array('Leads', 'HelpDesk', 'Potentials', 'Calendar'); + + // Leads module + $leadcountres = $adb->query("SELECT count(*) as count FROM vtiger_crmentity se INNER JOIN vtiger_leaddetails le on le.leadid = se.crmid + WHERE se.deleted = 0 AND se.smownerid = $user_id AND (le.converted = 0 OR le.converted IS NULL)"); + $modrecords['Leads'] = $adb->query_result($leadcountres, 0, 'count'); + + // HelpDesk module + $helpdeskcountres = $adb->query("SELECT count(*) as count FROM vtiger_crmentity se INNER JOIN vtiger_troubletickets tt ON tt.ticketid = se.crmid + WHERE se.deleted = 0 AND se.smownerid = $user_id AND (tt.status != 'Closed' OR tt.status IS NULL)"); + $modrecords['HelpDesk']=$adb->query_result($helpdeskcountres,0,'count'); + + // Potentials module + $potcountres = $adb->query("SELECT count(*) as count FROM vtiger_crmentity se INNER JOIN vtiger_potential pot ON pot.potentialid = se.crmid + WHERE se.deleted = 0 AND se.smownerid = $user_id AND (pot.sales_stage NOT IN ('".$app_strings['LBL_CLOSE_WON']."','". + $app_strings['LBL_CLOSE_LOST']."') OR pot.sales_stage IS NULL)"); + $modrecords['Potentials']= $adb->query_result($potcountres,0,'count'); + + // Calendar moudule + $calcountres = $adb->query("SELECT count(*) as count FROM vtiger_crmentity se INNER JOIN vtiger_activity act ON act.activityid = se.crmid + WHERE se.deleted = 0 AND se.smownerid = $user_id AND ((act.status!='Completed' AND act.status!='Deferred') OR act.status IS NULL) + AND ((act.eventstatus!='Held' AND act.eventstatus!='Not Held') OR act.eventstatus IS NULL)"); + $modrecords['Calendar']= $adb->query_result($calcountres,0,'count'); + + // Ignore the special module + $nor_modules = array_diff($module_list, $spl_modules); + // Prepare module string to use in SQL (check permission) + $inmodulestr = ''; + foreach($nor_modules as $modulename) { + if(isPermitted("$modulename","index",'') == 'yes') { + if($inmodulestr != '') $inmodulestr .= ",'$modulename'"; + else $inmodulestr = "'$modulename'"; + } + } + + // Get count for module that needs special conditions + $query = "SELECT setype, count(setype) setype_count FROM vtiger_crmentity se WHERE + se.deleted = 0 AND se.smownerid=$user_id AND se.setype in ($inmodulestr) GROUP BY se.setype"; + $queryres = $adb->query($query); + while($resrow = $adb->fetch_array($queryres)) { + $modrecords[$resrow['setype']] = $resrow['setype_count']; + } + + // Get module custom filter info + $cvidres = $adb->query("SELECT cvid,entitytype FROM vtiger_customview WHERE viewname='All' AND entitytype in ('". + implode("','", array_keys($modrecords)). "')"); + + $cvidinfo = Array(); + while($cvidrow = $adb->fetch_array($cvidres)) { + $cvidinfo[$cvidrow['entitytype']] = $cvidrow['cvid']; + } + + $name_val = ''; + $cnt_val = ''; + $target_val = ''; + $urlstring = ''; + $cnt_table = ''; + $test_target_val=''; + + $total_records= 0; + foreach($module_list as $modulename) { + if(isset($modrecords[$modulename])) { + $modrec_count = $modrecords[$modulename]; + if($modrec_count > 0) { + if($name_val != '') $name_val .= '::'; + $name_val .= $modulename; + + if($cnt_val != '') $cnt_val .= '::'; + $cnt_val .= $modrec_count; + + $modviewid = $cvidinfo[$modulename]; + if($target_val!= '') $target_val.= '::'; + $target_val.= urlencode("index.php?module=$modulename&action=ListView&from_homepagedb=true&type=dbrd&query=true&owner=$userinfo->user_name&viewname=$modviewid"); + if($test_target_val!='') $test_target_val.= 'K'; + $test_target_val.=urlencode("index.php?module=$modulename&action=ListView&from_homepagedb=true&type=dbrd&query=true&owner=$userinfo->user_name&viewname=$modviewid"); + + $urlstring .= 'K'; + $cnt_table .= ""; + + $total_records += $modrec_count; + } + } + } + $cnt_table .= '
StatusTotal
$modulename$modrec_count
'; + + $graph_details[] = $name_val; + $graph_details[] = $cnt_val; + $graph_details[] = " $userinfo->user_name : $total_records "; + $graph_details[] = $target_val; + $graph_details[] = ''; + $graph_details[] = $urlstring; + $graph_details[] = $cnt_table; + $graph_details[] = $test_target_val; + + return $graph_details; +} +/** END **/ + +/* Function returns the values to render the graph for a particular type + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. +*/ + +// TO get the Values for a particular graph type +function module_Chart($user_id,$date_start="2000-01-01",$end_date="2017-01-01",$query,$graph_for,$title,$added_qry="",$module="",$graph_type) +{ + + global $adb,$current_user,$mod_strings, $default_charset; + global $days,$date_array,$period_type; + + if($added_qry!="") + $query.=$added_qry; + + $result=$adb->query($query); + + $no_of_rows=$adb->num_rows($result); + $mod_count_array=array(); + $search_str_array=array(); + $mod_name_array=array(); + $count_by_date[]=array(); + $mod_tot_cnt_array=array(); + + $mod_name_val=""; + $mod_cnt_crtd_date=""; + $target_val=""; + $bar_target_val=""; + $test_target_val=""; + + if($no_of_rows!=0) + { + while($row = $adb->fetch_array($result)) + { + if($graph_for == 'sostatus'||$graph_for == 'leadsource'||$graph_for == 'leadstatus'||$graph_for == 'industry'||$graph_for == 'productcategory'||$graph_for =='postatus'||$graph_for == 'invoicestatus'||$graph_for == 'ticketstatus'||$graph_for == 'priority'||$graph_for == 'category'||$graph_for == 'quotestage'||$graph_for == 'salesstage') + { + $mod_name= getTranslatedString($row[$graph_for]); + $search_str = $row[$graph_for]; + } + else + { + $mod_name= $row[$graph_for]; + $search_str = $row[$graph_for]; + } + if($mod_name=="") + { + $mod_name=$mod_strings["Un Assigned"]; + $search_str = " "; + } + $crtd_time=$row['createdtime']; + $crtd_time_array=explode(" ",$crtd_time); + $crtd_date=$crtd_time_array[0]; + if(!isset($mod_tot_cnt_array[$crtd_date])) + $mod_tot_cnt_array[$crtd_date]=0; + + $mod_tot_cnt_array[$crtd_date]+=1; + + if (in_array($mod_name,$mod_name_array) == false) + { $uniqueid[$mod_name]='0'; + array_push($mod_name_array,$mod_name); // getting all the unique Names into the array + if($graph_for == "productname") + { + if($row['qtyinstock'] =='') + $mod_count_array[$mod_name] = 1; + else + $mod_count_array[$mod_name]=$row['qtyinstock']; + } + } + else + { + if($graph_for == "productname") + { + $uniqueid[$mod_name]=$uniqueid[$mod_name]+1; $mod_name=$mod_name.'['.$uniqueid[$mod_name].']'; array_push($mod_name_array,$mod_name); // getting all the unique Names into the array + + if($row['qtyinstock'] =='') + $mod_count_array[$mod_name] = 1; + else + $mod_count_array[$mod_name]=$row['qtyinstock']; + } + } + if (in_array($search_str,$search_str_array) == false) + { + array_push($search_str_array,$search_str); + } + + //Counting the number of values for a type of graph + if($graph_for == "productname") + { + if($row['qtyinstock'] =='') + $mod_count_array[$mod_name] = 1; + else + $mod_count_array[$mod_name]=$row['qtyinstock']; + + } + else + { + if(!isset($mod_count_array[$mod_name])) + $mod_count_array[$mod_name]=0; + $mod_count_array[$mod_name]++; + } + + //Counting the number of values for a type of graph for a particular date + if(!isset($count_by_date[$mod_name][$crtd_date])) + $count_by_date[$mod_name][$crtd_date]=0; + + $count_by_date[$mod_name][$crtd_date]+=1; + } + $mod_by_mod_cnt=count($mod_name_array); + + if($mod_by_mod_cnt!=0) + { + $url_string=""; + + $mod_cnt_table=" + "; + + //Assigning the Header values to the vtiger_table and giving the dates as graphformat + for($i=0; $i<$days; $i++) + { + $tdate=$date_array[$i]; + $values=Graph_n_table_format($period_type,$tdate); + $graph_format=$values[0]; + $table_format=$values[1]; + $mod_cnt_table.= ""; + } + $mod_cnt_table .= "" ; + + //For all type of the array + for ($i=0;$ipquery($query, array($mod_name)); + $name_val = $adb->query_result($result,0,"productname"); + if($name_val!="") + { + $mod_name=$name_val; + $search_str=$name_val; + } + } + if($graph_for =="purchaseorderid") + { + $query = "SELECT subject FROM vtiger_purchaseorder WHERE purchaseorderid=?"; + $result = $adb->pquery($query, array($mod_name)); + $name_val = $adb->query_result($result,0,"subject"); + $id_name = $mod_name; + if($name_val!="") + { + $mod_name=$name_val; + $search_str=$name_val; + } + } + if($graph_for =="quoteid") + { + $query = "SELECT subject FROM vtiger_quotes WHERE quoteid=?"; + $result = $adb->pquery($query, array($mod_name)); + $name_val = $adb->query_result($result,0,"subject"); + $id_name = $mod_name; + if($name_val!="") + { + $mod_name=$name_val; + $search_str=$name_val; + } + } + if($graph_for =="invoiceid") + { + $query = "SELECT subject FROM vtiger_invoice WHERE invoiceid=?"; + $result = $adb->pquery($query, array($mod_name)); + $name_val = $adb->query_result($result,0,"subject"); + $id_name = $mod_name; + if($name_val!="") + { + $mod_name=$name_val; + $search_str=$name_val; + } + } + if($graph_for =="campaignid") + { + //this will return the list of the names of the campaign``:w for the y-axis + $query = "SELECT campaignname FROM vtiger_campaign WHERE campaignid=?"; + $result = $adb->pquery($query, array($mod_name)); + $name_val = $adb->query_result($result,0,"campaignname"); + $id_name = $mod_name; + if($name_val!="") + { + $mod_name=$name_val; + $search_str=$name_val; + } + } + if($graph_for =="contactid") + { + $query = "SELECT contact_no, lastname, firstname FROM vtiger_contactdetails WHERE contactid=?"; + $result = $adb->pquery($query, array($mod_name)); + $name_val = $adb->query_result($result,0,"lastname"); + if($name_val!="") + { + if(getFieldVisibilityPermission('Contacts', $current_user->id,'firstname') == '0') + { + $first_name = ''; + $first_name = $adb->query_result($result,0,"firstname"); + if($first_name != '') + $name_val .= " ".$first_name; + } + + $mod_name=$name_val; + $search_str=$adb->query_result($result, 0, "contact_no"); + } + } + //Passing name to graph + $mod_name = str_replace(":", ":", $mod_name); + if($mod_name_val!="") $mod_name_val.="::$mod_name"; + else $mod_name_val="$mod_name"; + + + //Passing count to graph + if($mod_cnt_val!="") $mod_cnt_val.="::$mod_count_val"; + else $mod_cnt_val="$mod_count_val"; + if($module!="") + { + //Check for Ticket Priority + if(($graph_type=="ticketsbypriority")) + { + $graph_for="ticketpriorities"; + } + + //added to get valid url in dashbord for tickets by team + if($graph_for == "ticketgroupname" || $graph_for == "groupname") $graph_for = "smownerid"; + + if($graph_for == "accountid") $graph_for = "account_id"; + $cvid = getCvIdOfAll($module); + if($module == "Home") + { + $cvid = getCvIdOfAll($mod_name); + $link_val="index.php?module=".$mod_name."&action=ListView&from_homepagedb=true&type=dbrd&query=true&owner=".$current_user->user_name."&viewname=".$cvid; + } + else if($module == "Contacts" || ($module=="Products" && ($graph_for == "quoteid" || $graph_for == "invoiceid" || $graph_for == "purchaseorderid"))) + $link_val="index.php?module=".$module."&action=ListView&from_dashboard=true&type=dbrd&query=true&".$graph_for."=".$id_name."&viewname=".$cvid; + else { + $esc_search_str = urlencode($search_str); + //$esc_search_str = htmlentities($search_str, ENT_QUOTES, $default_charset); + $link_val="index.php?module=".$module."&action=index&from_dashboard=true&search_text=".$esc_search_str."&search_field=".$graph_for."&searchtype=BasicSearch&query=true&type=entchar&viewname=".$cvid; + } + + if($graph_for == "account_id") $graph_for = "accountid"; + + //Adding the links to the graph + $link_val = str_replace(':', ':', $link_val); + if($i==0) + $bar_target_val .=$link_val; + else + $bar_target_val .="::".$link_val; + } + //The data as per given date + if($i==0) + $urlstring .=$mod_cnt_crtd_date; + else + $urlstring .="K".$mod_cnt_crtd_date; + + if($i==0) + $test_target_val.=$link_val; + else + $test_target_val.="K".$link_val; + } + $mod_cnt_table .=""; + //For all Days getting the vtiger_table + for($k=0; $k<$days;$k++) + { + $tdate=$date_array[$k]; + if(!isset($mod_tot_cnt_array[$tdate])) + $mod_tot_cnt_array[$tdate]="0"; + $tot= $mod_tot_cnt_array[$tdate]; + if($period_type!="yday") + $mod_cnt_table.=""; + } + if($graph_for == "productname") + { + $cnt_total=array_sum($mod_count_array); + } + else + { + $cnt_total=array_sum($mod_tot_cnt_array); + } + + $mod_cnt_table.="
Status $table_formatTotal
Total$tot$cnt_total
"; + $mod_cnt_table.="
"; + $title_of_graph="$title : $cnt_total"; + $bar_target_val=urlencode($bar_target_val); + $test_target_val=urlencode($test_target_val); + + + $Prod_mod_val=array($mod_name_val,$mod_cnt_val,$title_of_graph,$bar_target_val,$mod_graph_date,$urlstring,$mod_cnt_table,$test_target_val); + return $Prod_mod_val; + } + else + { + $data=0; + + } + + } + else + { + $data=0; + return "

The data is not available with the specified time period

"; + } + return $data; +} + + +/** Saving the images of the graph in the /cache/images + * otherwise it will render the graph with the given details + * Portions created by vtiger are Copyright (C) vtiger. + * All Rights Reserved. + * Contributor(s): ______________________________________.. +*/ + + +function save_image_map($filename,$image_map) +{ + + + global $log; + + if (!$handle = fopen($filename, 'w')) { + $log->debug(" Cannot open file ($filename)"); + return; + } + + // Write $somecontent to our opened file. + if (fwrite($handle, $image_map) === FALSE) { + $log->debug(" Cannot write to file ($filename)"); + return false; + } + + fclose($handle); + return true; +} + +function get_graph_by_type($graph_by,$graph_title,$module,$where,$query,$width=900,$height=900,$frompage='') +{ + global $user_id,$date_start,$end_date,$type,$mod_strings; + $time = time(); + //Giving the Cached image name + $cache_file_name=abs(crc32($user_id))."_".$type."_".crc32($date_start.$end_date).$time.".png"; + $html_imagename=$graph_by; //Html image name for the graph + + $graph_details=module_Chart($user_id,$date_start,$end_date,$query,$graph_by,$graph_title,$where,$module,$type); + if($graph_details!=0) + { + $name_val=$graph_details[0]; + $cnt_val=$graph_details[1]; + $graph_title=$graph_details[2]; + $target_val=$graph_details[3]; + $graph_date=$graph_details[4]; + $urlstring=$graph_details[5]; + $cnt_table=$graph_details[6]; + $test_target_val=$graph_details[7]; + + if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') + { + $width = 250; + $height = 250; + }else + { + $width = 850; + $height = 500; + } + + $top=20; + $left=140; + $bottom=120; + $title=$graph_title; + if($frompage != '') + { + //echo $width.'------'.$height.'------'.$left.'------'.$right.'------'.$top.'------'.$bottom.'------'.$title.'------'.$test_target_val.'------'.$date_start.'------'.$end_date; + //die; + return get_graph_homepg($cache_file_name,$html_imagename,$cnt_val,$name_val,280,285,$left,$right,$top,$bottom,$title,$target_val,$graph_date,$urlstring,$test_target_val,$date_start,$end_date); + + }else + { + return get_graph($cache_file_name,$html_imagename,$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$graph_date,$urlstring,$test_target_val,$date_start,$end_date); + } + } + else + { + sleep(1); + echo '

'.$mod_strings['LBL_NO_DATA'].'

'; + } + +} + +/** Returns the Horizontal,vertical, pie graphs and Accumulated Graphs +for the details +* Portions created by vtiger are Copyright (C) vtiger. +* All Rights Reserved. +* Contributor(s): ______________________________________.. +*/ + + +// Function for get graphs +function get_graph($cache_file_name,$html_imagename,$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,$graph_date,$urlstring,$test_target_val,$date_start,$end_date) +{ + + global $tmp_dir; + global $graph_title, $mod_strings; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $val=explode(":",$title); + $display_title=$val[0]; + + if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') + { + $sHTML .="
"; + } + +$sHTML .= " + + + + + + + + + "; + +$sHTML .= " + + + + + "; + + if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') + { + $sHTML .="
+ + + + + + + +
1".$display_title."
".$mod_strings['LBL_HORZ_BAR_CHART']."
+
"; + if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') + { + $sHTML .= " "; + + }else + { + $sHTML .= " + + + + + + +
".$mod_strings['VIEWCHART']." : 12
"; + } + $sHTML .="
"; + + + $sHTML .= render_graph($tmp_dir."hor_".$cache_file_name,$html_imagename."_hor",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"horizontal"); +//Commented by Minnie -- same content displayed in two graphs +/*$sHTML .= "

+ + + + + + + +
2".$graph_title."
Vertical Bar Chart
+
"; + + $sHTML .= render_graph($tmp_dir."vert_".$cache_file_name,$html_imagename."_vert",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"vertical");*/ + +$sHTML .= "
"; + }else + { + $sHTML .= ""; + } + +$sHTML .= " + + + + + + "; + +if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') +{ + $sHTML .="
 
+ + + + + + + +
2".$graph_title."
".$mod_strings['LBL_PIE_CHART']."
+
"; + if(isset($_REQUEST['display_view']) && $_REQUEST['display_view'] == 'MATRIX') + { + $sHTML .= " "; + + }else + { + $sHTML .= " + + + + + + +
".$mod_strings['VIEWCHART']." : 12
"; + } + $sHTML .="
"; + + $sHTML .= render_graph($tmp_dir."pie_".$cache_file_name,$html_imagename."_pie",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"pie"); + +$sHTML .= "
 
+ + + + + + + +
1".$graph_title."
Horizontal Bar Chart
+
"; + + $sHTML .= render_graph($tmp_dir."hor_".$cache_file_name,$html_imagename."_hor",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"horizontal"); +//Commented by Minnie -- same content displayed in to graphs +/*$sHTML .= "

+ + + + + + + +
2".$graph_title."
Vertical Bar Chart
+
"; + + $sHTML .= render_graph($tmp_dir."vert_".$cache_file_name,$html_imagename."_vert",$cnt_val,$name_val,$width,$height,$left,$right,$top,$bottom,$title,$target_val,"vertical");*/ + +$sHTML .= "

+ + + + + + + +
2".$graph_title."
Pie Chart
+
"; + + $sHTML .= render_graph($tmp_dir."pie_".$cache_file_name,$html_imagename."_pie",$cnt_val,$name_val,$width,$height,40,$right,$top,$bottom,$title,$target_val,"pie"); + +$sHTML .= "

'; + //Charts for Lead Source + if($profileTabsPermission[getTabid("Leads")] == 0 && ($type == "leadsource") && (getFieldVisibilityPermission('Leads',$user_id,'leadsource') == "0")) + { + $graph_by="leadsource"; + $graph_title= $mod_strings['leadsource']; + $module="Leads"; + $where=""; + $query=$leads_query." ".dashboard_check($module); + //$html .= get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + // To display the charts for Lead status + elseif ($profileTabsPermission[getTabid("Leads")] == 0 && ($type == "leadstatus")&& (getFieldVisibilityPermission('Leads',$user_id,'leadstatus') == "0")) + { + $graph_by="leadstatus"; + $graph_title= $mod_strings['leadstatus']; + $module="Leads"; + $where=""; + $query=$leads_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_leaddetails.leadstatus '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Lead Industry + elseif ($profileTabsPermission[getTabid("Leads")] == 0 && ($type == "leadindustry") && (getFieldVisibilityPermission('Leads',$user_id,'industry') == "0")) + { + $graph_by="industry"; + $graph_title=$mod_strings['leadindustry']; + $module="Leads"; + $where=""; + $query=$leads_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_leaddetails.industry '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Sales by Lead Source + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyleadsource")&& (getFieldVisibilityPermission('Potentials',$user_id,'leadsource') == "0")) + { + $graph_by="leadsource"; + $graph_title=$mod_strings['salesbyleadsource']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like 'Closed Won' "; + $query=$potential_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_potential.leadsource '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Sales by Account + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyaccount") && (getFieldVisibilityPermission('Potentials',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['salesbyaccount']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like 'Closed Won' "; + $query=$potential_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Sales by User + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyuser")) + { + $graph_by="smownerid"; + $graph_title=$mod_strings['salesbyuser']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like 'Closed Won' and (vtiger_crmentity.smownerid != NULL || vtiger_crmentity.smownerid != ' ')"; + $query=$potential_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Sales by team + elseif ($profileTabsPermission[getTabid("Potentials")] == 0 && ($type == "salesbyteam")) + { + $graph_by="groupname"; + $graph_title=$mod_strings['salesbyteam']; + $module="Potentials"; + $where=" and vtiger_potential.sales_stage like 'Closed Won' and (vtiger_groups.groupname != NULL || vtiger_groups.groupname != '')"; + $query=$potential_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Account by Industry + elseif ($profileTabsPermission[getTabid("Accounts")] == 0 && ($type == "accountindustry") && (getFieldVisibilityPermission('Accounts',$user_id,'industry') == "0")) + { + $graph_by="industry"; + $graph_title=$mod_strings['accountindustry']; + $module="Accounts"; + $where=""; + $query=$account_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_account.industry '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Products by Category + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productcategory") && (getFieldVisibilityPermission('Products',$user_id,'productcategory') == "0")) + { + $graph_by="productcategory"; + $graph_title=$mod_strings['productcategory']; + $module="Products"; + $where=""; + $query=$product_category." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_products.productcategory '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Products by Quantity in stock + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbyqtyinstock") && (getFieldVisibilityPermission('Products',$user_id,'qtyinstock') == "0")) + { + $graph_by="productname"; + $graph_title=$mod_strings['productbyqtyinstock']; + $module="Products"; + $where=""; + $query=$products_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Products by PO + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbypo") && $profileTabsPermission[getTabid("PurchaseOrder")] == 0) + { + $graph_by="purchaseorderid"; + $graph_title=$mod_strings['productbypo']; + $module="Products"; + $where=""; + $query=$probyPO." ".dashboard_check("PurchaseOrder"); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Products by Quotes + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbyquotes") && $profileTabsPermission[getTabid("Quotes")] == 0) + { + $graph_by="quoteid"; + $graph_title=$mod_strings['productbyquotes']; + $module="Products"; + $where=""; + $query=$probyQ." ".dashboard_check("Quotes"); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Charts for Products by Invoice + elseif ($profileTabsPermission[getTabid("Products")] == 0 && ($type == "productbyinvoice") && $profileTabsPermission[getTabid("Invoice")] == 0) + { + $graph_by="invoiceid"; + $graph_title=$mod_strings['productbyinvoice']; + $module="Products"; + $where=""; + $query=$probyInv." ".dashboard_check("Invoice"); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + + // Sales Order by Accounts + elseif ($profileTabsPermission[getTabid("SalesOrder")] == 0 && ($type == "sobyaccounts") && (getFieldVisibilityPermission('SalesOrder',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['sobyaccounts']; + $module="SalesOrder"; + $where=""; + $query=$so_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Sales Order by Status + elseif ($profileTabsPermission[getTabid("SalesOrder")] == 0 && ($type == "sobystatus") && (getFieldVisibilityPermission('SalesOrder',$user_id,'sostatus') == "0")) + { + $graph_by="sostatus"; + $graph_title=$mod_strings['sobystatus']; + $module="SalesOrder"; + $where=""; + $query=$so_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_salesorder.sostatus '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Purchase Order by Status + elseif ($profileTabsPermission[getTabid("PurchaseOrder")] == 0 && ($type == "pobystatus") && (getFieldVisibilityPermission('PurchaseOrder',$user_id,'postatus') == "0")) + { + $graph_by="postatus"; + $graph_title=$mod_strings['pobystatus']; + $module="PurchaseOrder"; + $where=""; + $query=$po_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_purchaseorder.postatus '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Quotes by Accounts + elseif ($profileTabsPermission[getTabid("Quotes")] == 0 && ($type == "quotesbyaccounts") && (getFieldVisibilityPermission('Quotes',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title= $mod_strings['quotesbyaccounts']; + $module="Quotes"; + $where=""; + $query=$quotes_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Quotes by Stage + elseif ($profileTabsPermission[getTabid("Quotes")] == 0 && ($type == "quotesbystage") && (getFieldVisibilityPermission('Quotes',$user_id,'quotestage') == "0")) + { + $graph_by="quotestage"; + $graph_title=$mod_strings['quotesbystage']; + $module="Quotes"; + $where=""; + $query=$quotes_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_quotes.quotestage '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Invoice by Accounts + elseif ($profileTabsPermission[getTabid("Invoice")] == 0 && ($type == "invoicebyacnts") && (getFieldVisibilityPermission('Invoice',$user_id,'account_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['invoicebyacnts']; + $module="Invoice"; + $where=""; + $query=$invoice_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Invoices by status + elseif ($profileTabsPermission[getTabid("Invoice")] == 0 && ($type == "invoicebystatus") && (getFieldVisibilityPermission('Invoice',$user_id,'invoicestatus') == "0")) + { + $graph_by="invoicestatus"; + $graph_title=$mod_strings['invoicebystatus']; + $module="Invoice"; + $where=""; + $query=$invoice_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_invoice.invoicestatus '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Status + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbystatus") && (getFieldVisibilityPermission('HelpDesk',$user_id,'ticketstatus') == "0")) + { + $graph_by="ticketstatus"; + $graph_title=$mod_strings['ticketsbystatus']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_troubletickets.status '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Priority + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbypriority") && (getFieldVisibilityPermission('HelpDesk',$user_id,'ticketpriorities') == "0")) + { + $graph_by="priority"; + $graph_title=$mod_strings['ticketsbypriority']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_troubletickets.priority '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Category + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbycategory") && (getFieldVisibilityPermission('HelpDesk',$user_id,'ticketcategories') == "0")) + { + $graph_by="category"; + $graph_title=$mod_strings['ticketsbycategory']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + if(!$is_admin) + $query .= ' and vtiger_troubletickets.category '.picklist_check($module,$graph_by); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by User + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyuser")) + { + $graph_by="smownerid"; + $graph_title=$mod_strings['ticketsbyuser']; + $module="HelpDesk"; + $where=" and (vtiger_crmentity.smownerid != NULL || vtiger_crmentity.smownerid != ' ')"; + $query=$helpdesk_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Team + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyteam")) + { + $graph_by="ticketgroupname"; + $graph_title=$mod_strings['ticketsbyteam']; + $module="HelpDesk"; + $where=" and (vtiger_groups.groupname != NULL || vtiger_groups.groupname != ' ')"; + $query=$helpdesk_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Product + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyproduct") && (getFieldVisibilityPermission('HelpDesk',$user_id,'product_id') == "0")) + { + $graph_by="product_id"; + $graph_title=$mod_strings['ticketsbyproduct']; + $module="HelpDesk"; + $where=""; + $query=$helpdesk_query." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Campaigns by Contact + elseif ($profileTabsPermission[getTabid("Contacts")] == 0 && ($type == "contactbycampaign") && $profileTabsPermission[getTabid("Campaigns")] == 0) + { + $graph_by="campaignid"; + $graph_title=$mod_strings['contactbycampaign']; + $module="Contacts"; + $where=""; + $query=$campaign_query." ".dashboard_check("Campaigns"); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Account + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbyaccount") && (getFieldVisibilityPermission('HelpDesk',$user_id,'parent_id') == "0")) + { + $graph_by="accountid"; + $graph_title=$mod_strings['ticketsbyaccount']; + $module="HelpDesk"; + $where=""; + $query=$tickets_by_account." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + //Tickets by Contact + elseif ($profileTabsPermission[getTabid("HelpDesk")] == 0 && ($type == "ticketsbycontact") && (getFieldVisibilityPermission('HelpDesk',$user_id,'parent_id') == "0")) + { + $graph_by="contactid"; + $graph_title=$mod_strings['ticketsbycontact']; + $module="HelpDesk"; + $where=""; + $query=$tickets_by_contact." ".dashboard_check($module); + echo get_graph_by_type($graph_by,$graph_title,$module,$where,$query); + } + else + { + //echo $mod_strings['LBL_NO_PERMISSION_FIELD']; + sleep(1); + echo '

'.$mod_strings['LBL_NO_PERMISSION_FIELD'].'

'; + } + } +} + +/**This function generates the security parameters for a given module based on the assigned profile +*Param $module - module name +*Returns an string value +*/ + +function dashboard_check($module) +{ + global $current_user; + $sec_parameter = ''; + $tab_id = getTabid($module); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) + { + $sec_parameter=getListViewSecurityParameter($module); + } + return $sec_parameter; +} + +/**This function generates the security parameters for a given user base picklist values +*Param $graph - name of the graph +*Returns an string value +*/ + +function picklist_check($module,$graph_by) +{ + global $current_user,$adb; + $pick_query = ''; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + if($graph_by == 'sostatus' || $graph_by == 'leadsource' || $graph_by == 'leadstatus' ||$graph_by == 'industry' || $graph_by == 'productcategory' || $graph_by == 'postatus' || $graph_by == 'invoicestatus' || $graph_by == 'ticketstatus' || $graph_by == 'priority' || $graph_by == 'category' || $graph_by == 'quotestage') + { + $temp_fieldname = $graph_by; + if($graph_by == 'priority') + $temp_fieldname = 'ticketpriorities'; + if($graph_by == 'category') + $temp_fieldname = 'ticketcategories'; + + if(count($roleids) > 1) + $pick_query = " in (select distinct $temp_fieldname from vtiger_".$temp_fieldname." inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_".$temp_fieldname.".picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\")) "; + else + $pick_query = " in (select distinct $temp_fieldname from vtiger_".$temp_fieldname." inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_".$temp_fieldname.".picklist_valueid where roleid in ('$roleids')) "; + } + return $pick_query; +} +?> + diff --git a/oss/vtiger/trunk/modules/Dashboard/homestuff.php b/oss/vtiger/trunk/modules/Dashboard/homestuff.php new file mode 100644 index 00000000..a48637d4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/homestuff.php @@ -0,0 +1,90 @@ + $mod_strings['leadsource'], + "leadstatus" => $mod_strings['leadstatus'], + "leadindustry" => $mod_strings['leadindustry'], + "salesbyleadsource" => $mod_strings['salesbyleadsource'], + "salesbyaccount" => $mod_strings['salesbyaccount'], + "salesbyuser" => $mod_strings['salesbyuser'], + "salesbyteam" => $mod_strings['salesbyteam'], + "accountindustry" => $mod_strings['accountindustry'], + "productcategory" => $mod_strings['productcategory'], + "productbyqtyinstock" => $mod_strings['productbyqtyinstock'], + "productbypo" => $mod_strings['productbypo'], + "productbyquotes" => $mod_strings['productbyquotes'], + "productbyinvoice" => $mod_strings['productbyinvoice'], + "sobyaccounts" => $mod_strings['sobyaccounts'], + "sobystatus" => $mod_strings['sobystatus'], + "pobystatus" => $mod_strings['pobystatus'], + "quotesbyaccounts" => $mod_strings['quotesbyaccounts'], + "quotesbystage" => $mod_strings['quotesbystage'], + "invoicebyacnts" => $mod_strings['invoicebyacnts'], + "invoicebystatus" => $mod_strings['invoicebystatus'], + "ticketsbystatus" => $mod_strings['ticketsbystatus'], + "ticketsbypriority" => $mod_strings['ticketsbypriority'], + "ticketsbycategory" => $mod_strings['ticketsbycategory'], + "ticketsbyuser" => $mod_strings['ticketsbyuser'], + "ticketsbyteam" => $mod_strings['ticketsbyteam'], + "ticketsbyproduct"=> $mod_strings['ticketsbyproduct'], + "contactbycampaign"=> $mod_strings['contactbycampaign'], + "ticketsbyaccount"=> $mod_strings['ticketsbyaccount'], + "ticketsbycontact"=> $mod_strings['ticketsbycontact'], + ); + + $log = LoggerManager::getLogger('dashboard'); + if(isset($type) && $type != '') + { + $dashboard_type = $type; + }else + { + $dashboard_type = 'DashboardHome'; + } + + if(!isset($type)) + { + }else + { + require_once('modules/Dashboard/display_charts.php'); + $_REQUEST['type'] = $type; + $_REQUEST['Chart_Type'] = $Chart_Type; + $_REQUEST['from_page'] = 'HomePage'; + $dashval=dashBoardDisplayChart(); + return $dashval; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/horizontal_bargraph.php b/oss/vtiger/trunk/modules/Dashboard/horizontal_bargraph.php new file mode 100644 index 00000000..2fd4ded0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/horizontal_bargraph.php @@ -0,0 +1,248 @@ +=14) + $name=substr($name, 0, 44); + if($pos>=2) + { + $val=explode(" ",$name); + $n=count($val)-1; + + $x=""; + for($j=0;$j $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 12 + $font->setSize(8); + + if($theme == "blue") + { + $font_color = "#212473"; + } + else + { + $font_color = "#000000"; + } + $font->setColor($font_color); + + $graph->setFont($font); + $titlestr =& Image_Graph::factory('title', array($title,8)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'axis', + 'axis', + 'horizontal' + )); + $graph->add( + Image_Graph::vertical($titlestr, + $plotarea, + 5 + ) + ); + + + // Now create a bar plot + $max=0; + // To create unique lables we need to keep track of lable name and its count + $uniquex = array(); + + $xlabels = array(); + $dataset = & Image_Graph::factory('dataset'); + if($theme == 'woodspice') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL_MIRRORED, '#804000', 'white')); + elseif($theme == 'bluelagoon') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL_MIRRORED, 'blue', 'white')); + elseif($theme == 'softed') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL_MIRRORED, 'blue', 'white')); + elseif($theme == 'hawebs') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL_MIRRORED, 'blue', 'white')); + else + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL_MIRRORED, 'black', 'white')); + + for($i=0;$i=$max) $max=$datay[$i]; + $dataset->addPoint( + $x, + $datay[$i], + array( + 'url' => $target[$i], + 'alt' => $alts[$i] + ) + ); + // build the xaxis label array to allow intermediate ticks + + $xlabels[$x] = $datax[$i]; + $xlabels[$x+1] = ''; + + // To have unique names even in case of duplicates let us add the id + $datax_appearance = $uniquex[$datax[$i]]; + if($datax_appearance == null) { + $uniquex[$datax[$i]] = 1; + } else { + $xlabels[$x] = $datax[$i] .' ['. $datax_appearance.']'; + $uniquex[$datax[$i]] = $datax_appearance + 1; + } + } + + $bplot = & $plotarea->addNew('bar', $dataset); + $bplot->setFillStyle($fill); + + //You can change the width of the bars if you like + $bplot->setBarWidth(50/count($datax),"%"); + $bplot->setPadding(array('top'=>10)); + + // We want to display the value of each bar at the top + //$bplot->value->Show(); + //$bplot->value->SetFont(FF_FONT2,FS_BOLD,12); + //$bplot->value->SetAlign('left','center'); + //$bplot->value->SetColor("black","gray4"); + //$bplot->value->SetFormat('%d'); + + //$graph->SetBackgroundGradient('#E5E5E5','white',GRAD_VER,BGRAD_PLOT); + $bplot->setBackground(Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL, 'white', 'white'))); + //$bplot->setBackground(Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL, 'white', '#E5E5E5'))); + //$bplot->SetFillGradient("navy","lightsteelblue",GRAD_MIDVER); + + //$graph->SetFrame(false); + //$graph->SetMarginColor('cadetblue2'); + //$graph->ygrid->SetFill(true,'azure1','azure2'); + //$graph->xgrid->Show(); + + // Add the bar to the graph + //$graph->Add($bplot); + + // Setup title + //$titlestr->setText($title); + + // Setup X-axis + $xaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_X); + $yaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_Y); + $yaxis->setFontSize(10); + + // Invert X-axis and put Y-axis at bottom + $xaxis->setInverted(true); + $yaxis->setAxisIntersection('max'); + + // set grid + $gridY =& $plotarea->addNew('line_grid', IMAGE_GRAPH_AXIS_Y); + $gridY->setLineColor('#FFFFFF@0.5'); + $gridY2 =& $plotarea->addNew('bar_grid', null, IMAGE_GRAPH_AXIS_Y); + $gridY2->setFillColor('#FFFFFF@0.2'); + + + // Add some grace to y-axis so the bars doesn't go + // all the way to the end of the plot area + $yaxis->forceMaximum(round(($max * 1.1) + 0.5)); + $ticks = get_tickspacing(round(($max * 1.1) + 0.5)); + + // First make the labels look right + $yaxis->setLabelInterval($ticks[0]); + $yaxis->setTickOptions(-5,0); + $yaxis->setLabelInterval($ticks[1],2); + $yaxis->setTickOptions(-2,0,2); + + // Create the xaxis labels + $array_data =& Image_Graph::factory('Image_Graph_DataPreprocessor_Array', + array($xlabels) + ); + + // The fix the tick marks + $xaxis->setDataPreprocessor($array_data); + $xaxis->forceMinimum(0); + $xaxis->forceMaximum(2*count($datay)); + $xaxis->setLabelInterval(1); + $xaxis->setTickOptions(0,0); + $xaxis->setLabelInterval(2,2); + $xaxis->setTickOptions(5,0,2); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setFillColor('000000@0.0'); + $marker->setBorderColor('000000@0.0'); + $marker->setFontSize(10); + // shift markers 10 pix right + $marker_pointing =& $graph->addNew('Image_Graph_Marker_Pointing', array(40,0,& $marker)); + $marker_pointing->setLineColor('000000@0.0'); + $bplot->setMarker($marker_pointing); + + + //Getting the graph in the form of html page + $img = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => '', + 'urlpath' => '' + )); + save_image_map($cache_file_name.'.map', $img); + + return $img; +} + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/index.php b/oss/vtiger/trunk/modules/Dashboard/index.php new file mode 100644 index 00000000..79fb3ee2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/index.php @@ -0,0 +1,393 @@ + $mod_strings['DashboardHome'], + "leadsource" => $mod_strings['leadsource'], + "leadstatus" => $mod_strings['leadstatus'], + "leadindustry" => $mod_strings['leadindustry'], + "salesbyleadsource" => $mod_strings['salesbyleadsource'], + "salesbyaccount" => $mod_strings['salesbyaccount'], + "salesbyuser" => $mod_strings['salesbyuser'], + "salesbyteam" => $mod_strings['salesbyteam'], + "accountindustry" => $mod_strings['accountindustry'], + "productcategory" => $mod_strings['productcategory'], + "productbyqtyinstock" => $mod_strings['productbyqtyinstock'], + "productbypo" => $mod_strings['productbypo'], + "productbyquotes" => $mod_strings['productbyquotes'], + "productbyinvoice" => $mod_strings['productbyinvoice'], + "sobyaccounts" => $mod_strings['sobyaccounts'], + "sobystatus" => $mod_strings['sobystatus'], + "pobystatus" => $mod_strings['pobystatus'], + "quotesbyaccounts" => $mod_strings['quotesbyaccounts'], + "quotesbystage" => $mod_strings['quotesbystage'], + "invoicebyacnts" => $mod_strings['invoicebyacnts'], + "invoicebystatus" => $mod_strings['invoicebystatus'], + "ticketsbystatus" => $mod_strings['ticketsbystatus'], + "ticketsbypriority" => $mod_strings['ticketsbypriority'], + "ticketsbycategory" => $mod_strings['ticketsbycategory'], + "ticketsbyuser" => $mod_strings['ticketsbyuser'], + "ticketsbyteam" => $mod_strings['ticketsbyteam'], + "ticketsbyproduct"=> $mod_strings['ticketsbyproduct'], + "contactbycampaign"=> $mod_strings['contactbycampaign'], + "ticketsbyaccount"=> $mod_strings['ticketsbyaccount'], + "ticketsbycontact"=> $mod_strings['ticketsbycontact'], + ); + +$log = LoggerManager::getLogger('dashboard'); +if(isset($_REQUEST['type']) && $_REQUEST['type'] != '') +{ + $dashboard_type = $_REQUEST['type']; +}else +{ + $dashboard_type = 'DashboardHome'; +} +?> + +
+ + + + + + + + + + + + +
> + + + + + +
+ + + + + +
+
+
  + + + + + + + + + + + + + +
<?php echo $app_strings['LBL_CALENDAR_ALT']; ?><?php echo $app_strings['LBL_CLOCK_ALT']; ?><?php echo $app_strings['LBL_CALCULATOR_ALT']; ?><?php echo $app_strings['LBL_CHAT_ALT']; ?> + + <?php echo $app_strings['LBL_LAST_VIEWED']; ?>
+
  + + + + + +
+
  + + + + +
<?php echo $app_strings['LBL_ALL_MENU_ALT']; ?>
+
+
+
+ + + + + + + + + + +
+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + +
  + + + + +
+ +
+ +
 
+ +
 
  + + + + + +
+ > > + <?php echo $mod_strings['NORMALVIEW'];?> | <?php echo $mod_strings['GRIDVIEW'];?>
+
 
 
+ + + + + + + +
  +
+ + + + + + +
+ + +  
+ + +
 
 
+ + + + + + + + + +
  + + + +
+
  
+ +
+ + + + + + +
 
+
+ +
+
+ + + + + + + + diff --git a/oss/vtiger/trunk/modules/Dashboard/language/en_us.lang.php b/oss/vtiger/trunk/modules/Dashboard/language/en_us.lang.php new file mode 100644 index 00000000..b96b89e5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/language/en_us.lang.php @@ -0,0 +1,191 @@ +'Pipeline By Sales Stage', +'LBL_SALES_STAGE_FORM_DESC'=>'Shows cumulative opportunity amounts by selected sales stages for selected users where the expected closed date is within the specificed date range.', +'LBL_MONTH_BY_OUTCOME'=>'Pipeline By Month By Outcome', +'LBL_MONTH_BY_OUTCOME_DESC'=>'Shows cumulative opportunity amounts by month by outcome for selected users where the expected closed date is within the specificed date range. Outcome is based on whether the sales stage is Closed Won, Closed Lost or any other value.', +'LBL_LEAD_SOURCE_FORM_TITLE'=>'All Opportunities By Lead Source', +'LBL_LEAD_SOURCE_FORM_DESC'=>'Shows cumulative opportunity amounts by selected lead source for selected users.', +'LBL_LEAD_SOURCE_BY_OUTCOME'=>'All Opportunities By Lead Source By Outcome', +'LBL_LEAD_SOURCE_BY_OUTCOME_DESC'=>'Shows cumulative opportunity amounts by selected lead source by outcome for selected users where the expected closed date is within the specificed date range. Outcome is based on whether the sales stage is Closed Won, Closed Lost or any other value.', +'LBL_PIPELINE_FORM_TITLE_DESC'=>'Shows cumulative amounts by selected sales stages for your opportunities where the expected closed date is within the specificed date range.', +'LBL_DATE_RANGE'=>'Date range is', +'LBL_DATE_RANGE_TO'=>'to', +'ERR_NO_OPPS'=>'Please create some Opportunities to see Opportunity graphs.', +'LBL_TOTAL_PIPELINE'=>'Pipeline total is ', +'LBL_ALL_OPPORTUNITIES'=>'Total amount of all opportunities is ', +'LBL_OPP_SIZE'=>'Opportunity size in ', +'LBL_OPP_SIZE_VALUE'=>'1K', +'NTC_NO_LEGENDS'=>'None', +'LBL_LEAD_SOURCE_OTHER'=>'Other', +'LBL_EDIT'=>'Edit', +'LBL_REFRESH'=>'Refresh', +'LBL_CREATED_ON'=>'Last run on ', +'LBL_OPPS_IN_STAGE'=>'opportunities where sales stage is', +'LBL_OPPS_IN_LEAD_SOURCE'=>'opportunities where lead source is', +'LBL_OPPS_OUTCOME'=>'opportunities where outcome is', +'LBL_USERS'=>'Users:', +'LBL_SALES_STAGES'=>'Sales Stages:', +'LBL_LEAD_SOURCES'=>'Lead Sources:', +'LBL_DATE_START'=>'Begin Date:', +'LBL_DATE_END'=>'End Date:', +//Added for 5.0 +'LBL_NO_PERMISSION'=>'Sorry, you don\'t have access to view the Graph for this module', +'LBL_NO_PERMISSION_FIELD'=>'Sorry, you don\'t have access to view the Graph for this module or for the Field', + +"leadsource" => "Leads By Source", +"leadstatus" => "Leads By Status", +"leadindustry" => "Leads By Industry", +"salesbyleadsource" => "Sales by LeadSource", +"salesbyaccount" => "Sales by Accounts", +"salesbyuser" => "Sales by User", +"salesbyteam"=>"Sales by Team", +"accountindustry" => "Account By Industry", +"productcategory" => "Products by Category", +"productbyqtyinstock" => "Products by Quantity in stock", +"productbypo" => "Products by PurchaseOrder", +"productbyquotes" => "Products by Quotes", +"productbyinvoice" => "Products by Invoice", +"sobyaccounts" => "Sales Order by Accounts", +"sobystatus" => "Sales Order by Status", +"pobystatus" => "Purchase Order by Status", +"quotesbyaccounts" => "Quotes by Accounts", +"quotesbystage" => "Quotes by Stage", +"invoicebyacnts" => "Invoices by Accounts", +"invoicebystatus" => "Invoices by Status", +"ticketsbystatus" => "Tickets by Status", +"ticketsbypriority" => "Tickets by Priority", +"ticketsbycategory" => "Tickets by Category", +"ticketsbyuser"=>"Tickets by User", +"ticketsbyteam"=>"Tickets by Team", +"ticketsbyproduct"=>"Tickets by Product", +"contactbycampaign"=>"Contacts by Campaign", +"ticketsbyaccount"=>"Tickets by Account", +"ticketsbycontact"=>"Tickets by Contact", + +'LBL_DASHBRD_HOME'=>'Dashboard Home', +'LBL_HORZ_BAR_CHART'=>'Horizontal Bar Chart', +'LBL_VERT_BAR_CHART'=>'Vertical Bar Chart', +'LBL_PIE_CHART'=>'Pie Chart', +'LBL_NO_DATA'=>'No data available', +'DashboardHome'=>'Dashboard Home', +'GRIDVIEW'=>'Grid view', +'NORMALVIEW'=>'Normal view', +'VIEWCHART'=>'View Chart', +'LBL_DASHBOARD'=>'Dashboard', + +// Added/Updated for vtiger CRM 5.0.4 +"Approved"=>"Approved", +"Created"=>"Created", +"Cancelled"=>"Cancelled", +"Delivered"=>"Delivered", +"Received Shipment"=>"Received Shipments", +"Sent"=>"Sent", +"Credit Invoice"=>"Credit Invoice", +"Paid"=>"Paid", +"Un Assigned"=>"Un Assigned", +"Cold Call"=>"Cold Call", +"Existing Customer"=>"Existing Customer", +"Self Generated"=>"Self Generated", +"Employee"=>"Employee", +"Partner"=>"Partner", +"Public Relations"=>"Public Relations", +"Direct Mail"=>"Direct Mail", +"Conference"=>"Conference", +"Trade Show"=>"Trade Show", +"Web Site"=>"Web Site", +"Word of mouth"=>"Word of mouth", +"Other"=>"Other", +"--None--"=>"None", +"Attempted to Contact"=>"Attempted to Contact", +"Cold"=>"Cold", +"Contact in Future"=>"Contact in Future", +"Contacted"=>"Contacted", +"Hot"=>"Hot", +"Junk Lead"=>"Junk Lead", +"Lost Lead"=>"Lost Lead", +"Not Contacted"=>"Not Contacted", +"Pre Qualified"=>"Pre Qualified", +"Qualified"=>"Qualified", +"Warm"=>"Warm", +"Apparel"=>"Apparel", +"Banking"=>"Banking", +"Biotechnology"=>"Biotechnology", +"Chemicals"=>"Chemicals", +"Communications"=>"Communications", +"Construction"=>"Constructions", +"Consulting"=>"Consulting", +"Education"=>"Education", +"Electronics"=>"Electronics", +"Energy"=>"Energy", +"Engineering"=>"Engineering", +"Entertainment"=>"Entertainment", +"Environmental"=>"Environmental", +"Finance"=>"Finance", +"Food & Beverage"=>"Food & Beverage", +"Government"=>"Government", +"Healthcare"=>"Healthcare", +"Hospitality"=>"Hospitality", +"Insurance"=>"Insurance", +"Machinery"=>"Machinery", +"Manufacturing"=>"Manufacturing", +"Media"=>"Media", +"Not For Profit"=>"Not For Profit", +"Recreation"=>"Recreation", +"Retail"=>"Retail", +"Shipping"=>"Shipping", +"Technology"=>"Technology", +"Telecommunications"=>"Telecommunications", +"Transportation"=>"Transportation", +"Utilities"=>"Utilities", +"Hardware"=>"Hardware", +"Software"=>"Software", +"CRM Applications"=>"CRM Applications", +"Open"=>"Open", +"In Progress"=>"In Progress", +"Wait For Response"=>"Wait For Response", +"Closed"=>"Closed", +"Low"=>"Low", +"Normal"=>"Normal", +"High"=>"High", +"Urgent"=>"Urgent", +"Big Problem"=>"Big Problem", +"Small Problem"=>"Small Problem", +"Other Problem"=>"Other Problem", +"Accepted"=>"Accepted", +"Rejected"=>"Rejected", +"Prospecting"=>"Prospecting", +"Qualification"=>"Qualifications", +"Needs Analysis"=>"Needs Analysis", +"Value Proposition"=>"Value Propositions", +"Id. Decision Makers"=>"Id. Decision Makers", +"Perception Analysis"=>"Perception Analysis", +"Proposal/Price Quote"=>"Proposal/Price Quotes", +"Negotiation/Review"=>"Negotiation/Review", +"Closed Won"=>"Closed Won", +"Closed Lost"=>"Closed Lost", + +); + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Dashboard/language/zh_cn.lang.php new file mode 100644 index 00000000..cf2460d7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/language/zh_cn.lang.php @@ -0,0 +1,190 @@ + '销售策略统计', + 'LBL_SALES_STAGE_FORM_DESC' => '显示选择的客服策略、使用者累计客服数量在指定期间内预期要结案.', + 'LBL_MONTH_BY_OUTCOME' => '月客服统计', + 'LBL_MONTH_BY_OUTCOME_DESC' => '显示选取使用者于指定期间的对外按月累计潜在案件,对外指的是根据客服策略判断优劣.', + 'LBL_LEAD_SOURCE_FORM_TITLE' => '经由接触来源的潜在案件', + 'LBL_LEAD_SOURCE_FORM_DESC' => '显示选取使用者潜在客户来源的累计潜在案件数量.', + 'LBL_LEAD_SOURCE_BY_OUTCOME' => '由潜在客户来源显示所有对外潜在案件', + 'LBL_LEAD_SOURCE_BY_OUTCOME_DESC' => '显示选取潜在客户来源于指定期间的对外按月累计潜在案件,对外指的是根据销售策略判断优劣.', + 'LBL_PIPELINE_FORM_TITLE_DESC' => '显示预期在指定期间结案的销售策略潜在案件数量.', + 'LBL_DATE_RANGE' => '日期范围从', + 'LBL_DATE_RANGE_TO' => '到', + 'ERR_NO_OPPS' => '请新增潜在案件,然后才能看见潜在案件图.', + 'LBL_TOTAL_PIPELINE' => '总处理数 ', + 'LBL_ALL_OPPORTUNITIES' => '潜在案件总数', + 'LBL_OPP_SIZE' => '预算在1万元以下的潜在案件', + 'LBL_OPP_SIZE_VALUE' => '1K', + 'NTC_NO_LEGENDS' => '无', + 'LBL_LEAD_SOURCE_OTHER' => '其它', + 'LBL_EDIT' => '编辑', + 'LBL_REFRESH' => '更新画面', + 'LBL_CREATED_ON' => '最后执行 ', + 'LBL_OPPS_IN_STAGE' => '潜在案件的客服场地', + 'LBL_OPPS_IN_LEAD_SOURCE' => '潜在案件的接触来源', + 'LBL_OPPS_OUTCOME' => '该潜在案件的处理结果', + 'LBL_USERS' => '使用者:', + 'LBL_SALES_STAGES' => '客服场地:', + 'LBL_LEAD_SOURCES' => '接触来源:', + 'LBL_DATE_START' => '开始日期:', + 'LBL_DATE_END' => '结束日期:', +//Added for 5.0 + 'LBL_NO_PERMISSION' => '您没有检视这个模块图形的权限', + 'LBL_NO_PERMISSION_FIELD' => '您没有检视这个模块或字段图形的权限', + + 'leadsource' => '依照来源显示潜在客户', + 'leadstatus' => '依照状态显示潜在客户', + 'leadindustry' => '依照行业显示潜在客户', + 'salesbyleadsource' => '依照潜在客户来源显示业绩', + 'salesbyaccount' => '依照客户显示业绩', + 'salesbyuser' => '依照业务显示业绩', + 'salesbyteam' => '依照团队显示业绩', + 'accountindustry' => '依照产业显示客户', + 'productcategory' => '依照类别显示产品', + 'productbyqtyinstock' => '依照库存数量显示产品', + 'productbypo' => '依照采购订单显示产品', + 'productbyquotes' => '依照报价单显示产品', + 'productbyinvoice' => '依照发票显示产品', +'sobyaccounts' => '依照客户显示销售订单', + 'sobystatus' => '依照状态显示销售订单', + 'pobystatus' => '依照状态显示采购订单', + 'quotesbyaccounts' => '依照客户显示报价单', + 'quotesbystage' => '依照销售策略显示报价单', + 'invoicebyacnts' => '依照公司显示发票', + 'invoicebystatus' => '依照状态显示发票', + 'ticketsbystatus' => '依照状态显示传票', + 'ticketsbypriority' => '依照优先级显示传票', + 'ticketsbycategory' => '依照类别显示传票', +'ticketsbyuser' => '依照业务显示传票', + 'ticketsbyteam' => '依照团队显示传票', + 'ticketsbyproduct' => '依照产品显示传票', + 'contactbycampaign' => '依照活动显示联络人', + 'ticketsbyaccount' => '依照客户显示传票', + 'ticketsbycontact' => '依照联络人显示传票', +'LBL_DASHBRD_HOME' => '统计图表首页', + 'LBL_HORZ_BAR_CHART' => '水平长条图', + 'LBL_VERT_BAR_CHART' => '垂直长条图', + 'LBL_PIE_CHART' => '圆饼图', + 'LBL_NO_DATA' => '没有资料', + 'DashboardHome' => '统计图表首页', + 'GRIDVIEW' => '格状检视', + 'NORMALVIEW' => '一般检视', + 'VIEWCHART' => '检视图表', + +'LBL_DASHBOARD' => '统计图表', +"Approved"=>"批准", +"Created"=>"创造", +"Cancelled"=>"取消", +"Delivered"=>"交付", +"Received Shipment"=>"被接受的发货", +"Sent"=>"发送", +"Credit Invoice"=>"信用发货票", +"Paid"=>"有偿", +"Un Assigned"=>"没有被分配", +"Cold Call"=>"备用电话", +"Existing Customer"=>"现有的客户", +"Self Generated"=>"自己引起的", +"Employee"=>"员工", +"Partner"=>"合作者", +"Public Relations"=>"公共关系", +"Direct Mail"=>"直接邮件", +"Conference"=>"会议", +"Trade Show"=>"商业展览", +"Web Site"=>"网站", +"Word of mouth"=>"口述", +"Other"=>"其他", +"--None--"=>"无", +"Attempted to Contact"=>"试图接触", +"Cold"=>"冷淡", +"Contact in Future"=>"以后联系", +"Contacted"=>"联系中", +"Hot"=>"关系火热", +"Junk Lead"=>"不好的潜在客户", +"Lost Lead"=>"丢失的潜在客户", +"Not Contacted"=>"没有联系", +"Pre Qualified"=>"基本合格", +"Qualified"=>"合格", +"Warm"=>"很好", +"Apparel"=>"服装", +"Banking"=>"银行业务", +"Biotechnology"=>"生物工艺", +"Chemicals"=>"化学制品", +"Communications"=>"通信", +"Construction"=>"建筑", +"Consulting"=>"咨询", +"Education"=>"教育", +"Electronics"=>"电子", +"Energy"=>"能源", +"Engineering"=>"工程", +"Entertainment"=>"娱乐", +"Environmental"=>"环保", +"Finance"=>"财务", +"Food & Beverage"=>"食品、饮料", +"Government"=>"政府", +"Healthcare"=>"医疗保健", +"Hospitality"=>"好客", +"Insurance"=>"保险", +"Machinery"=>"机械", +"Manufacturing"=>"制造业", +"Media"=>"媒介", +"Not For Profit"=>"非盈利", +"Recreation"=>"休闲", +"Retail"=>"零售业", +"Shipping"=>"航运", +"Technology"=>"技术", +"Telecommunications"=>"电信", +"Transportation"=>"交通运输", +"Utilities"=>"公共事业", +"Hardware"=>"硬件", +"Software"=>"软件", +"CRM Applications"=>"CRM 应用", +"Open"=>"开放", +"In Progress"=>"进展中", +"Wait For Response"=>"等待中", +"Closed"=>"未完成", +"Low"=>"低", +"Normal"=>"正常", +"High"=>"高", +"Urgent"=>"紧急", +"Big Problem"=>"大问题", +"Small Problem"=>"小问题", +"Other Problem"=>"其他问题", +"Accepted"=>"接受", +"Rejected"=>"拒绝", +"Prospecting"=>"勘察", +"Qualification"=>"资格", +"Needs Analysis"=>"需要分析", +"Value Proposition"=>"已提价", +"Id. Decision Makers"=>"Id. 决策者", +"Perception Analysis"=>"感性分析", +"Proposal/Price Quote"=>"建议/价格行情", +"Negotiation/Review"=>"交涉/回顾", +"Closed Won"=>"成功结单", +"Closed Lost"=>"丢失", + + +); + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/line_graph.php b/oss/vtiger/trunk/modules/Dashboard/line_graph.php new file mode 100644 index 00000000..88dfd67d --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/line_graph.php @@ -0,0 +1,104 @@ +SetMarginColor('white'); +$graph->SetScale("textlin"); +$graph->SetMargin($left,$right,$top,$bottom); +$graph->tabtitle->Set($title ); +$graph->tabtitle->SetFont(FF_FONT2,FS_BOLD,13); +$graph->yaxis->HideZeroLabel(); +$graph->xgrid->Show(); + +$thick=6; +// Create the lines of the Graph +for($i=0;$iSetColor($color_val); + $$temp->SetLegend($name); + + $x_thick=$thick-$i; + if($x_thick<=1) + $x_thick=1; + + $$temp->SetWeight($x_thick); + $graph->Add($$temp); + + $max=0; + for($j=0;$j=$max) + $max=$x; + else + $max=$max; + } +} + + +if($max>=5) +{ + $graph->yaxis->SetLabelFormat('%d'); +} +$graph->legend->Pos(0,0.4,"right","center"); + +// Set some other color then the boring default +$graph->SetColor("#6F96FF"); +//$graph->SetColor("#CCDFCC"); +$graph->SetMarginColor("#2447A7"); +//$graph->SetMarginColor("#98C098"); +$graph->xaxis->SetTickLabels($datax); +$graph->xaxis->SetLabelAngle(90); + +// Output line +$graph->Stroke(); + + + +?> diff --git a/oss/vtiger/trunk/modules/Dashboard/loadDashBoard.php b/oss/vtiger/trunk/modules/Dashboard/loadDashBoard.php new file mode 100644 index 00000000..96b535cb --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/loadDashBoard.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Dashboard/pie_graph.php b/oss/vtiger/trunk/modules/Dashboard/pie_graph.php new file mode 100644 index 00000000..60a36662 --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/pie_graph.php @@ -0,0 +1,191 @@ +=14) + $name=substr($name, 0, 34); + if($pos>=2) + { + $val=explode(" ",$name); + $n=count($val)-1; + + $x=""; + for($j=0;$j $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 11 pixels + $font->setSize(8); + $font->setColor($font_color); + + $graph->setFont($font); + // create the plotarea layout + $title =& Image_Graph::factory('title', array($title,10)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'category', + 'axis' + )); + $footer =& Image_Graph::factory('title', array('Footer',8)); + $legend_box =& Image_Graph::factory('legend'); + $graph->add( + Image_Graph::vertical($title, + $plotarea, + 5 + ) + ); + + // To create unique lables we need to keep track of lable name and its count + $uniquex = array(); + + + // Generate colours + $colors = color_generator(count($datay),'#33DDFF','#3322FF'); + $dataset = & Image_Graph::factory('dataset'); + $fills =& Image_Graph::factory('Image_Graph_Fill_Array'); + $sum = 0; + for($i=0;$iaddPoint( + $datalabel, + $datay[$i], + array( + 'url' => $target[$i], + 'alt' => $alts[$i] + ) + ); + $sum += $datay[$i]; + $fills->addColor($colors[$i]); + } + + // create an array with % values + $pcvalues = array(); + for($i=0;$iaddNew('pie', $dataset); + $plotarea->setPadding(array('top'=>20,'bottom'=>0,'left'=>0,'right'=>50)); + $plotarea->hideAxis(); + $gbplot->setFillStyle($fills); + + // format the data values + $marker_array =& Image_Graph::factory('Image_Graph_DataPreprocessor_Array', array($pcvalues)); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setDataPreprocessor($marker_array); + $marker->setFillColor('#FFFFFF'); + $marker->setBorderColor($font_color); + $marker->setFontColor($font_color); + $marker->setFontSize(8); + $pointingMarker =& $graph->addNew('Image_Graph_Marker_Pointing_Angular', array(20, &$marker)); + $gbplot->setMarker($pointingMarker); + + // set legend + $legend_box =& $plotarea->addNew('legend'); + $legend_box->setPadding(array('top'=>20,'bottom'=>0,'left'=>0,'right'=>0)); + $legend_box->setFillColor('#F5F5F5'); + $legend_box->showShadow(); + + $img = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => '', + 'urlpath' => '' + )); + save_image_map($cache_file_name.'.map', $img); + + return $img; + +} +?> + diff --git a/oss/vtiger/trunk/modules/Dashboard/vertical_bargraph.php b/oss/vtiger/trunk/modules/Dashboard/vertical_bargraph.php new file mode 100644 index 00000000..0b809f2c --- /dev/null +++ b/oss/vtiger/trunk/modules/Dashboard/vertical_bargraph.php @@ -0,0 +1,224 @@ +=15) + $name=substr($name, 0, 15); + if($pos>=2) + { + $val=explode(" ",$name); + $n=count($val)-1; + + $x=""; + for($j=0;$j $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 12 + $font->setSize(8); + + if($theme == "blue") + { + $font_color = "#212473"; + } + else + { + $font_color = "#000000"; + } + $font->setColor($font_color); + + $graph->setFont($font); + $titlestr =& Image_Graph::factory('title', array($title,10)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'axis', + 'axis', + 'vertical' + )); + $graph->add( + Image_Graph::vertical($titlestr, + $plotarea, + 5 + ) + ); + + + // Now create a bar plot + $max=0; + $xlabels = array(); + $dataset = & Image_Graph::factory('dataset'); + if($theme == 'woodspice') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL_MIRRORED, '#804000', 'white')); + elseif($theme == 'bluelagoon') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL_MIRRORED, 'blue', 'white')); + elseif($theme == 'softed') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL_MIRRORED, 'blue', 'white')); + elseif($theme == 'hawebs') + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL_MIRRORED, 'blue', 'white')); + else + $fill =& Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL_MIRRORED, 'black', 'white')); + + + for($i=0;$i=$max) $max=$datay[$i]; + $dataset->addPoint( + $x, + $datay[$i], + array( + 'url' => $target[$i], + 'alt' => $alts[$i] + ) + ); + // build the xaxis label array to allow intermediate ticks + $xlabels[$x] = $datax[$i]; + $xlabels[$x+1] = ''; + } + + + //$bplot = new BarPlot($datay); + $bplot = & $plotarea->addNew('bar', $dataset); + $bplot->setFillStyle($fill); + + //You can change the width of the bars if you like + $bplot->setBarWidth(50/count($datax),"%"); + $bplot->setPadding(array('top'=>20)); + + $bplot->setBackground(Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL, 'white', 'white'))); + + // Setup X-axis + $xaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_X); + $yaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_Y); + $yaxis->setFontSize(10); + + // set grid + $gridY =& $plotarea->addNew('line_grid', IMAGE_GRAPH_AXIS_Y); + $gridY->setLineColor('#FFFFFF@0.5'); + $gridY2 =& $plotarea->addNew('bar_grid', null, IMAGE_GRAPH_AXIS_Y); + $gridY2->setFillColor('#FFFFFF@0.2'); + + + // Add some grace to y-axis so the bars doesn't go + // all the way to the end of the plot area + if($max<=10) + $yaxis->forceMaximum(round(($max * 1.1) + 1.5)); + elseif($max>10 && $max<=100) + $yaxis->forceMaximum(round(($max * 1.1) + 1.5)); + elseif($max>100 && $max<=1000) + $yaxis->forceMaximum(round(($max * 1.1) + 10.5)); + else + $yaxis->forceMaximum(round(($max * 1.1) + 100.5)); + $ticks = get_tickspacing(round(($max * 1.1) + 2.0)); + + // First make the labels look right + $yaxis->setLabelInterval($ticks[0]); + $yaxis->setTickOptions(5,0); + $yaxis->setLabelInterval($ticks[1],2); + $yaxis->setTickOptions(2,0,2); + + // Create the xaxis labels + $array_data =& Image_Graph::factory('Image_Graph_DataPreprocessor_Array', + array($xlabels) + ); + + // Then fix the tick marks + $xaxis->setDataPreprocessor($array_data); + $xaxis->forceMinimum(0); + $xaxis->forceMaximum(2*count($datay)); + $xaxis->setFontAngle('vertical'); + $xaxis->setLabelInterval(1); + $xaxis->setTickOptions(0,0); + $xaxis->setLabelInterval(2,2); + $xaxis->setTickOptions(5,0,2); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setFillColor('000000@0.0'); + $marker->setBorderColor('000000@0.0'); + $marker->setFontSize(10); + // shift markers 10 pix right + $marker_pointing =& $graph->addNew('Image_Graph_Marker_Pointing', array(0,-10,& $marker)); + $marker_pointing->setLineColor('000000@0.0'); + $bplot->setMarker($marker_pointing); + + + //Getting the graph in the form of html page + $img = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => '', + 'urlpath' => '' + )); + save_image_map($cache_file_name.'.map', $img); + + return $img; +} + +?> diff --git a/oss/vtiger/trunk/modules/Documents/CustomView.php b/oss/vtiger/trunk/modules/Documents/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Documents/Delete.php b/oss/vtiger/trunk/modules/Documents/Delete.php new file mode 100644 index 00000000..85401813 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/Delete.php @@ -0,0 +1,28 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/DeleteFolder.php b/oss/vtiger/trunk/modules/Documents/DeleteFolder.php new file mode 100644 index 00000000..fa147ef1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/DeleteFolder.php @@ -0,0 +1,54 @@ +is_admin != 'on') +{ + echo 'NOT_PERMITTED'; + die; +} +else +{ + $local_log =& LoggerManager::getLogger('index'); + if(isset($_REQUEST['folderid']) && $_REQUEST['folderid'] != '') + $folderId = $_REQUEST['folderid']; + else + { + echo 'FAILURE'; + die; + } + if(isset($_REQUEST['deletechk']) && $_REQUEST['deletechk'] == 'true') + { + $query = "select notesid from vtiger_notes INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_notes.notesid WHERE vtiger_notes.folderid = ? and vtiger_crmentity.deleted = 0"; + $result = $adb->pquery($query,array($folderId)); + if($adb->num_rows($result) > 0) + { + echo 'FAILURE'; + } + else + { + header("Location: index.php?action=DocumentsAjax&file=ListView&mode=ajax&module=Documents"); + exit; + } + } + else + { + $sql="delete from vtiger_attachmentsfolder where (folderid=? and folderid != 1)"; + $adb->pquery($sql,array($folderId)); + header("Location: index.php?action=DocumentsAjax&file=ListView&mode=ajax&module=Documents"); + exit; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/DetailView.php b/oss/vtiger/trunk/modules/Documents/DetailView.php new file mode 100644 index 00000000..33814eac --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/DetailView.php @@ -0,0 +1,175 @@ +retrieve_entity_info($_REQUEST['record'],"Documents"); + $focus->id = $_REQUEST['record']; + $focus->name=$focus->column_fields['notes_title']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +//needed when creating a new note with default values passed in +if (isset($_REQUEST['contact_name']) && is_null($focus->contact_name)) { + $focus->contact_name = $_REQUEST['contact_name']; +} +if (isset($_REQUEST['contact_id']) && is_null($focus->contact_id)) { + $focus->contact_id = $_REQUEST['contact_id']; +} +if (isset($_REQUEST['opportunity_name']) && is_null($focus->parent_name)) { + $focus->parent_name = $_REQUEST['opportunity_name']; +} +if (isset($_REQUEST['opportunity_id']) && is_null($focus->parent_id)) { + $focus->parent_id = $_REQUEST['opportunity_id']; +} +if (isset($_REQUEST['account_name']) && is_null($focus->parent_name)) { + $focus->parent_name = $_REQUEST['account_name']; +} +if (isset($_REQUEST['account_id']) && is_null($focus->parent_id)) { + $focus->parent_id = $_REQUEST['account_id']; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Document detail view"); + +$smarty = new vtigerCRM_Smarty; +$dbQuery="select filename,folderid,filelocationtype,filestatus from vtiger_notes where notesid = ?"; +$result=$adb->pquery($dbQuery,array($focus->id)); +$filename=$adb->query_result($result,0,'filename'); +$folderid=$adb->query_result($result,0,'folderid'); +$filestatus=$adb->query_result($result,0,'filestatus'); +$filelocationtype=$adb->query_result($result,0,'filelocationtype'); + +$fileattach = "select attachmentsid from vtiger_seattachmentsrel where crmid = ?"; +$res = $adb->pquery($fileattach,array($focus->id)); +$fileid = $adb->query_result($res,0,'attachmentsid'); + +if($filelocationtype == 'I'){ + $pathQuery = $adb->pquery("select path from vtiger_attachments where attachmentsid = ?",array($fileid)); + $filepath = $adb->query_result($pathQuery,0,'path'); +} +else{ + $filepath = $filename; +} + + +$smarty->assign("FILEID",$fileid); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$allblocks = getBlocks($currentModule,"detail_view",'',$focus->column_fields); +$smarty->assign("BLOCKS", $allblocks); +$flag = 0; +foreach($allblocks as $blocks) +{ + foreach($blocks as $block_entries) + { + if($block_entries['File Name']['value'] != '' || isset($block_entries['File Name']['value'])) + $flag = 1; + } +} +if($flag == 1) + $smarty->assign("FILE_EXIST","yes"); +elseif($flag == 0) + $smarty->assign("FILE_EXIST","no"); + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); + +$smarty->assign("FILENAME", $filename); + +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'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $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 + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + + +$smarty->assign("SINGLE_MOD", 'Document'); + +if(isPermitted("Documents","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("Documents","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + + +$tabid = getTabid("Documents"); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data = split_validationdataArray($validationData); + + $smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); + $smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); + $smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + if($current_user->id == 1) +{ + $smarty->assign("CHECK_INTEGRITY_PERMISSION","yes"); + $smarty->assign("ADMIN","yes"); +} +$smarty->assign("FILE_STATUS",$filestatus); + $smarty->assign("DLD_TYPE",$filelocationtype); + $smarty->assign("NOTESID",$focus->id); + $smarty->assign("FOLDERID",$folderid); + $smarty->assign("DLD_PATH",$filepath); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("DetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/DetailViewAjax.php b/oss/vtiger/trunk/modules/Documents/DetailViewAjax.php new file mode 100644 index 00000000..d9e93b58 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/DetailViewAjax.php @@ -0,0 +1,45 @@ +retrieve_entity_info($crmid,"Documents"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Documents"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/Documents.js b/oss/vtiger/trunk/modules/Documents/Documents.js new file mode 100644 index 00000000..2ceb8e73 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/Documents.js @@ -0,0 +1,322 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + +//Added after 504 for renaming a folder +function UpdateAjaxSave(label,fid,fldname,fileOrFolder) +{ + fldVal=$('txtbox_'+label).value; + if(fldVal.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) + { + alert(alert_arr.FOLDERNAME_EMPTY); + return false; + } + if(fldVal.replace(/^\s+/g, '').replace(/\s+$/g, '').length>=21) + { + alert(alert_arr.FOLDER_NAME_TOO_LONG); + return false; + } + if(fldVal.match(/['"\\%+?]/)) + { + alert(alert_arr.NO_SPECIAL_CHARS_DOCS); + return false; + } + if(fileOrFolder == 'file') + var url='action=DocumentsAjax&mode=ajax&file=Save&module=Documents&fileid='+fid+'&fldVal='+fldVal+'&fldname='+fldname+'&act=ajaxEdit'; + else + { + var foldername = encodeURIComponent(fldVal); + foldername = foldername.replace(/^\s+/g, '').replace(/\s+$/g, ''); + foldername = foldername.replace(/&/gi,'*amp*'); + var url='action=DocumentsAjax&mode=ajax&file=SaveFolder&module=Documents&record='+fid+'&foldername='+fldVal+'&savemode=Save'; + } + if(fldname == 'status') + { + fldVal = $('txtbox_'+label).options[$('txtbox_'+label).options.selectedIndex].text; + gtempselectedIndex = $('txtbox_'+label).options.selectedIndex; + } + $('status').style.display="block"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: url, + onComplete: function(response) { + var item = response.responseText; + $('status').style.display="none"; + if(item.indexOf("Failure") > -1 ) + { + $("lblError").innerHTML="
"+alert_arr.LBL_UNABLE_TO_UPDATE+"
"; + setTimeout(hidelblError,3000); + } + else if(item.indexOf('DUPLICATE_FOLDERNAME') > -1) + { + alert(alert_arr.DUPLICATE_FOLDER_NAME); + } + else + { + $('dtlview_'+label).innerHTML = fldVal; + eval("hndCancel('dtlview_"+label+"','editarea_"+label+"','"+label+"')"); + if(fldname == 'status') + $('txtbox_'+label).selectedIndex = gtempselectedIndex; + else + $('txtbox_'+label).value = fldVal; + eval(item); + + } + + } + } + ); + +} + +function closeFolderCreate() +{ + $('folder_id').value = ''; + $('folder_name').value = ''; + $('folder_desc').value=''; + fninvsh('orgLay') +} + +function AddFolder() +{ + var fldrname=getObj('folder_name').value; + var fldrdesc=getObj('folder_desc').value; + if(fldrname.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) + { + alert(alert_arr.FOLDERNAME_EMPTY); + return false; + } + if(fldrname.replace(/^\s+/g, '').replace(/\s+$/g, '').length>=21) + { + alert(alert_arr.FOLDER_NAME_TOO_LONG); + return false; + } + if(fldrdesc.replace(/^\s+/g, '').replace(/\s+$/g, '').length>=51) + { + alert(alert_arr.FOLDER_DESCRIPTION_TOO_LONG); + return false; + } + if(fldrname.match(/['"\\%+]/) || fldrdesc.match(/['"\\%+]/)) + { + alert(alert_arr.NO_SPECIAL_CHARS_DOCS+alert_arr.NAME_DESC); + return false; + } + if(fldrname.match(/[?]+$/) || fldrname.match(/[?]+/)) + { + alert(alert_arr.NO_SPECIAL_CHARS_DOCS); + return false; + } + fninvsh('orgLay'); + var foldername = encodeURIComponent(getObj('folder_name').value); + var folderdesc = encodeURIComponent(getObj('folder_desc').value); + foldername = foldername.replace(/^\s+/g, '').replace(/\s+$/g, ''); + foldername = foldername.replace(/&/gi,'*amp*'); + folderdesc = folderdesc.replace(/^\s+/g, '').replace(/\s+$/g, ''); + folderdesc = folderdesc.replace(/&/gi,'*amp*'); + getObj('folder_name').value = ''; + getObj('folder_desc').value = ''; + var mode = getObj('fldrsave_mode').value; + if(mode == 'save') + { + url ='&savemode=Save&foldername='+foldername+'&folderdesc='+folderdesc; + } + getObj('fldrsave_mode').value = 'save'; + $('status').style.display = 'block'; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'action=DocumentsAjax&mode=ajax&file=SaveFolder&module=Documents'+url, + onComplete: function(response) { + var item = response.responseText; + $('status').style.display = 'none'; + if(item.indexOf('Failure') > -1) + { + $('lblError').innerHTML = "
"+alert_arr.LBL_UNABLE_TO_ADD_FOLDER+"
"; + setTimeOutFn(); + } + else if(item.indexOf('DUPLICATE_FOLDERNAME') > -1) + { + alert(alert_arr.DUPLICATE_FOLDER_NAME); + } + else + { + getObj("ListViewContents").innerHTML = item; + } + } + } + ); +} + + +function DeleteFolderCheck(folderId) +{ + gtempfolderId = folderId; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Documents&action=DocumentsAjax&mode=ajax&file=DeleteFolder&deletechk=true&folderid="+folderId, + onComplete: function(response) { + var item = response.responseText; + if(item.indexOf("NOT_PERMITTED") > -1) { + alert(alert_arr.NOT_PERMITTED); + return false; + } + else if(item.indexOf("FAILURE") > -1) + { + alert(alert_arr.LBL_FOLDER_SHOULD_BE_EMPTY); + } + else { + if(confirm(alert_arr.LBL_ARE_YOU_SURE_YOU_WANT_TO_DELETE_FOLDER)) + { + DeleteFolder(gtempfolderId); + } + } + } + } + ); +} + +function DeleteFolder(folderId) +{ + $('status').style.display = "block"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Documents&action=DocumentsAjax&mode=ajax&file=DeleteFolder&folderid="+folderId, + onComplete: function(response) { + var item = response.responseText; + $('status').style.display = "none"; + if(item.indexOf("FAILURE") > -1) + alert(alert_arr.LBL_ERROR_WHILE_DELETING_FOLDER); + else + $('ListViewContents').innerHTML = item; + } + } + ); +} + +function MoveFile(id,foldername) +{ + fninvsh('movefolderlist'); + var select_options = document.getElementById('allselectedboxes').value; + var x = select_options.split(";"); + var searchurl= document.getElementById('search_url').value; + var count=x.length + var viewid =getviewId(); + var idstring = ""; + if (count > 1) + { + document.getElementById('idlist').value=select_options; + idstring = select_options; + } + else + { + alert(alert_arr.SELECT); + return false; + } + + if(idstring != '') + { + if(confirm(alert_arr.LBL_ARE_YOU_SURE_TO_MOVE_TO + foldername + alert_arr.LBL_FOLDER)) + { + $('status').style.display = "block"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'action=DocumentsAjax&file=MoveFile&from_folderid=0&module=Documents&folderid='+id+'&idlist='+idstring, + onComplete: function(response) { + var item = response.responseText; + $('status').style.display = "none"; + if(item.indexOf("NOT_PERMITTED") > -1 ) { + $("lblError").innerHTML="
"+alert_arr.NOT_PERMITTED+"
"; + setTimeout(hidelblError,3000); + } + else + getObj('ListViewContents').innerHTML = item; + } + + } + ); + }else{ + return false; + } + + }else + { + alert(alert_arr.LBL_SELECT_ONE_FILE); + return false; + } +} + +function dldCntIncrease(fileid) +{ + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'action=DocumentsAjax&mode=ajax&file=SaveFile&module=Documents&file_id='+fileid+"&act=updateDldCnt", + onComplete: function(response) { + } + } + ); +} + + +function checkFileIntegrityDetailView(noteid) +{ + $('vtbusy_integrity_info').style.display=''; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=Documents&action=DocumentsAjax&mode=ajax&file=SaveFile&act=checkFileIntegrityDetailView¬eid='+noteid, + onComplete: function(response) { + var item = response.responseText; + if(item.indexOf('file_available') > -1) + { + $('vtbusy_integrity_info').style.display='none'; + $('integrity_result').innerHTML='

   '+alert_arr.LBL_FILE_CAN_BE_DOWNLOAD+''; + $('integrity_result').style.display=''; + setTimeout(hideresult,4000); + } + else if(item.indexOf('file_not_available') > -1) + { + $('vtbusy_integrity_info').style.display='none'; + $('integrity_result').innerHTML='

   '+alert_arr.LBL_DOCUMENT_NOT_AVAILABLE+''; + $('integrity_result').style.display=''; + setTimeout(hideresult,6000); + } + else if(item.indexOf('lost_integrity') > -1) + { + $('vtbusy_integrity_info').style.display='none'; + $('integrity_result').innerHTML='

   '+alert_arr.LBL_DOCUMENT_LOST_INTEGRITY+''; + $('integrity_result').style.display=''; + setTimeout(hideresult,6000); + } + } + } + ); +} + +function hideresult() +{ + $('integrity_result').style.display = 'none'; +} + +function add_data_to_relatedlist(entity_id,recordid) { + + opener.document.location.href="index.php?module={RETURN_MODULE}&action=updateRelations&smodule={SMODULE}&destination_module=Products&entityid="+entity_id+"&parentid="+recordid; +} + diff --git a/oss/vtiger/trunk/modules/Documents/Documents.php b/oss/vtiger/trunk/modules/Documents/Documents.php new file mode 100644 index 00000000..024e294a --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/Documents.php @@ -0,0 +1,441 @@ +'crmid','vtiger_notes'=>'notesid','vtiger_senotesrel'=>'notesid'); + + var $column_fields = Array(); + + var $sortby_fields = Array('title','modifiedtime','filename','createdtime','lastname','filedownloadcount','smownerid'); + + // This is used to retrieve related vtiger_fields from form posts. + var $additional_column_fields = Array('', '', '', ''); + + // This is the list of vtiger_fields that are in the lists. + var $list_fields = Array( + 'Title'=>Array('notes'=>'title'), + 'File Name'=>Array('notes'=>'filename'), + 'Assigned To' => Array('crmentity'=>'smownerid'), + 'Folder Name' => Array('attachmentsfolder'=>'foldername') + ); + var $list_fields_name = Array( + 'Title'=>'notes_title', + 'File Name'=>'filename', + 'Assigned To'=>'assigned_user_id', + 'Folder Name' => 'folderid' + ); + + var $search_fields = Array( + 'Title' => Array('notes'=>'notes_title'), + 'File Name' => Array('notes'=>'filename'), + 'Assigned To' => Array('crmentity'=>'smownerid'), + 'Folder Name' => Array('attachmentsfolder'=>'foldername') + ); + + var $search_fields_name = Array( + 'Title' => 'notes_title', + 'File Name' => 'filename', + 'Assigned To' => 'assigned_user_id', + 'Folder Name' => 'folderid' + ); + var $list_link_field= 'notes_title'; + var $old_filename = ''; + //var $groupTable = Array('vtiger_notegrouprelation','notesid'); + + var $mandatory_fields = Array('notes_title','createdtime' ,'modifiedtime','filename','filesize','filetype','filedownloadcount','assigned_user_id'); + + //Added these variables which are used as default order by and sortorder in ListView + var $default_order_by = 'title'; + var $default_sort_order = 'ASC'; + function Documents() { + $this->log = LoggerManager::getLogger('notes'); + $this->log->debug("Entering Documents() method ..."); + $this->db = PearDatabase::getInstance(); + $this->column_fields = getColumnFields('Documents'); + $this->log->debug("Exiting Documents method ..."); + } + + function save_module($module) + { + global $log,$adb,$upload_badext; + $insertion_mode = $this->mode; + if(isset($this->parentid) && $this->parentid != '') + $relid = $this->parentid; + //inserting into vtiger_senotesrel + if(isset($relid) && $relid != '') + { + $this->insertintonotesrel($relid,$this->id); + } + $filetype_fieldname = $this->getFileTypeFieldName(); + $filename_fieldname = $this->getFile_FieldName(); + if($this->column_fields[$filetype_fieldname] == 'I' ){ + if($_FILES[$filename_fieldname]['name'] != ''){ + $errCode=$_FILES[$filename_fieldname]['error']; + if($errCode == 0){ + foreach($_FILES as $fileindex => $files) + { + if($files['name'] != '' && $files['size'] > 0){ + $filename = $_FILES[$filename_fieldname]['name']; + $filename = from_html(preg_replace('/\s+/', '_', $filename)); + $filetype = $_FILES[$filename_fieldname]['type']; + $filesize = $_FILES[$filename_fieldname]['size']; + $filelocationtype = 'I'; + $binFile = sanitizeUploadFileName($filename, $upload_badext); + $filename = ltrim(basename(" ".$binFile)); //allowed filename like UTF-8 characters + } + } + + } + }elseif($this->mode == 'edit') { + $fileres = $adb->pquery("select filetype, filesize,filename,filedownloadcount,filelocationtype from vtiger_notes where notesid=?", array($this->id)); + if ($adb->num_rows($fileres) > 0) { + $filename = $adb->query_result($fileres, 0, 'filename'); + $filetype = $adb->query_result($fileres, 0, 'filetype'); + $filesize = $adb->query_result($fileres, 0, 'filesize'); + $filedownloadcount = $adb->query_result($fileres, 0, 'filedownloadcount'); + $filelocationtype = $adb->query_result($fileres, 0, 'filelocationtype'); + } + }elseif($this->column_fields[$filename_fieldname]) { + $filename = $this->column_fields[$filename_fieldname]; + $filesize = $this->column_fields['filesize']; + $filetype = $this->column_fields['filetype']; + $filelocationtype = $this->column_fields[$filetype_fieldname]; + $filedownloadcount = 0; + } + } else{ + $filelocationtype = 'E'; + $filename = $this->column_fields[$filename_fieldname]; + // If filename does not has the protocol prefix, default it to http:// + // Protocol prefix could be like (https://, smb://, file://, \\, smb:\\,...) + if(!empty($filename) && !preg_match('/^\w{1,5}:\/\/|^\w{0,3}:?\\\\\\\\/', trim($filename), $match)) { + $filename = "http://$filename"; + } + $filetype = ''; + $filesize = 0; + $filedownloadcount = null; + } + $query = "UPDATE vtiger_notes SET filename = ? ,filesize = ?, filetype = ? , filelocationtype = ? , filedownloadcount = ? WHERE notesid = ?"; + $re=$adb->pquery($query,array($filename,$filesize,$filetype,$filelocationtype,$filedownloadcount,$this->id)); + //Inserting into attachments table + if($filelocationtype == 'I') { + $this->insertIntoAttachment($this->id,'Documents'); + }else{ + $query = "delete from vtiger_seattachmentsrel where crmid = ?"; + $qparams = array($this->id); + $adb->pquery($query, $qparams); + } + } + + + /** + * This function is used to add the vtiger_attachments. This will call the function uploadAndSaveFile which will upload the attachment into the server and save that attachment information in the database. + * @param int $id - entity id to which the vtiger_files to be uploaded + * @param string $module - the current module name + */ + function insertIntoAttachment($id,$module) + { + global $log, $adb; + $log->debug("Entering into insertIntoAttachment($id,$module) method."); + + $file_saved = false; + + foreach($_FILES as $fileindex => $files) + { + if($files['name'] != '' && $files['size'] > 0) + { + $files['original_name'] = vtlib_purify($_REQUEST[$fileindex.'_hidden']); + $file_saved = $this->uploadAndSaveFile($id,$module,$files); + } + } + + $log->debug("Exiting from insertIntoAttachment($id,$module) method."); + } + + /** Function used to get the sort order for Documents listview + * @return string $sorder - first check the $_REQUEST['sorder'] if request value is empty then check in the $_SESSION['NOTES_SORT_ORDER'] if this session value is empty then default sort order will be returned. + */ + function getSortOrder() + { + global $log; + $log->debug("Entering getSortOrder() method ..."); + if(isset($_REQUEST['sorder'])) + $sorder = $this->db->sql_escape_string($_REQUEST['sorder']); + else + $sorder = (($_SESSION['NOTES_SORT_ORDER'] != '')?($_SESSION['NOTES_SORT_ORDER']):($this->default_sort_order)); + $log->debug("Exiting getSortOrder() method ..."); + return $sorder; + } + + /** Function used to get the order by value for Documents listview + * @return string $order_by - first check the $_REQUEST['order_by'] if request value is empty then check in the $_SESSION['NOTES_ORDER_BY'] if this session value is empty then default order by will be returned. + */ + function getOrderBy() + { + global $log; + $log->debug("Entering getOrderBy() method ..."); + + $use_default_order_by = ''; + if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) { + $use_default_order_by = $this->default_order_by; + } + + if (isset($_REQUEST['order_by'])) + $order_by = $this->db->sql_escape_string($_REQUEST['order_by']); + else + $order_by = (($_SESSION['NOTES_ORDER_BY'] != '')?($_SESSION['NOTES_ORDER_BY']):($use_default_order_by)); + $log->debug("Exiting getOrderBy method ..."); + return $order_by; + } + + + /** Function to export the notes in CSV Format + * @param reference variable - where condition is passed when the query is executed + * Returns Export Documents Query. + */ + function create_export_query($where) + { + global $log,$current_user; + $log->debug("Entering create_export_query(". $where.") method ..."); + + include("include/utils/ExportUtils.php"); + //To get the Permitted fields query and the permitted fields list + $sql = getPermittedFieldsQuery("Documents", "detail_view"); + $fields_list = getFieldsListFromQuery($sql); + + $query = "SELECT $fields_list, case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name" . + " FROM vtiger_notes + inner join vtiger_crmentity + on vtiger_crmentity.crmid=vtiger_notes.notesid + LEFT JOIN vtiger_attachmentsfolder on vtiger_notes.folderid=vtiger_attachmentsfolder.folderid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id " . + " LEFT JOIN vtiger_groups ON vtiger_crmentity.smownerid=vtiger_groups.groupid " + ; + + $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'); + //we should add security check when the user has Private Access + $tabid = getTabid("Documents"); + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tabid] == 3) + { + //Added security check to get the permitted records only + $query = $query." ".getListViewSecurityParameter("Documents"); + } + + + $log->debug("Exiting create_export_query method ..."); + return $query; + } + + function del_create_def_folder($query) + { + global $adb; + $dbQuery = $query." and vtiger_attachmentsfolder.folderid = 0"; + $dbresult = $adb->pquery($dbQuery,array()); + $noofnotes = $adb->num_rows($dbresult); + if($noofnotes > 0) + { + $folderQuery = "select folderid from vtiger_attachmentsfolder"; + $folderresult = $adb->pquery($folderQuery,array()); + $noofdeffolders = $adb->num_rows($folderresult); + if($noofdeffolders == 0) + { + $insertQuery = "insert into vtiger_attachmentsfolder values (0,'Default','Contains all attachments for which a folder is not set',1,0)"; + $insertresult = $adb->pquery($insertQuery,array()); + } + } + + } + + function insertintonotesrel($relid,$id) + { + global $adb; + $dbQuery = "insert into vtiger_senotesrel values ( ?, ? )"; + $dbresult = $adb->pquery($dbQuery,array($relid,$id)); + } + + /*function save_related_module($module, $crmid, $with_module, $with_crmid){ + global $log; + $log->debug("indocument".$module.$crmid.$with_module.$with_crmid); + if(isset($this->parentid) && $this->parentid != '') + $relid = $this->parentid; + //inserting into vtiger_senotesrel + if(isset($relid) && $relid != '') + { + $this->insertintonotesrel($relid,$this->id); + } + }*/ + + + /* + * Function to get the primary query part of a report + * @param - $module Primary module name + * returns the query string formed on fetching the related data for report for primary module + */ + function generateReportsQuery($module){ + $moduletable = $this->table_name; + $moduleindex = $this->tab_name_index[$moduletable]; + $query = "from $moduletable + inner join vtiger_crmentity on vtiger_crmentity.crmid=$moduletable.$moduleindex + inner join vtiger_attachmentsfolder on vtiger_attachmentsfolder.folderid=$moduletable.folderid + left join vtiger_groups as vtiger_groups".$module." on vtiger_groups".$module.".groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_users".$module." on vtiger_users".$module.".id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid"; + return $query; + + } + + /* + * Function to get the secondary query part of a report + * @param - $module primary module name + * @param - $secmodule secondary module name + * returns the query string formed on fetching the related data for report for secondary module + */ + function generateReportsSecQuery($module,$secmodule){ + $query = $this->getRelationQuery($module,$secmodule,"vtiger_notes","notesid"); + $query .=" left join vtiger_crmentity as vtiger_crmentityDocuments on vtiger_crmentityDocuments.crmid=vtiger_notes.notesid and vtiger_crmentityDocuments.deleted=0 + left join vtiger_attachmentsfolder on vtiger_attachmentsfolder.folderid=vtiger_notes.folderid + left join vtiger_groups as vtiger_groupsDocuments on vtiger_groupsDocuments.groupid = vtiger_crmentityDocuments.smownerid + left join vtiger_users as vtiger_usersDocuments on vtiger_usersDocuments.id = vtiger_crmentityDocuments.smownerid"; + + return $query; + } + + /* + * Function to get the relation tables for related modules + * @param - $secmodule secondary module name + * returns the array with table names and fieldnames storing relations between module and this module + */ + function setRelationTables($secmodule){ + $rel_tables = array(); + return $rel_tables[$secmodule]; + } + + // Function to unlink all the dependent entities of the given Entity by Id + function unlinkDependencies($module, $id) { + global $log; + /*//Backup Documents Related Records + $se_q = 'SELECT crmid FROM vtiger_senotesrel WHERE notesid = ?'; + $se_res = $this->db->pquery($se_q, array($id)); + if ($this->db->num_rows($se_res) > 0) { + for($k=0;$k < $this->db->num_rows($se_res);$k++) + { + $se_id = $this->db->query_result($se_res,$k,"crmid"); + $params = array($id, RB_RECORD_DELETED, 'vtiger_senotesrel', 'notesid', 'crmid', $se_id); + $this->db->pquery('INSERT INTO vtiger_relatedlists_rb VALUES (?,?,?,?,?,?)', $params); + } + } + $sql = 'DELETE FROM vtiger_senotesrel WHERE notesid = ?'; + $this->db->pquery($sql, array($id));*/ + + parent::unlinkDependencies($module, $id); + } + + // Function to unlink an entity with given Id from another entity + function unlinkRelationship($id, $return_module, $return_id) { + global $log; + if(empty($return_module) || empty($return_id)) return; + + $sql = 'DELETE FROM vtiger_senotesrel WHERE notesid = ? AND crmid = ?'; + $this->db->pquery($sql, array($id, $return_id)); + + $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)'; + $params = array($id, $return_module, $return_id, $id, $return_module, $return_id); + $this->db->pquery($sql, $params); + } + + +// Function to get fieldname for uitype 27 assuming that documents have only one file type field + + function getFileTypeFieldName(){ + global $adb,$log; + $query = 'SELECT fieldname from vtiger_field where tabid = ? and uitype = ?'; + $tabid = getTabid('Documents'); + $filetype_uitype = 27; + $res = $adb->pquery($query,array($tabid,$filetype_uitype)); + $fieldname = null; + if(isset($res)){ + $rowCount = $adb->num_rows($res); + if($rowCount > 0){ + $fieldname = $adb->query_result($res,0,'fieldname'); + } + } + return $fieldname; + + } + +// Function to get fieldname for uitype 28 assuming that doc has only one file upload type + + function getFile_FieldName(){ + global $adb,$log; + $query = 'SELECT fieldname from vtiger_field where tabid = ? and uitype = ?'; + $tabid = getTabid('Documents'); + $filename_uitype = 28; + $res = $adb->pquery($query,array($tabid,$filename_uitype)); + $fieldname = null; + if(isset($res)){ + $rowCount = $adb->num_rows($res); + if($rowCount > 0){ + $fieldname = $adb->query_result($res,0,'fieldname'); + } + } + return $fieldname; + } + + /** + * Check the existence of folder by folderid + */ + function isFolderPresent($folderid) { + global $adb; + $result = $adb->pquery("SELECT folderid FROM vtiger_attachmentsfolder WHERE folderid = ?", array($folderid)); + if(!empty($result) && $adb->num_rows($result) > 0) return true; + return false; + } + + /** + * Customizing the restore procedure. + */ + function restore($modulename, $id) { + parent::restore($modulename, $id); + + global $adb; + $fresult = $adb->pquery("SELECT folderid FROM vtiger_notes WHERE notesid = ?", array($id)); + if(!empty($fresult) && $adb->num_rows($fresult)) { + $folderid = $adb->query_result($fresult, 0, 'folderid'); + if(!$this->isFolderPresent($folderid)) { + // Re-link to default folder + $adb->pquery("UPDATE vtiger_notes set folderid = 1 WHERE notesid = ?", array($id)); + } + } + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/DocumentsAjax.php b/oss/vtiger/trunk/modules/Documents/DocumentsAjax.php new file mode 100644 index 00000000..ce66087f --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/DocumentsAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Documents/DownloadFile.php b/oss/vtiger/trunk/modules/Documents/DownloadFile.php new file mode 100644 index 00000000..4122becc --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/DownloadFile.php @@ -0,0 +1,68 @@ +pquery("select crmid from vtiger_seattachmentsrel where attachmentsid = ?",array($fileid)); +$noteid = $adb->query_result($noteQuery,0,'crmid'); +$dbQuery = "SELECT * FROM vtiger_notes WHERE notesid = ? and folderid= ?"; +$result = $adb->pquery($dbQuery,array($noteid,$folderid)) or die("Couldn't get file list"); +if($adb->num_rows($result) == 1) +{ + $fileType = @$adb->query_result($result, 0, "filetype"); + $name = @$adb->query_result($result, 0, "filename"); + $name = html_entity_decode($name, ENT_QUOTES, $default_charset); + $pathQuery = $adb->pquery("select path from vtiger_attachments where attachmentsid = ?",array($fileid)); + $filepath = $adb->query_result($pathQuery,0,'path'); + + $saved_filename = $fileid."_".$name; + if(!$filepath.$saved_filename) + $saved_filename = $fileid."_".$name; + + $filesize = filesize($filepath.$saved_filename); + if(!fopen($filepath.$saved_filename, "r")) + { + echo 'unable to open file'; + $log->debug('Unable to open file'); + } + else + { + $fileContent = fread(fopen($filepath.$saved_filename, "r"), $filesize); + } + if($fileContent != '') + { + $log->debug('About to update download count'); + $sql = "select filedownloadcount from vtiger_notes where notesid= ?"; + $download_count = $adb->query_result($adb->pquery($sql,array($fileid)),0,'filedownloadcount') + 1; + $sql="update vtiger_notes set filedownloadcount= ? where notesid= ?"; + $res=$adb->pquery($sql,array($download_count,$fileid)); + } + + header("Content-type: $fileType"); + header("Content-length: $filesize"); + header("Cache-Control: private"); + header("Content-Disposition: attachment; filename=$name"); + header("Content-Description: PHP Generated Data"); + echo $fileContent; +} +else +{ + echo "Record doesn't exist."; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/EditView.php b/oss/vtiger/trunk/modules/Documents/EditView.php new file mode 100644 index 00000000..b483e3ef --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/EditView.php @@ -0,0 +1,226 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if($_REQUEST['upload_error'] == true) +{ + echo '
'.$mod_strings['FILE_HAS_NO_DATA'].'.
'; +} + +if(isset($_REQUEST['record']) && $_REQUEST['record'] !='') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Documents"); + $focus->name=$focus->column_fields['notes_title']; +} + +if($focus->mode != 'edit') +{ + if(isset($_REQUEST['parent_id']) && isset($_REQUEST['return_module'])) + { + $owner = getRecordOwnerId($_REQUEST['parent_id']); + if(isset($owner['Users']) && $owner['Users'] != '') { + $permitted_users = get_user_array('true', 'Active',$current_user->id); + if(!in_array($owner['Users'],$permitted_users)){ + $owner['Users'] = $current_user->id; + } + $focus->column_fields['assigntype'] = 'U'; + $focus->column_fields['assigned_user_id'] = $owner['Users']; + } elseif(isset($owner['Groups']) && $owner['Groups'] != '') { + $focus->column_fields['assigntype'] = 'T'; + $focus->column_fields['assigned_user_id'] = $owner['Groups']; + } + } +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +if(isset($_REQUEST['parent_id']) && $focus->mode != 'edit') { + $smarty->assign("PARENTID",vtlib_purify($_REQUEST['parent_id'])); +} + +$dbQuery="select filename from vtiger_notes where notesid = ?"; +$result=$adb->pquery($dbQuery,array($focus->id)); +$filename=$adb->query_result($result,0,'filename'); +if(is_null($filename) || $filename == '') +{ + $smarty->assign("FILE_EXIST","no"); +} +else +{ + $smarty->assign("FILE_NAME",$filename); + $smarty->assign("FILE_EXIST","yes"); +} + +//setting default flag value so due date and time not required +if (!isset($focus->id)) $focus->date_due_flag = 'on'; + +//needed when creating a new case with default values passed in +if (isset($_REQUEST['contact_name']) && is_null($focus->contact_name)) { + $focus->contact_name = $_REQUEST['contact_name']; +} +if (isset($_REQUEST['contact_id']) /* && is_null($focus->contact_id) */ ) { + $focus->contact_id = $_REQUEST['contact_id']; +} +if (isset($_REQUEST['parent_name']) && is_null($focus->parent_name)) { + $focus->parent_name = $_REQUEST['parent_name']; +} +if (isset($_REQUEST['parent_id']) /* && is_null($focus->parent_id) */ ) { + $focus->parent_id = $_REQUEST['parent_id']; +} +if (isset($_REQUEST['parent_type'])) { + $focus->parent_type = $_REQUEST['parent_type']; +} +elseif (!isset($focus->parent_type)) { + $focus->parent_type = $app_list_strings['record_type_default_key']; +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $smarty->assign("BASBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS')); +} +$smarty->assign("OP_MODE",$disp_view); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + + +$log->info("Document detail view"); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Document'); +//Display the FCKEditor or not? -- configure $FCKEDITOR_DISPLAY in config.php +if(getFieldVisibilityPermission('Documents',$current_user->id,'notecontent') != '0') + $FCKEDITOR_DISPLAY = false; +$smarty->assign("FCKEDITOR_DISPLAY",$FCKEDITOR_DISPLAY); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); + +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} +else +{ + $smarty->assign("MODE",'create'); +} + +if (isset($_REQUEST['return_module'])) +$smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else +$smarty->assign("RETURN_MODULE","Documents"); +if (isset($_REQUEST['return_action'])) +$smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else +$smarty->assign("RETURN_ACTION","index"); +if (isset($_REQUEST['return_id'])) +$smarty->assign("RETURN_ID", vtlib_purify($_REQUEST['return_id'])); +if (isset($_REQUEST['email_id'])) +$smarty->assign("EMAILID", vtlib_purify($_REQUEST['email_id'])); +if (isset($_REQUEST['ticket_id'])) $smarty->assign("TICKETID", vtlib_purify($_REQUEST['ticket_id'])); +if (isset($_REQUEST['fileid'])) +$smarty->assign("FILEID", vtlib_purify($_REQUEST['fileid'])); +if (isset($_REQUEST['record'])) +{ + $smarty->assign("CANCELACTION", "DetailView"); +} +else +{ + $smarty->assign("CANCELACTION", "index"); +} +if (isset($_REQUEST['return_viewname'])) +$smarty->assign("RETURN_VIEWNAME", vtlib_purify($_REQUEST['return_viewname'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); +$smarty->assign("OLD_ID", $old_id ); + +if ( empty($focus->filename)) +{ + $smarty->assign("FILENAME_TEXT", ""); + $smarty->assign("FILENAME", ""); +} +else +{ + $smarty->assign("FILENAME_TEXT", "(".$focus->filename.")"); + $smarty->assign("FILENAME", $focus->filename); +} + +if (isset($focus->parent_type) && $focus->parent_type != "") { + $change_parent_button = ""; + $smarty->assign("CHANGE_PARENT_BUTTON", $change_parent_button); +} +if ($focus->parent_type == "Account") $smarty->assign("DEFAULT_SEARCH", "&query=true&account_id=$focus->parent_id&account_name=".urlencode($focus->parent_name)); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); + +$tabid = getTabid("Documents"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 '
'. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +if($focus->mode == 'edit') + $smarty->display("salesEditView.tpl"); +else + $smarty->display("CreateView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/EmailFile.php b/oss/vtiger/trunk/modules/Documents/EmailFile.php new file mode 100644 index 00000000..a56952be --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/EmailFile.php @@ -0,0 +1,38 @@ +pquery($dbQuery,array($notesid)); +$folderid = $adb->query_result($result,0,'folderid'); +$filename = $adb->query_result($result,0,'filename'); + +$fileidQuery = "select attachmentsid from vtiger_seattachmentsrel where crmid = ?"; +$fileidRes = $adb->pquery($fileidQuery,array($notesid)); +$fileid = $adb->query_result($fileidRes,0,'attachmentsid'); + +$pathQuery = $adb->pquery("select path from vtiger_attachments where attachmentsid = ?",array($fileid)); +$filepath = $adb->query_result($pathQuery,0,'path'); + +$fileinattachments = $root_directory.$filepath.$fileid.'_'.$filename; +if(!file($fileinattachments))$fileinattachments = $root_directory.$filepath.$fileid."_".$filename; + +$newfileinstorage = $root_directory."/storage/$fileid-".$filename; + +copy($fileinattachments,$newfileinstorage); + +echo ""; +exit(); +?> diff --git a/oss/vtiger/trunk/modules/Documents/ExportRecords.php b/oss/vtiger/trunk/modules/Documents/ExportRecords.php new file mode 100644 index 00000000..bc9a872a --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/ExportRecords.php @@ -0,0 +1,14 @@ + + diff --git a/oss/vtiger/trunk/modules/Documents/ListView.php b/oss/vtiger/trunk/modules/Documents/ListView.php new file mode 100644 index 00000000..82c6a708 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/ListView.php @@ -0,0 +1,311 @@ +sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +//<<<>>>>>> +$oCustomView = new CustomView("Documents"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); +//<<<<>>>> +if (!isset($where)) $where = ""; +$url_string = ''; // assigning http url string + +$focus = new Documents(); +// Initialize sort by fields +$focus->initSortbyField('Documents'); +// END +$smarty = new vtigerCRM_Smarty; +$other_text = Array(); + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['NOTES_ORDER_BY'] = $order_by; +$_SESSION['NOTES_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + + +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); + +} +if(isPermitted('Documents','Delete','') == 'yes') +{ + $smarty->assign("MASS_DELETE","yes"); + $other_text['del'] = $app_strings['LBL_MASS_DELETE']; +} + +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Document'); +$smarty->assign("BUTTONS",$other_text); +$smarty->assign("CATEGORY",$category); + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != 0) +{ + $listquery = getListQuery("Documents"); + $query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Documents"); +}else +{ + $query = getListQuery("Documents"); +} +//<<<<<<<>>>>>>>> + +$hide_empty_folders = 'no'; + +if(isset($where) && $where != '') +{ + $query .= ' and '.$where; + $_SESSION['export_where'] = $where; +} +else + unset($_SESSION['export_where']); + +$focus->query = $query; + +if($viewid ==0) +{ + echo "
"; + echo "
+ + + + + + + + + +
$app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} + +//Retreive the List View Table Header +if($viewid !='') +$url_string .="&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"Documents",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); +$listview_header_search = getSearchListHeaderValues($focus,"Documents",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER",$listview_header_search); + +$smarty->assign("SELECT_SCRIPT", $view_script); + +$start = Array(); +$request_folderid = ''; + +if($_REQUEST['action'] == 'DocumentsAjax' && isset($_REQUEST['folderid'])) +{ + $request_folderid = vtlib_purify($_REQUEST['folderid']); + $start[$request_folderid] = vtlib_purify($_REQUEST['start']); +} +$focus->del_create_def_folder($focus->query); + +$dbQuery = "select * from vtiger_attachmentsfolder"; +$result = $adb->pquery($dbQuery,array()); +$foldercount = $adb->num_rows($result); +$folders = Array(); +$emptyfolders = Array(); +if($foldercount > 0 ) +{ + for($i=0;$i<$foldercount;$i++) + { + $query = ''; + $displayFolder=''; + $query = $focus->query; + $list_query = ''; + $list_query = $focus->query; + $folder_id = $adb->query_result($result,$i,"folderid"); + $query .= " and vtiger_notes.folderid = $folder_id"; + if($folder_id != $request_folderid) + { + $start[$folder_id] = 1; + } + + + if(isset($order_by) && $order_by != '') + { + $tablename = getTableNameForField('Documents',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + + if( $adb->dbType == "pgsql") + { + $query .= ' GROUP BY '.$tablename.$order_by; + $list_query .= ' GROUP BY '.$tablename.$order_by; + $focus->additional_query .= ' GROUP BY '.$tablename.$order_by; + } + + $query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + $list_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + $focus->additional_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } + //Retreiving the no of rows + $count_result = $adb->query( mkCountQuery( $query)); + $num_records = $adb->query_result($count_result,0,"count"); + if($num_records > 0){ + $displayFolder=true; + } + //navigation start + $max_entries_per_page = $list_max_entries_per_page; + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $list_query = fixPostgresQuery( $query, $log, 0); + + if($folder_id == $request_folderid){ + $start[$folder_id] = 1; + if(!empty($_REQUEST['start'])){ + $start[$folder_id] = ListViewSession::getRequestStartPage(); + if($start[$folder_id] == 'last'){ + if($num_records > 0){ + $start[$folder_id] = ceil($num_records/$max_entries_per_page); + } + } + if(!is_numeric($start[$folder_id])){ + $start[$folder_id] = 1; + } + } + } + + $navigation_array = VT_getSimpleNavigationValues($start[$folder_id],$max_entries_per_page,$num_records); + if($folder_id == $request_folderid){ + if(!is_array($_SESSION['lvs'][$currentModule]['start'])){ + $_SESSION['lvs'][$currentModule]['start'] = array(); + } + $_SESSION['lvs'][$currentModule]['start'][$folder_id] = $start[$folder_id]; + } + $limit_start_rec = ($start[$folder_id]-1) * $max_entries_per_page; + + if( $adb->dbType == "pgsql") + $list_result = $adb->pquery($query. " OFFSET $limit_start_rec LIMIT $max_entries_per_page", array()); + else + $list_result = $adb->pquery($query. " LIMIT $limit_start_rec, $max_entries_per_page", array()); + //navigation end + + $folder_details=Array(); + $folderid = $adb->query_result($result,$i,"folderid"); + $folder_details['folderid']=$folderid; + $folder_details['foldername']=$adb->query_result($result,$i,"foldername"); + $foldername = $folder_details['foldername']; + $folder_details['description']=$adb->query_result($result,$i,"description"); + $folder_files = getListViewEntries($focus,"Documents",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); + $folder_details['entries']= $folder_files; + $folder_details['navigation'] = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Documents",$folder_id,$viewid); + $folder_details['recordListRange'] = getRecordRangeMessage($list_result, $limit_start_rec); + if ($displayFolder == true) { + $folders[$foldername] = $folder_details; + } else{ + $emptyfolders[$foldername] = $folder_details; + } + if ($folderid == 1) $default_folder_details = $folder_details; + } + if (count($folders) == 0) $folders[$default_folder_details['foldername']] = $default_folder_details; +} +else +{ + $smarty->assign("NO_FOLDERS","yes"); +} + +$smarty->assign("NO_OF_FOLDERS",$foldercount); +$smarty->assign("FOLDERS", $folders); +$smarty->assign("EMPTY_FOLDERS", $emptyfolders); +$smarty->assign("ALL_FOLDERS", array_merge($folders, $emptyfolders)); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); + +$alphabetical = AlphabeticalSearch($currentModule,'index','notes_title','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("RECORD_COUNTS", $record_string); +if($current_user->id == 1) + $smarty->assign("IS_ADMIN","on"); +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '' || $_REQUEST['mode'] == 'ajax') + $smarty->display("DocumentsListViewEntries.tpl"); +else + $smarty->display("DocumentsListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/ListViewPagging.php b/oss/vtiger/trunk/modules/Documents/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/MoveFile.php b/oss/vtiger/trunk/modules/Documents/MoveFile.php new file mode 100644 index 00000000..a3cc7838 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/MoveFile.php @@ -0,0 +1,46 @@ +is_admin != 'on') +{ + echo 'NOT_PERMITTED'; + die; +} +else +{ + $new_folderid = $_REQUEST['folderid']; + + if(isset($_REQUEST['idlist']) && $_REQUEST['idlist']!= '') + { + $id_array = Array(); + $id_array = explode(';',$_REQUEST['idlist']); + for($i = 0;$i < count($id_array)-1;$i++) + { + ChangeFolder($id_array[$i],$new_folderid); + } + header("Location: index.php?action=DocumentsAjax&file=ListView&mode=ajax&module=Documents"); + } +} + +/** To Change the Documents to another folder + * @param $recordid -- The file id + * @param $new_folderid -- The folderid to which the file to be moved + * @returns nothing + */ +function ChangeFolder($recordid,$new_folderid) +{ + global $adb; + $sql="update vtiger_notes set folderid=".$new_folderid." where notesid in (".$recordid.")"; + $res=$adb->pquery($sql,array()); +} +?> diff --git a/oss/vtiger/trunk/modules/Documents/Popup.php b/oss/vtiger/trunk/modules/Documents/Popup.php new file mode 100644 index 00000000..98ea8ece --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/Popup.php @@ -0,0 +1,23 @@ + diff --git a/oss/vtiger/trunk/modules/Documents/QuickCreate.php b/oss/vtiger/trunk/modules/Documents/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Documents/Save.php b/oss/vtiger/trunk/modules/Documents/Save.php new file mode 100644 index 00000000..3f81c581 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/Save.php @@ -0,0 +1,64 @@ +date_due_flag = 'off'; + +if(isset($_REQUEST['parentid']) && $_REQUEST['parentid'] != '') + $focus->parentid = $_REQUEST['parentid']; +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']; +} +//Save the Document + +$focus->save($currentModule); + +$return_id = $focus->id; +$note_id = $return_id; + +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Documents"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + + +$local_log->debug("Saved record with id of ".$return_id); + +//Redirect to EditView if the given file is not valid. +if($file_upload_error) +{ + $return_module = 'Documents'; + $return_action = 'EditView'; + $return_id = $note_id.'&upload_error=true&return_module='.$return_module.'&return_action='.$return_action.'&return_id='.$return_id; +} + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); +header("Location: index.php?action=$return_action&module=$return_module&parenttab=$parenttab&record=$return_id&viewname=$return_viewname&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/SaveFile.php b/oss/vtiger/trunk/modules/Documents/SaveFile.php new file mode 100644 index 00000000..ae22aa84 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/SaveFile.php @@ -0,0 +1,74 @@ +query_result($adb->pquery($sql,array($file_id)),0,'filedownloadcount') + 1; + $sql="update vtiger_notes set filedownloadcount= ? where notesid= ?"; + $res=$adb->pquery($sql,array($download_count,$file_id)); +} + +if(isset($_REQUEST['act']) && $_REQUEST['act'] == 'checkFileIntegrityDetailView') +{ + global $adb,$root_directory; + $dbQuery = "SELECT * FROM vtiger_notes where notesid= ?"; + $fileidQuery = "select attachmentsid from vtiger_seattachmentsrel where crmid = ? "; + $result = $adb->pquery($dbQuery,array($_REQUEST['noteid'])); + $fileidResult = $adb->pquery($fileidQuery,array($_REQUEST['noteid'])); + //$activeToinactive_count = 0; + + $file_status = $adb->query_result($result,0,"filestatus"); + $download_type = $adb->query_result($result,0,"filelocationtype"); + $notesid = $adb->query_result($result,0,'notesid'); + $fileid = $adb->query_result($fileidResult,0,"attachmentsid"); + $folderid = $adb->query_result($result,0,"folderid"); + $name = $adb->query_result($result,0,"filename"); + + if($download_type == 'I'){ + $saved_filename = $fileid."_".$name; + $pathQuery = $adb->pquery("select path from vtiger_attachments where attachmentsid = ?",array($fileid)); + $filepath = $adb->query_result($pathQuery,0,'path'); + + } + elseif($download_type == 'E'){ + $saved_filename = $name; + } + else + $saved_filename = ''; + + + if(!fopen($filepath.$saved_filename, "r")) + { + if($file_status == 1) + { + $dbQuery1 = "update vtiger_notes set filestatus = 0 where notesid= ?"; + $result1 = $adb->pquery($dbQuery1,array($notesid)); + echo "lost_integrity"; + } + else + echo "file_not_available"; + }else { + echo "file_available"; + } + +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/SaveFolder.php b/oss/vtiger/trunk/modules/Documents/SaveFolder.php new file mode 100644 index 00000000..916b2ba4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/SaveFolder.php @@ -0,0 +1,84 @@ +query_result($adb->pquery($sqlfid,$params),0,'max(folderid)')+1; + $params=array(); + $sqlseq="select max(sequence) from vtiger_attachmentsfolder"; + $sequence=$adb->query_result($adb->pquery($sqlseq,$params),0,'max(sequence)')+1; + $params=array(); + $dbQuery="select * from vtiger_attachmentsfolder"; + $result1=$adb->pquery($dbQuery,array()); + $flag=0; + for($i=0;$i<$adb->num_rows($result1);$i++) + { + $dbfldrname=$adb->query_result($result1,$i,'foldername'); + if($dbfldrname == $foldername) + $flag = 1; + } + if($flag == 0) + { + $sql="insert into vtiger_attachmentsfolder (folderid,foldername,description,createdby,sequence)values ($fid,'".$foldername."','".$folderdesc."',".$current_user->id.",$sequence)"; + $result=$adb->pquery($sql,$params); + if(!$result) + { + echo "Failure"; + } + else + header("Location: index.php?action=DocumentsAjax&file=ListView&mode=ajax&module=Documents"); + } + elseif($flag == 1) + echo "DUPLICATE_FOLDERNAME"; + } + elseif($folderid != "") + { + $dbQuery="select * from vtiger_attachmentsfolder"; + $result1=$adb->pquery($dbQuery,array()); + $flag=0; + for($i=0;$i<$adb->num_rows($result1);$i++) + { + $dbfldrname=$adb->query_result($result1,$i,'foldername'); + if($dbfldrname == $foldername) + $flag = 1; + } + if($flag == 0) + { + $sql="update vtiger_attachmentsfolder set foldername= ? where folderid= ? "; + $result=$adb->pquery($sql,array($foldername,$folderid)); + if(!$result) + { + echo "Failure"; + } + else + echo 'Success'; + } + elseif($flag == 1) + echo "DUPLICATE_FOLDERNAME"; + } + } + +?> diff --git a/oss/vtiger/trunk/modules/Documents/Settings.php b/oss/vtiger/trunk/modules/Documents/Settings.php new file mode 100644 index 00000000..48a80c0b --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/Settings.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/TagCloud.php b/oss/vtiger/trunk/modules/Documents/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Documents/UnifiedSearch.php b/oss/vtiger/trunk/modules/Documents/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Documents/index.php b/oss/vtiger/trunk/modules/Documents/index.php new file mode 100644 index 00000000..3ff42ab5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/index.php @@ -0,0 +1,26 @@ + diff --git a/oss/vtiger/trunk/modules/Documents/language/en_us.lang.php b/oss/vtiger/trunk/modules/Documents/language/en_us.lang.php new file mode 100644 index 00000000..be697932 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/language/en_us.lang.php @@ -0,0 +1,138 @@ +'Documents', +'LBL_MODULE_TITLE'=>'Documents: Home', +'LBL_SEARCH_FORM_TITLE'=>'Document Search', +'LBL_LIST_FORM_TITLE'=>'Document List', +'LBL_NEW_FORM_TITLE'=>'New Document', + +'LBL_LIST_SUBJECT'=>'Subject', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', +'LBL_LIST_RELATED_TO'=>'Related To', +'LBL_LIST_DATE_MODIFIED'=>'Last Modified', + +'LBL_NOTE'=>'Document:', +'LBL_NOTE_SUBJECT'=>'Document Subject:', +'LBL_CONTACT_NAME'=>'Contact Name:', +'LBL_PHONE'=>'Phone:', +'LBL_SUBJECT'=>'Subject:', +'LBL_CLOSE'=>'Close:', +'LBL_RELATED_TO'=>'Related To:', +'LBL_EMAIL_ADDRESS'=>'Email Address:', +'LBL_COLON'=>':', + +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", +'LBL_LIST_FILENAME'=>"File Name", + +// Added for Note(3.2-patch 3) + +'LBL_FILENAME'=>'Attachment:', +'LBL_NOTE_INFORMATION'=>'Basic Information', +'File Information'=>'File Information', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Documents Tools', +// Added for 4GA +'Contact Name'=>'Contact Name', +'Related To'=>'Related to', +'Subject'=>'Subject', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Document'=>'Document', +'Note'=>'Notes', +//Added for 4.2 Release -- CustomView +'Related to'=>'Related to', +'Last Modified'=>'Last Modified', +'File'=>'File', +'LBL_ALL'=>'All', +'Title'=>'Title', + +//Added after 504 for Downloads Module +'LBL_FILE_INFORMATION'=>'File Information', +'LBL_FILE_NAME'=>'File Name', +'LBL_FILE_TYPE'=>'File Type', +'LBL_FILE_SIZE'=>'Size', +'filelocationtype'=>'Download Type', +'fileversion'=>'Version', +'filestatus'=>'Active', +'filedownloadcount'=>'Download Count', +'os'=>'Platform', +'LBL_FOLDER_NAME'=>'Folder Name', +'LBL_DOWNLOAD_TYPE'=>'Download Type', +'LBL_INTERNAL'=>'Internal', +'LBL_EXTERNAL'=>'External', +'LBL_EXTERNAL_FILE_NAME'=>'File Name', +'LBL_FILE_LOCATION'=>'File Location', +'LBL_PD'=>'Platform Dependent', +'LBL_PIND'=>'Platform Independent', +'ChoosePlatform'=>'Choose Platform', +'LBL_ACTIVE'=>'Active', +'LBL_INACTIVE'=>'Inactive', +'LBL_UPLOAD_BUTTON'=>'Upload', +'architecture'=>'Architecture', +'LBL_DOWNLOAD_FILE'=>'Download file', +'LBL_CHECK_INTEGRITY'=>'Check file integrity', +'LBL_EMAIL_FILE'=>'Email file as attachment', +'LBL_CLICK_HERE'=>'Click here', +'LBL_TO_ADD_FOLDER'=>'to add a new folder.', +'LBL_DELETE_FOLDER'=>'Delete Folder', +'LBL_FOLDER_DESC'=>'Description', +'LBL_ADD_NEW_FOLDER'=>'Add Folder', +'LBL_DELETE_DOCUMENTS'=>'Delete Document(s)', +'LBL_MOVE_TO'=>'Move to', +'File Name'=>'File Name', +'File Type'=>'File Type', +'File Size'=>'Size', +'LBL_INTERNAL'=>'Internal', +'LBL_URL'=>'URL', +'LBL_EXTERNAL'=>'External', +'LBL_EXTERNAL_LNK'=>'External Link', +'LBL_ACTIVE'=>'Active', +'LBL_INACTIVE'=>'Inactive', +'LBL_PLATFORM_INDEPENDENT'=>'Platform Independent', +'LNK_DOWNLOAD'=>'download', +'LBL_MOVE_DOCUMENTS'=>'Move Document(s)', +'LBL_MOVE'=>'Move', +'Download Type'=>'Download Type', +'Version'=>'Version', +'Active'=>'Active', +'Download Count'=>'Download Count', +'Platform'=>'Platform', +'Assigned To'=>'Assigned To', +// Module Sequence Numbering +'Note No' => 'Document No', +// END + +// Documents module +'LBL_EMPTY_FOLDERS' => 'Empty Folders', +'LBL_VIEW_EMPTY_FOLDERS' => 'View Empty Folders', +'LBL_NO_DOCUMENTS' => 'No Documents', +'LBL_DESCRIPTION' => 'Description', +'FILE_HAS_NO_DATA'=>'The selected file has no data or a invalid file', + +'LBL_MAXIMUM_20'=>'Maximum 20', +'LBL_MAXIMUM_50'=>'Maximum 50', +); + +?> diff --git a/oss/vtiger/trunk/modules/Documents/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Documents/language/zh_cn.lang.php new file mode 100644 index 00000000..be697932 --- /dev/null +++ b/oss/vtiger/trunk/modules/Documents/language/zh_cn.lang.php @@ -0,0 +1,138 @@ +'Documents', +'LBL_MODULE_TITLE'=>'Documents: Home', +'LBL_SEARCH_FORM_TITLE'=>'Document Search', +'LBL_LIST_FORM_TITLE'=>'Document List', +'LBL_NEW_FORM_TITLE'=>'New Document', + +'LBL_LIST_SUBJECT'=>'Subject', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', +'LBL_LIST_RELATED_TO'=>'Related To', +'LBL_LIST_DATE_MODIFIED'=>'Last Modified', + +'LBL_NOTE'=>'Document:', +'LBL_NOTE_SUBJECT'=>'Document Subject:', +'LBL_CONTACT_NAME'=>'Contact Name:', +'LBL_PHONE'=>'Phone:', +'LBL_SUBJECT'=>'Subject:', +'LBL_CLOSE'=>'Close:', +'LBL_RELATED_TO'=>'Related To:', +'LBL_EMAIL_ADDRESS'=>'Email Address:', +'LBL_COLON'=>':', + +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", +'LBL_LIST_FILENAME'=>"File Name", + +// Added for Note(3.2-patch 3) + +'LBL_FILENAME'=>'Attachment:', +'LBL_NOTE_INFORMATION'=>'Basic Information', +'File Information'=>'File Information', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Documents Tools', +// Added for 4GA +'Contact Name'=>'Contact Name', +'Related To'=>'Related to', +'Subject'=>'Subject', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Document'=>'Document', +'Note'=>'Notes', +//Added for 4.2 Release -- CustomView +'Related to'=>'Related to', +'Last Modified'=>'Last Modified', +'File'=>'File', +'LBL_ALL'=>'All', +'Title'=>'Title', + +//Added after 504 for Downloads Module +'LBL_FILE_INFORMATION'=>'File Information', +'LBL_FILE_NAME'=>'File Name', +'LBL_FILE_TYPE'=>'File Type', +'LBL_FILE_SIZE'=>'Size', +'filelocationtype'=>'Download Type', +'fileversion'=>'Version', +'filestatus'=>'Active', +'filedownloadcount'=>'Download Count', +'os'=>'Platform', +'LBL_FOLDER_NAME'=>'Folder Name', +'LBL_DOWNLOAD_TYPE'=>'Download Type', +'LBL_INTERNAL'=>'Internal', +'LBL_EXTERNAL'=>'External', +'LBL_EXTERNAL_FILE_NAME'=>'File Name', +'LBL_FILE_LOCATION'=>'File Location', +'LBL_PD'=>'Platform Dependent', +'LBL_PIND'=>'Platform Independent', +'ChoosePlatform'=>'Choose Platform', +'LBL_ACTIVE'=>'Active', +'LBL_INACTIVE'=>'Inactive', +'LBL_UPLOAD_BUTTON'=>'Upload', +'architecture'=>'Architecture', +'LBL_DOWNLOAD_FILE'=>'Download file', +'LBL_CHECK_INTEGRITY'=>'Check file integrity', +'LBL_EMAIL_FILE'=>'Email file as attachment', +'LBL_CLICK_HERE'=>'Click here', +'LBL_TO_ADD_FOLDER'=>'to add a new folder.', +'LBL_DELETE_FOLDER'=>'Delete Folder', +'LBL_FOLDER_DESC'=>'Description', +'LBL_ADD_NEW_FOLDER'=>'Add Folder', +'LBL_DELETE_DOCUMENTS'=>'Delete Document(s)', +'LBL_MOVE_TO'=>'Move to', +'File Name'=>'File Name', +'File Type'=>'File Type', +'File Size'=>'Size', +'LBL_INTERNAL'=>'Internal', +'LBL_URL'=>'URL', +'LBL_EXTERNAL'=>'External', +'LBL_EXTERNAL_LNK'=>'External Link', +'LBL_ACTIVE'=>'Active', +'LBL_INACTIVE'=>'Inactive', +'LBL_PLATFORM_INDEPENDENT'=>'Platform Independent', +'LNK_DOWNLOAD'=>'download', +'LBL_MOVE_DOCUMENTS'=>'Move Document(s)', +'LBL_MOVE'=>'Move', +'Download Type'=>'Download Type', +'Version'=>'Version', +'Active'=>'Active', +'Download Count'=>'Download Count', +'Platform'=>'Platform', +'Assigned To'=>'Assigned To', +// Module Sequence Numbering +'Note No' => 'Document No', +// END + +// Documents module +'LBL_EMPTY_FOLDERS' => 'Empty Folders', +'LBL_VIEW_EMPTY_FOLDERS' => 'View Empty Folders', +'LBL_NO_DOCUMENTS' => 'No Documents', +'LBL_DESCRIPTION' => 'Description', +'FILE_HAS_NO_DATA'=>'The selected file has no data or a invalid file', + +'LBL_MAXIMUM_20'=>'Maximum 20', +'LBL_MAXIMUM_50'=>'Maximum 50', +); + +?> diff --git a/oss/vtiger/trunk/modules/Emails/CallRelatedList.php b/oss/vtiger/trunk/modules/Emails/CallRelatedList.php new file mode 100644 index 00000000..dfe47baa --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/CallRelatedList.php @@ -0,0 +1,56 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['subject']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); +} + +global $mod_strings; +global $app_strings; +global $currentModule; +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +$related_array=getRelatedLists($currentModule,$focus); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); +if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); +} +$smarty->assign("id",$focus->id); +$smarty->assign("RELATEDLISTS", $related_array); +$smarty->assign("ID",$RECORD ); +$smarty->assign("MODULE",$currentmodule); +$smarty->assign("SINGLE_MOD",$app_strings['Email']); +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +$smarty->assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$smarty->display("RelatedLists.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/Choose.php b/oss/vtiger/trunk/modules/Emails/Choose.php new file mode 100644 index 00000000..98605f85 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/Choose.php @@ -0,0 +1,82 @@ +pquery($querystr, array()); +$numrows = $adb->num_rows($result); + +?> +
+ +

The following emails are available for the selected record. Please choose the ones you would like to use.

+
+ + query_result($result,$i,'columnname'); + $temp1=br2nl($myfocus->column_fields[$temp]); + echo ''; + } + ?> + + + +
'.$adb->query_result($result,$i,'fieldlabel').'    '.$temp1.'
+ +
+
diff --git a/oss/vtiger/trunk/modules/Emails/ChooseEmail.php b/oss/vtiger/trunk/modules/Emails/ChooseEmail.php new file mode 100644 index 00000000..5ef825c2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/ChooseEmail.php @@ -0,0 +1,106 @@ +pquery($querystr, array()); +$numrows = $adb->num_rows($result); + +if ($pmodule=='Accounts') +{ + require_once('modules/Accounts/Accounts.php'); + $myfocus = new Accounts(); + $myfocus->retrieve_entity_info($entityid,"Accounts"); +} +elseif ($pmodule=='Contacts') +{ + require_once('modules/Contacts/Contacts.php'); + $myfocus = new Contacts(); + $myfocus->retrieve_entity_info($entityid,"Contacts"); +} +elseif ($pmodule=='Leads') +{ + require_once('modules/Leads/Leads.php'); + $myfocus = new Leads(); + $myfocus->retrieve_entity_info($entityid,"Leads"); +} +?> + + +
+

The following emails are available for the selected record. Please choose the ones you would like to use.

+
+ + query_result($result,$i,'columnname'); + $temp1=br2nl($myfocus->column_fields[$temp]); + echo ''; + } + ?> +
'.$adb->query_result($result,$i,'fieldlabel').'    '.$temp1.'
+ + +
+
diff --git a/oss/vtiger/trunk/modules/Emails/CustomView.php b/oss/vtiger/trunk/modules/Emails/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Emails/Delete.php b/oss/vtiger/trunk/modules/Emails/Delete.php new file mode 100644 index 00000000..b8e17de0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/Delete.php @@ -0,0 +1,36 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/DetailView.php b/oss/vtiger/trunk/modules/Emails/DetailView.php new file mode 100644 index 00000000..f159ffd5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/DetailView.php @@ -0,0 +1,159 @@ +retrieve_entity_info($_REQUEST['record'],"Emails"); + $log->info("Entity info successfully retrieved for DetailView."); + $focus->id = $_REQUEST['record']; + $query = 'select email_flag,from_email,to_email,cc_email,bcc_email from vtiger_emaildetails where emailid = ?'; + $result = $adb->pquery($query, array($focus->id)); + $smarty->assign('FROM_MAIL',$adb->query_result($result,0,'from_email')); + $to_email = $json->decode($adb->query_result($result,0,'to_email')); + $cc_email = $json->decode($adb->query_result($result,0,'cc_email')); + $smarty->assign('TO_MAIL',vt_suppressHTMLTags(@implode(',',$to_email))); + $smarty->assign('CC_MAIL',vt_suppressHTMLTags(@implode(',',$cc_email))); + $bcc_email = $json->decode($adb->query_result($result,0,'bcc_email')); + $smarty->assign('BCC_MAIL',vt_suppressHTMLTags(@implode(',',$bcc_email))); + $smarty->assign('EMAIL_FLAG',$adb->query_result($result,0,'email_flag')); + if($focus->column_fields['name'] != '') + $focus->name = $focus->column_fields['name']; + else + $focus->name = $focus->column_fields['subject']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; +} + +//needed when creating a new email with default values passed in +if (isset($_REQUEST['contact_name']) && is_null($focus->contact_name)) +{ + $focus->contact_name = $_REQUEST['contact_name']; +} +if (isset($_REQUEST['contact_id']) && is_null($focus->contact_id)) +{ + $focus->contact_id = $_REQUEST['contact_id']; +} +if (isset($_REQUEST['opportunity_name']) && is_null($focus->parent_name)) +{ + $focus->parent_name = $_REQUEST['opportunity_name']; +} +if (isset($_REQUEST['opportunity_id']) && is_null($focus->parent_id)) +{ + $focus->parent_id = $_REQUEST['opportunity_id']; +} +if (isset($_REQUEST['account_name']) && is_null($focus->parent_name)) +{ + $focus->parent_name = $_REQUEST['account_name']; +} +if (isset($_REQUEST['account_id']) && is_null($focus->parent_id)) +{ + $focus->parent_id = $_REQUEST['account_id']; +} +if (isset($_REQUEST['parent_name'])) +{ + $focus->parent_name = $_REQUEST['parent_name']; +} +if (isset($_REQUEST['parent_id'])) +{ + $focus->parent_id = $_REQUEST['parent_id']; +} +if (isset($_REQUEST['parent_type'])) +{ + $focus->parent_type = $_REQUEST['parent_type']; +} +if (isset($_REQUEST['filename']) && is_null($focus->filename)) +{ + $focus->filename = $_REQUEST['filename']; +} +elseif (is_null($focus->parent_type)) +{ + $focus->parent_type = $app_list_strings['record_type_default_key']; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Email detail view"); + +$submenu = array('LBL_EMAILS_TITLE'=>'index.php?module=Emails&action=index','LBL_WEBMAILS_TITLE'=>'index.php?module=squirrelmail-1.4.4&action=redirect'); +$sec_arr = array('index.php?module=Emails&action=index'=>'Emails','index.php?module=squirrelmail-1.4.4&action=redirect'=>'Emails'); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + else $smarty->assign("NAME", ""); + +$entries = getBlocks($currentModule,"detail_view",'',$focus->column_fields); +$entries[$mod_strings['LBL_EMAIL_INFORMATION']]['5'][$mod_strings['Description']]['value'] = from_html($entries[$mod_strings['LBL_EMAIL_INFORMATION']]['5'][$mod_strings['Description']]['value']); +//changed this to view description in all langauge - bharath +$smarty->assign("BLOCKS",$entries[$mod_strings['LBL_EMAIL_INFORMATION']]); +$smarty->assign("SINGLE_MOD", 'Email'); + +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +if(isPermitted("Emails","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("Emails","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); +$smarty->assign("ID",$focus->id); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +//Constructing the Related Lists from here +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SENDER",$email_id); +if($_REQUEST['mode'] != 'ajax') + $smarty->display("EmailDetailView.tpl"); +else + $smarty->display("EmailDetails.tpl") +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/EditView.php b/oss/vtiger/trunk/modules/Emails/EditView.php new file mode 100644 index 00000000..58714f31 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/EditView.php @@ -0,0 +1,355 @@ + The selected file has no data or a invalid file.
'; +} + +//Email Error handling +if($_REQUEST['mail_error'] != '') +{ + require_once("modules/Emails/mail.php"); + echo parseEmailErrorString($_REQUEST['mail_error']); +} +//added to select the module in combobox of compose-popup +if(isset($_REQUEST['par_module']) && $_REQUEST['par_module']!=''){ + $smarty->assign('select_module',vtlib_purify($_REQUEST['par_module'])); +} +elseif(isset($_REQUEST['pmodule']) && $_REQUEST['pmodule']!='') { + $smarty->assign('select_module',vtlib_purify($_REQUEST['pmodule'])); +} + +if(isset($_REQUEST['record']) && $_REQUEST['record'] !='') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Emails"); + $query = 'select idlists,from_email,to_email,cc_email,bcc_email from vtiger_emaildetails where emailid =?'; + $result = $adb->pquery($query, array($focus->id)); + $from_email = $adb->query_result($result,0,'from_email'); + $smarty->assign('FROM_MAIL',$from_email); + $to_email = implode(',',$json->decode($adb->query_result($result,0,'to_email'))); + $smarty->assign('TO_MAIL',$to_email); + $cc_add = implode(',',$json->decode($adb->query_result($result,0,'cc_email'))); + $smarty->assign('CC_MAIL',$cc_add); + $bcc_add = implode(',',$json->decode($adb->query_result($result,0,'bcc_email'))); + $smarty->assign('BCC_MAIL',$bcc_add); + $idlist = $adb->query_result($result,0,'idlists'); + $smarty->assign('IDLISTS',$idlist); + $log->info("Entity info successfully retrieved for EditView."); + $focus->name=$focus->column_fields['name']; +} +elseif(isset($_REQUEST['sendmail']) && $_REQUEST['sendmail'] !='') +{ + + $mailids = get_to_emailids($_REQUEST['pmodule']); + if($mailids['mailds'] != '') + $to_add = trim($mailids['mailds'],",").","; + $smarty->assign('TO_MAIL',$to_add); + $smarty->assign('IDLISTS',$mailids['idlists']); + $focus->mode = ''; +} + +// INTERNAL MAILER +if($_REQUEST["internal_mailer"] == "true") { + $smarty->assign('INT_MAILER',"true"); + $rec_type = $_REQUEST["type"]; + $rec_id = $_REQUEST["rec_id"]; + $fieldname = $_REQUEST["fieldname"]; + + //added for getting list-ids to compose email popup from list view(Accounts,Contacts,Leads) + if(isset($_REQUEST['field_id']) && strlen($_REQUEST['field_id']) != 0) { + if($_REQUEST['par_module'] == "Users") + $id_list = $_REQUEST['rec_id'].'@'.'-1|'; + else + $id_list = $_REQUEST['rec_id'].'@'.$_REQUEST['field_id'].'|'; + $smarty->assign("IDLISTS", $id_list); + } + if($rec_type == "record_id") { + $type = $_REQUEST['par_module']; + //check added for email link in user detail view + $normal_tabs = Array('Users'=>'vtiger_users', 'Leads'=>'vtiger_leaddetails', 'Contacts'=>'vtiger_contactdetails', 'Accounts'=>'vtiger_account', 'Vendors'=>'vtiger_vendor'); + $cf_tabs = Array('Accounts'=>'vtiger_accountscf', 'Campaigns'=>'vtiger_campaignscf', 'Contacts'=>'vtiger_contactscf', 'Invoice'=>'vtiger_invoicecf', 'Leads'=>'vtiger_leadscf', 'Potentials'=>'vtiger_potentialscf', 'Products'=>'vtiger_productcf', 'PurchaseOrder'=>'vtiger_purchaseordercf', 'Quotes'=>'vtiger_quotescf', 'SalesOrder'=>'vtiger_salesordercf', 'HelpDesk'=>'vtiger_ticketcf', 'Vendors'=>'vtiger_vendorcf'); + if(substr($fieldname,0,2)=="cf") + $tablename = $cf_tabs[$type]; + else + $tablename = $normal_tabs[$type]; + if($type == "Users") + $q = "select $fieldname from $tablename where id=?"; + elseif($type == "Leads") + $q = "select $fieldname from $tablename where leadid=?"; + elseif ($type == "Contacts") + $q = "select $fieldname from $tablename where contactid=?"; + elseif ($type == "Accounts") + $q = "select $fieldname from $tablename where accountid=?"; + elseif ($type == "Vendors") + $q = "select $fieldname from $tablename where vendorid=?"; + else { + // vtlib customization: Support for email-type custom field for other modules. + $module_focus = CRMEntity::getInstance($type); + vtlib_setup_modulevars($type, $module_focus); + if(!empty($module_focus->customFieldTable)) { + $q = "select $fieldname from " . $module_focus->customFieldTable[0] . " where " . $module_focus->customFieldTable[1]. "= ?"; + } + // END + } + $email1 = $adb->query_result($adb->pquery($q, array($rec_id)),0,$fieldname); + } elseif ($rec_type == "email_addy") { + $email1 = $_REQUEST["email_addy"]; + } + + $smarty->assign('TO_MAIL',trim($email1,",").","); +} + +//handled for replying emails +if($_REQUEST['reply'] == "true") +{ + $fromadd = $_REQUEST['record']; + $query = "select from_email,idlists,cc_email,bcc_email from vtiger_emaildetails where emailid =?"; + $result = $adb->pquery($query, array($fromadd)); + $from_mail = $adb->query_result($result,0,'from_email'); + $smarty->assign('TO_MAIL',trim($from_mail,",").','); + $cc_add = implode(',',$json->decode($adb->query_result($result,0,'cc_email'))); + $smarty->assign('CC_MAIL',$cc_add); + $bcc_add = implode(',',$json->decode($adb->query_result($result,0,'bcc_email'))); + $smarty->assign('BCC_MAIL',$bcc_add); + $smarty->assign('IDLISTS',ereg_replace('###',',',$adb->query_result($result,0,'idlists'))); +} + +// Webmails +if(isset($_REQUEST["mailid"]) && $_REQUEST["mailid"] != "") { + $mailid = $_REQUEST["mailid"]; + $mailbox = $_REQUEST["mailbox"]; + require_once('include/utils/UserInfoUtil.php'); + require_once("modules/Webmails/Webmails.php"); + require_once("modules/Webmails/MailParse.php"); + require_once('modules/Webmails/MailBox.php'); + + $mailInfo = getMailServerInfo($current_user); + $temprow = $adb->fetch_array($mailInfo); + + $MailBox = new MailBox($mailbox); + $mbox = $MailBox->mbox; + + $webmail = new Webmails($mbox,$mailid); + $array_tab = Array(); + $webmail->loadMail($array_tab); + $hdr = @imap_headerinfo($mbox, $mailid); + $smarty->assign('WEBMAIL',"true"); + $smarty->assign('mailid',$mailid); + $smarty->assign('mailbox',$mailbox); + $temp_id = $MailBox->boxinfo['mail_id']; + $smarty->assign('from_add',$temp_id); + $webmail->subject = utf8_decode(utf8_encode(imap_utf8($webmail->subject))); + if($_REQUEST["reply"] == "all") { + $smarty->assign('TO_MAIL',$webmail->from.","); + //added to remove the emailid of webmail client from cc list....to fix the issue #3818 + $cc_address = ''; + + $use_to_header = htmlentities($webmail->to_header, ENT_QUOTES, $default_charset); + $use_cc_address= htmlentities($hdr->ccaddress, ENT_QUOTES, $default_charset); + + $cc_array = explode(',',$use_to_header.','.$use_cc_address); + for($i=0;$iassign('CC_MAIL',$cc_address); + // fix #3818 ends + /*if(is_array($webmail->cc_list)) + { + $smarty->assign('CC_MAIL',implode(",",$webmail->cc_list).",".implode(",",$webmail->to)); + } + else + { + //Commenting this to fix #3231 + // $smarty->assign('CC_MAIL',implode(",",$webmail->to)); + }*/ + if(preg_match("/RE:/i", $webmail->subject)) + $smarty->assign('SUBJECT',$webmail->subject); + else + $smarty->assign('SUBJECT',"RE: ".$webmail->subject); + + } elseif($_REQUEST["reply"] == "single"){ + $smarty->assign('TO_MAIL',$webmail->reply_to[0].","); + //$smarty->assign('BCC_MAIL',$webmail->to[0]); + if(preg_match("/RE:/i", $webmail->subject)) + $smarty->assign('SUBJECT',$webmail->subject); + else + $smarty->assign('SUBJECT',"RE: ".$webmail->subject); + + } elseif($_REQUEST["forward"] == "true" ) { + //added for attachment handling + $attachment_links = Array(); + for($i=0;$iattname);$i++){ + $attachment_links[$i] = $webmail->anchor_arr[$i].decode_header($webmail->attname[$i])."
"; + } + $smarty->assign('webmail_attachments',$attachment_links); + if(preg_match("/FW:/i", $webmail->subject)) + $smarty->assign('SUBJECT',$webmail->subject); + else + $smarty->assign('SUBJECT',"FW: ".$webmail->subject); + } + $smarty->assign('DESCRIPTION',$webmail->replyBody()); + $focus->mode=''; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +$details = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields); +//changed this below line to view description in all language - bharath +$smarty->assign("BLOCKS",$details[$mod_strings['LBL_EMAIL_INFORMATION']]); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",$app_strings['Email']); +//id list of attachments while forwarding +$smarty->assign("ATT_ID_LIST",$att_id_list); + +//needed when creating a new email with default values passed in +if (isset($_REQUEST['contact_name']) && is_null($focus->contact_name)) +{ + $focus->contact_name = $_REQUEST['contact_name']; +} +if (isset($_REQUEST['contact_id']) && is_null($focus->contact_id)) +{ + $focus->contact_id = $_REQUEST['contact_id']; +} +if (isset($_REQUEST['parent_name']) && is_null($focus->parent_name)) +{ + $focus->parent_name = $_REQUEST['parent_name']; +} +if (isset($_REQUEST['parent_id']) && is_null($focus->parent_id)) +{ + $focus->parent_id = $_REQUEST['parent_id']; +} +if (isset($_REQUEST['parent_type'])) +{ + $focus->parent_type = $_REQUEST['parent_type']; +} +if (isset($_REQUEST['filename']) && $_REQUEST['isDuplicate'] != 'true') +{ + $focus->filename = $_REQUEST['filename']; +} +elseif (is_null($focus->parent_type)) +{ + $focus->parent_type = $app_list_strings['record_type_default_key']; +} + +$log->info("Email detail view"); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); + + +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} + +// Unimplemented until jscalendar language vtiger_files are fixed + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +if(isset($_REQUEST['return_module'])) $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else $smarty->assign("RETURN_MODULE",'Emails'); +if(isset($_REQUEST['return_action'])) $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else $smarty->assign("RETURN_ACTION",'index'); +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'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); +$smarty->assign("ENTITY_ID", vtlib_purify($_REQUEST["record"])); +$smarty->assign("ENTITY_TYPE",vtlib_purify($_REQUEST["email_directing_module"])); +$smarty->assign("OLD_ID", $old_id ); +//Display the FCKEditor or not? -- configure $FCKEDITOR_DISPLAY in config.php +$smarty->assign("FCKEDITOR_DISPLAY",$FCKEDITOR_DISPLAY); + +if(empty($focus->filename)) +{ + $smarty->assign("FILENAME_TEXT", ""); + $smarty->assign("FILENAME", ""); +} +else +{ + $smarty->assign("FILENAME_TEXT", "(".$focus->filename.")"); + $smarty->assign("FILENAME", $focus->filename); +} +if($ret_error == 1) { + require_once('modules/Webmails/MailBox.php'); + $smarty->assign("RET_ERROR",$ret_error); + if($ret_parentid != ''){ + $smarty->assign("IDLISTS",$ret_parentid); + } + if($ret_toadd != '') + $smarty->assign("TO_MAIL",$ret_toadd); + $ret_toadd = ''; + if($ret_subject != '') + $smarty->assign("SUBJECT",$ret_subject); + if($ret_ccaddress != '') + $smarty->assign("CC_MAIL",$ret_ccaddress); + if($ret_bccaddress != '') + $smarty->assign("BCC_MAIL",$ret_bccaddress); + if($ret_description != '') + $smarty->assign("DESCRIPTION", $ret_description); + $temp_obj = new MailBox($mailbox); + $temp_id = $temp_obj->boxinfo['mail_id']; + if($temp_id != '') + $smarty->assign('from_add',$temp_id); +} +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$smarty->display("ComposeEmail.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/Emails.js b/oss/vtiger/trunk/modules/Emails/Emails.js new file mode 100644 index 00000000..3401a48e --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/Emails.js @@ -0,0 +1,196 @@ +/********************************************************************************* + +** 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. + ********************************************************************************/ + +var gFolderid = 1; +var gselectedrowid = 0; +function gotoWebmail() +{ + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Webmails&action=WebmailsAjax&config_chk=true", + onComplete: function(response) { + if(response.responseText.indexOf('SUCCESS') > -1) + window.location.href = "index.php?module=Webmails&action=index&parenttab=My Home Page"; + else + $('mailconfchk').style.display = 'block'; + + } + } + ); + +} + +function getEmailContents(id) +{ + $("status").style.display="inline"; + var rowid = 'row_'+id; + getObj(rowid).className = 'emailSelected'; + if(gselectedrowid != 0 && gselectedrowid != id) + { + var prev_selected_rowid = 'row_'+gselectedrowid; + getObj(prev_selected_rowid).className = 'prvPrfHoverOff'; + } + gselectedrowid = id; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=Emails&action=EmailsAjax&file=DetailView&mode=ajax&record='+id, + onComplete: function(response) { + $("status").style.display="none"; + $("EmailDetails").innerHTML = response.responseText; + } + } + ); +} + +function getListViewEntries_js(module,url) +{ + $("status").style.display="inline"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module="+module+"&action="+module+"Ajax&file=ListView&ajax=true&"+url, + onComplete: function(response) { + $("status").style.display="none"; + $("email_con").innerHTML=response.responseText; + execJS(document.getElementById('email_con')); + } + } + ); + +} + +function massDelete() +{ + var delete_selected_row = false; + //added to fix the issue 4295 + var select_options = document.getElementsByName('selected_id'); + var x = select_options.length; + + idstring = ""; + xx = 0; + for(i = 0; i < x ; i++) + { + if(select_options[i].checked) + { + idstring = select_options[i].value +";"+idstring + if(select_options[i].value == gselectedrowid) + { + gselectedrowid = 0; + delete_selected_row = true; + } + xx++ + } + } + if (xx > 0) + { + document.massdelete.idlist.value=idstring; + } + else + { + alert(alert_arr.SELECT); + return false; + } + if(confirm(alert_arr.DELETE + xx + alert_arr.RECORDS)) + { + getObj('search_text').value = ''; + show("status"); + if(!delete_selected_row) + { + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Users&action=massdelete&folderid="+gFolderid+"&return_module=Emails&idlist="+idstring, + onComplete: function(response) { + $("status").style.display="none"; + $("email_con").innerHTML=response.responseText; + execJS(document.getElementById('email_con')); + } + } + ); + } + else + { + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Users&action=massdelete&folderid="+gFolderid+"&return_module=Emails&idlist="+idstring, + onComplete: function(response) { + $("status").style.display="none"; + $("email_con").innerHTML=response.responseText; + execJS($('email_con')); + $('EmailDetails').innerHTML = '
 
'; + $("subjectsetter").innerHTML=''; + } + } + ); + } + } + else + { + return false; + } +} + +function DeleteEmail(id) +{ + if(confirm(alert_arr.SURE_TO_DELETE)) + { + getObj('search_text').value = ''; + gselectedrowid = 0; + $("status").style.display="inline"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Users&action=massdelete&return_module=Emails&folderid="+gFolderid+"&idlist="+id, + onComplete: function(response) { + $("status").style.display="none"; + $("email_con").innerHTML=response.responseText; + execJS($('email_con')); + $('EmailDetails').innerHTML = '
 
'; + $("subjectsetter").innerHTML=''; + } + } + ); + } + else + { + return false; + } +} +function Searchfn() +{ + gselectedrowid = 0; + var osearch_field = document.getElementById('search_field'); + var search_field = osearch_field.options[osearch_field.options.selectedIndex].value; + var search_text = document.getElementById('search_text').value; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: "module=Emails&action=EmailsAjax&ajax=true&file=ListView&folderid="+gFolderid+"&search=true&search_field="+search_field+"&search_text="+search_text, + onComplete: function(response) { + $("email_con").innerHTML=response.responseText; + $("status").style.display="none"; + $('EmailDetails').innerHTML = '
 
'; + $("subjectsetter").innerHTML=''; + execJS($('email_con')); + } + } + ); +} + diff --git a/oss/vtiger/trunk/modules/Emails/Emails.php b/oss/vtiger/trunk/modules/Emails/Emails.php new file mode 100644 index 00000000..3d7c079e --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/Emails.php @@ -0,0 +1,690 @@ +'crmid','vtiger_activity'=>'activityid', + 'vtiger_seactivityrel'=>'activityid','vtiger_cntactivityrel'=>'activityid','vtiger_email_track'=>'mailid','vtiger_emaildetails'=>'emailid'); + + // This is the list of vtiger_fields that are in the lists. + var $list_fields = Array( + 'Subject'=>Array('activity'=>'subject'), + 'Related to'=>Array('seactivityrel'=>'parent_id'), + 'Date Sent'=>Array('activity'=>'date_start'), + 'Assigned To'=>Array('crmentity','smownerid'), + 'Access Count'=>Array('email_track','access_count') + ); + + var $list_fields_name = Array( + 'Subject'=>'subject', + 'Related to'=>'parent_id', + 'Date Sent'=>'date_start', + 'Assigned To'=>'assigned_user_id', + 'Access Count'=>'access_count' + ); + + var $list_link_field= 'subject'; + + var $column_fields = Array(); + + var $sortby_fields = Array('subject','date_start','saved_toid'); + + //Added these variables which are used as default order by and sortorder in ListView + var $default_order_by = 'date_start'; + 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('subject','assigned_user_id'); + + /** This function will set the columnfields for Email module + */ + + function Emails() { + $this->log = LoggerManager::getLogger('email'); + $this->log->debug("Entering Emails() method ..."); + $this->log = LoggerManager::getLogger('email'); + $this->db = PearDatabase::getInstance(); + $this->column_fields = getColumnFields('Emails'); + $this->log->debug("Exiting Email method ..."); + } + + + function save_module($module) + { + global $adb; + //Inserting into seactivityrel + + //modified by Richie as raju's implementation broke the feature for addition of webmail to vtiger_crmentity.need to be more careful in future while integrating code + if($_REQUEST['module']=="Emails" && $_REQUEST['smodule']!='webmails' && (!$this->plugin_save)) + { + if($_REQUEST['currentid']!='') + { + $actid=$_REQUEST['currentid']; + } + else + { + $actid=$_REQUEST['record']; + } + $parentid=$_REQUEST['parent_id']; + if($_REQUEST['module'] != 'Emails' && $_REQUEST['module'] != 'Webmails') + { + if(!$parentid) { + $parentid = $adb->getUniqueID('vtiger_seactivityrel'); + } + $mysql='insert into vtiger_seactivityrel values(?,?)'; + $adb->pquery($mysql, array($parentid, $actid)); + } + else + { + $myids=explode("|",$parentid); //2@71| + for ($i=0;$i<(count($myids)-1);$i++) + { + $realid=explode("@",$myids[$i]); + $mycrmid=$realid[0]; + //added to handle the relationship of emails with vtiger_users + if($realid[1] == -1) + { + $del_q = 'delete from vtiger_salesmanactivityrel where smid=? and activityid=?'; + $adb->pquery($del_q,array($mycrmid, $actid)); + $mysql='insert into vtiger_salesmanactivityrel values(?,?)'; + } + else + { + $del_q = 'delete from vtiger_seactivityrel where crmid=? and activityid=?'; + $adb->pquery($del_q,array($mycrmid, $actid)); + $mysql='insert into vtiger_seactivityrel values(?,?)'; + } + $params = array($mycrmid, $actid); + $adb->pquery($mysql, $params); + } + } + } + else + { + if(isset($this->column_fields['parent_id']) && $this->column_fields['parent_id'] != '') + { + $this->insertIntoEntityTable('vtiger_seactivityrel', $module); + } + elseif($this->column_fields['parent_id']=='' && $insertion_mode=="edit") + { + $this->deleteRelation('vtiger_seactivityrel'); + } + } + + + //Insert into cntactivity rel + + if(isset($this->column_fields['contact_id']) && $this->column_fields['contact_id'] != '') + { + $this->insertIntoEntityTable('vtiger_cntactivityrel', $module); + } + elseif($this->column_fields['contact_id'] =='' && $insertion_mode=="edit") + { + $this->deleteRelation('vtiger_cntactivityrel'); + } + + //Inserting into attachment + + $this->insertIntoAttachment($this->id,$module); + + } + + + function insertIntoAttachment($id,$module) + { + global $log, $adb; + $log->debug("Entering into insertIntoAttachment($id,$module) method."); + + $file_saved = false; + + //Added to send generated Invoice PDF with mail + $pdfAttached = $_REQUEST['pdf_attachment']; + //created Invoice pdf is attached with the mail + if(isset($_REQUEST['pdf_attachment']) && $_REQUEST['pdf_attachment'] !='') + { + $file_saved = pdfAttach($this,$module,$pdfAttached,$id); + } + + //This is to added to store the existing attachment id of the contact where we should delete this when we give new image + foreach($_FILES as $fileindex => $files) + { + if($files['name'] != '' && $files['size'] > 0) + { + $files['original_name'] = vtlib_purify($_REQUEST[$fileindex.'_hidden']); + $file_saved = $this->uploadAndSaveFile($id,$module,$files); + } + } + if($module == 'Emails' && isset($_REQUEST['att_id_list']) && $_REQUEST['att_id_list'] != '') + { + $att_lists = explode(";",$_REQUEST['att_id_list'],-1); + $id_cnt = count($att_lists); + if($id_cnt != 0) + { + for($i=0;$i<$id_cnt;$i++) + { + $sql_rel='insert into vtiger_seattachmentsrel values(?,?)'; + $adb->pquery($sql_rel, array($id, $att_lists[$i])); + } + } + } + if($_REQUEST['att_module'] == 'Webmails') + { + require_once("modules/Webmails/Webmails.php"); + require_once("modules/Webmails/MailParse.php"); + require_once('modules/Webmails/MailBox.php'); + //$mailInfo = getMailServerInfo($current_user); + //$temprow = $adb->fetch_array($mailInfo); + + $MailBox = new MailBox($_REQUEST["mailbox"]); + $mbox = $MailBox->mbox; + $webmail = new Webmails($mbox,$_REQUEST['mailid']); + $array_tab = Array(); + $webmail->loadMail($array_tab); + if(isset($webmail->att_details)){ + foreach($webmail->att_details as $fileindex => $files) + { + if($files['name'] != '' && $files['size'] > 0) + { + //print_r($files); + $file_saved = $this->saveForwardAttachments($id,$module,$files); + } + } + } + } + $log->debug("Exiting from insertIntoAttachment($id,$module) method."); + } + + function saveForwardAttachments($id,$module,$file_details) + { + global $log; + $log->debug("Entering into saveForwardAttachments($id,$module,$file_details) method."); + global $adb, $current_user; + global $upload_badext; + require_once('modules/Webmails/MailBox.php'); + $mailbox=$_REQUEST["mailbox"]; + $MailBox = new MailBox($mailbox); + $mail = $MailBox->mbox; + $binFile = sanitizeUploadFileName($file_details['name'], $upload_badext); + $filename = ltrim(basename(" ".$binFile)); //allowed filename like UTF-8 characters + $filetype= $file_details['type']; + $filesize = $file_details['size']; + $filepart = $file_details['part']; + $transfer = $file_details['transfer']; + $file = imap_fetchbody($mail,$_REQUEST['mailid'],$filepart); + if ($transfer == 'BASE64') + $file = imap_base64($file); + elseif($transfer == 'QUOTED-PRINTABLE') + $file = imap_qprint($file); + $current_id = $adb->getUniqueID("vtiger_crmentity"); + $date_var = date('Y-m-d H:i:s'); + //to get the owner id + $ownerid = $this->column_fields['assigned_user_id']; + if(!isset($ownerid) || $ownerid=='') + $ownerid = $current_user->id; + $upload_file_path = decideFilePath(); + file_put_contents ($upload_file_path.$current_id."_".$filename,$file); + + $sql1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?,?,?,?,?,?,?)"; + $params1 = array($current_id, $current_user->id, $ownerid, $module." Attachment", $this->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true)); + $adb->pquery($sql1, $params1); + + $sql2="insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?,?,?,?,?)"; + $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path); + $result=$adb->pquery($sql2, $params2); + + if($_REQUEST['mode'] == 'edit') + { + if($id != '' && $_REQUEST['fileid'] != '') + { + $delquery = 'delete from vtiger_seattachmentsrel where crmid = ? and attachmentsid = ?'; + $adb->pquery($delquery, array($id, $_REQUEST['fileid'])); + } + } + $sql3='insert into vtiger_seattachmentsrel values(?,?)'; + $adb->pquery($sql3, array($id, $current_id)); + return true; + $log->debug("exiting from saveforwardattachment function."); + } + /** Returns a list of the associated contacts + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.. + * All Rights Reserved.. + * Contributor(s): ______________________________________.. + */ + function get_contacts($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule,$current_user; + $log->debug("Entering get_contacts(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + + $button = ''; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + if(in_array('BULKMAIL', $actions) && isPermitted($related_module,1, '') == 'yes') { + $button .= ""; + } + } + + $query = 'select vtiger_contactdetails.accountid, vtiger_contactdetails.contactid, vtiger_contactdetails.firstname,vtiger_contactdetails.lastname, vtiger_contactdetails.department, vtiger_contactdetails.title, vtiger_contactdetails.email, vtiger_contactdetails.phone, vtiger_contactdetails.emailoptout, vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.modifiedtime from vtiger_contactdetails inner join vtiger_cntactivityrel on vtiger_cntactivityrel.contactid=vtiger_contactdetails.contactid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid where vtiger_cntactivityrel.activityid='.$adb->quote($id).' and vtiger_crmentity.deleted=0'; + + $return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_contacts method ..."); + return $return_value; + } + + /** Returns the column name that needs to be sorted + * Portions created by vtigerCRM are Copyright (C) vtigerCRM. + * All Rights Reserved.. + * Contributor(s): Mike Crowe + */ + + function getSortOrder() + { + global $log; + $log->debug("Entering getSortOrder() method ..."); + if(isset($_REQUEST['sorder'])) + $sorder = $this->db->sql_escape_string($_REQUEST['sorder']); + else + $sorder = (($_SESSION['EMAILS_SORT_ORDER'] != '')?($_SESSION['EMAILS_SORT_ORDER']):($this->default_sort_order)); + + $log->debug("Exiting getSortOrder method ..."); + return $sorder; + } + + /** Returns the order in which the records need to be sorted + * Portions created by vtigerCRM are Copyright (C) vtigerCRM. + * All Rights Reserved.. + * Contributor(s): Mike Crowe + */ + + function getOrderBy() + { + global $log; + $log->debug("Entering getOrderBy() method ..."); + + $use_default_order_by = ''; + if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) { + $use_default_order_by = $this->default_order_by; + } + + if (isset($_REQUEST['order_by'])) + $order_by = $this->db->sql_escape_string($_REQUEST['order_by']); + else + $order_by = (($_SESSION['EMAILS_ORDER_BY'] != '')?($_SESSION['EMAILS_ORDER_BY']):($use_default_order_by)); + + $log->debug("Exiting getOrderBy method ..."); + return $order_by; + } + // Mike Crowe Mod -------------------------------------------------------- + + /** Returns a list of the associated vtiger_users + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.. + * All Rights Reserved.. + * Contributor(s): ______________________________________.. + */ + function get_users($id) + { + global $log; + $log->debug("Entering get_users(".$id.") method ..."); + global $adb; + global $mod_strings; + global $app_strings; + + $id = $_REQUEST['record']; + + $button = '  + '; + + $query = 'SELECT vtiger_users.id, vtiger_users.first_name,vtiger_users.last_name, vtiger_users.user_name, vtiger_users.email1, vtiger_users.email2, vtiger_users.yahoo_id, vtiger_users.phone_home, vtiger_users.phone_work, vtiger_users.phone_mobile, vtiger_users.phone_other, vtiger_users.phone_fax from vtiger_users inner join vtiger_salesmanactivityrel on vtiger_salesmanactivityrel.smid=vtiger_users.id and vtiger_salesmanactivityrel.activityid=?'; + $result=$adb->pquery($query, array($id)); + + $noofrows = $adb->num_rows($result); + $header [] = $app_strings['LBL_LIST_NAME']; + + $header []= $app_strings['LBL_LIST_USER_NAME']; + + $header []= $app_strings['LBL_EMAIL']; + + $header []= $app_strings['LBL_PHONE']; + while($row = $adb->fetch_array($result)) + { + + global $current_user; + + $entries = Array(); + + if(is_admin($current_user)) + { + $entries[] = $row['last_name'].' '.$row['first_name']; + } + else + { + $entries[] = $row['last_name'].' '.$row['first_name']; + } + + $entries[] = $row['user_name']; + $entries[] = $row['email1']; + if($email == '') $email = $row['email2']; + if($email == '') $email = $row['yahoo_id']; + + $entries[] = $row['phone_home']; + if($phone == '') $phone = $row['phone_work']; + if($phone == '') $phone = $row['phone_mobile']; + if($phone == '') $phone = $row['phone_other']; + if($phone == '') $phone = $row['phone_fax']; + + //Adding Security Check for User + + $entries_list[] = $entries; + } + + if($entries_list != '') + $return_data = array("header"=>$header, "entries"=>$entries); + + if($return_data == null) $return_data = Array(); + $return_data['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_users method ..."); + return $return_data; + } + + + /** + * Returns a list of the Emails to be exported + */ + function create_export_query(&$order_by, &$where) + { + global $log; + global $current_user; + $log->debug("Entering create_export_query(".$order_by.",".$where.") method ..."); + + include("include/utils/ExportUtils.php"); + + //To get the Permitted fields query and the permitted fields list + $sql = getPermittedFieldsQuery("Emails", "detail_view"); + $fields_list = getFieldsListFromQuery($sql); + + $query = "SELECT $fields_list FROM vtiger_activity + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid=vtiger_activity.activityid + LEFT JOIN vtiger_users + ON vtiger_users.id = vtiger_crmentity.smownerid + LEFT JOIN vtiger_seactivityrel + ON vtiger_seactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_contactdetails + ON vtiger_contactdetails.contactid = vtiger_seactivityrel.crmid + LEFT JOIN vtiger_cntactivityrel + ON vtiger_cntactivityrel.activityid = vtiger_activity.activityid + AND vtiger_cntactivityrel.contactid = vtiger_cntactivityrel.contactid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_salesmanactivityrel + ON vtiger_salesmanactivityrel.activityid = vtiger_activity.activityid + LEFT JOIN vtiger_emaildetails + ON vtiger_emaildetails.emailid = vtiger_activity.activityid + LEFT JOIN vtiger_seattachmentsrel + ON vtiger_activity.activityid=vtiger_seattachmentsrel.crmid + LEFT JOIN vtiger_attachments + ON vtiger_seattachmentsrel.attachmentsid = vtiger_attachments.attachmentsid + WHERE vtiger_activity.activitytype='Emails' AND vtiger_crmentity.deleted=0 "; + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + //we should add security check when the user has Private Access + + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + { + $sec_parameter=getListViewSecurityParameter("Emails"); + $query .= $sec_parameter; + } + + $log->debug("Exiting create_export_query method ..."); + return $query; + } + + /** + * Used to releate email and contacts -- Outlook Plugin + */ + function set_emails_contact_invitee_relationship($email_id, $contact_id) + { + global $log; + $log->debug("Entering set_emails_contact_invitee_relationship(".$email_id.",". $contact_id.") method ..."); + $query = "insert into $this->rel_contacts_table (contactid,activityid) values(?,?)"; + $this->db->pquery($query, array($contact_id, $email_id), true,"Error setting email to contact relationship: "."
$query"); + $log->debug("Exiting set_emails_contact_invitee_relationship method ..."); + } + + /** + * Used to releate email and salesentity -- Outlook Plugin + */ + function set_emails_se_invitee_relationship($email_id, $contact_id) + { + global $log; + $log->debug("Entering set_emails_se_invitee_relationship(".$email_id.",". $contact_id.") method ..."); + $query = "insert into $this->rel_serel_table (crmid,activityid) values(?,?)"; + $this->db->pquery($query, array($contact_id, $email_id), true,"Error setting email to contact relationship: "."
$query"); + $log->debug("Exiting set_emails_se_invitee_relationship method ..."); + } + + /** + * Used to releate email and Users -- Outlook Plugin + */ + function set_emails_user_invitee_relationship($email_id, $user_id) + { + global $log; + $log->debug("Entering set_emails_user_invitee_relationship(".$email_id.",". $user_id.") method ..."); + $query = "insert into $this->rel_users_table (smid,activityid) values (?,?)"; + $this->db->pquery($query, array($user_id, $email_id), true,"Error setting email to user relationship: "."
$query"); + $log->debug("Exiting set_emails_user_invitee_relationship method ..."); + } + + // Function to unlink an entity with given Id from another entity + function unlinkRelationship($id, $return_module, $return_id) { + global $log; + + $sql='DELETE FROM vtiger_seactivityrel WHERE activityid=?'; + $this->db->pquery($sql, array($id)); + + $sql = 'DELETE FROM vtiger_crmentityrel WHERE (crmid=? AND relmodule=? AND relcrmid=?) OR (relcrmid=? AND module=? AND crmid=?)'; + $params = array($id, $return_module, $return_id, $id, $return_module, $return_id); + $this->db->pquery($sql, $params); + } +} +/** Function to get the emailids for the given ids form the request parameters + * It returns an array which contains the mailids and the parentidlists +*/ + +function get_to_emailids($module) +{ + global $adb; + if(isset($_REQUEST["field_lists"]) && $_REQUEST["field_lists"] != "") + { + $field_lists = $_REQUEST["field_lists"]; + if (is_string($field_lists)) $field_lists = explode(":", $field_lists); + $query = 'select columnname,fieldid from vtiger_field where fieldid in ('. generateQuestionMarks($field_lists) .') and vtiger_field.presence in (0,2)'; + $result = $adb->pquery($query, array($field_lists)); + $columns = Array(); + $idlists = ''; + $mailids = ''; + while($row = $adb->fetch_array($result)) + { + $columns[]=$row['columnname']; + $fieldid[]=$row['fieldid']; + } + $columnlists = implode(',',$columns); + $idstring = $_REQUEST["idlist"]; + $single_record = false; + if(!strpos($idstring,':')) + { + $single_record = true; + } + $crmids = ereg_replace(':',',',$idstring); + $crmids = explode(",", $crmids); + switch($module) + { + case 'Leads': + $query = 'select crmid,concat(lastname," ",firstname) as entityname,'.$columnlists.' from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid left join vtiger_leadscf on vtiger_leadscf.leadid = vtiger_leaddetails.leadid where vtiger_crmentity.deleted=0 and ((ltrim(vtiger_leaddetails.email) != \'\') or (ltrim(vtiger_leaddetails.yahooid) != \'\')) and vtiger_crmentity.crmid in ('. generateQuestionMarks($crmids) .')'; + break; + case 'Contacts': + //email opt out funtionality works only when we do mass mailing. + if(!$single_record) + $concat_qry = '(((ltrim(vtiger_contactdetails.email) != \'\') or (ltrim(vtiger_contactdetails.yahooid) != \'\')) and (vtiger_contactdetails.emailoptout != 1)) and '; + else + $concat_qry = '((ltrim(vtiger_contactdetails.email) != \'\') or (ltrim(vtiger_contactdetails.yahooid) != \'\')) and '; + $query = 'select crmid,concat(lastname," ",firstname) as entityname,'.$columnlists.' from vtiger_contactdetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid left join vtiger_contactscf on vtiger_contactscf.contactid = vtiger_contactdetails.contactid where vtiger_crmentity.deleted=0 and '.$concat_qry.' vtiger_crmentity.crmid in ('. generateQuestionMarks($crmids) .')'; + break; + case 'Accounts': + //added to work out email opt out functionality. + if(!$single_record) + $concat_qry = '(((ltrim(vtiger_account.email1) != \'\') or (ltrim(vtiger_account.email2) != \'\')) and (vtiger_account.emailoptout != 1)) and '; + else + $concat_qry = '((ltrim(vtiger_account.email1) != \'\') or (ltrim(vtiger_account.email2) != \'\')) and '; + + $query = 'select crmid,accountname as entityname,'.$columnlists.' from vtiger_account inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid left join vtiger_accountscf on vtiger_accountscf.accountid = vtiger_account.accountid where vtiger_crmentity.deleted=0 and '.$concat_qry.' vtiger_crmentity.crmid in ('. generateQuestionMarks($crmids) .')'; + break; + } + $result = $adb->pquery($query, array($crmids)); + while($row = $adb->fetch_array($result)) + { + $name = $row['entityname']; + for($i=0;$i,'; + } + } + } + + $return_data = Array('idlists'=>$idlists,'mailds'=>$mailids); + }else + { + $return_data = Array('idlists'=>"",'mailds'=>""); + } + return $return_data; + +} + +//added for attach the generated pdf with email +function pdfAttach($obj,$module,$file_name,$id) +{ + global $log; + $log->debug("Entering into pdfAttach() method."); + + global $adb, $current_user; + global $upload_badext; + $date_var = date('Y-m-d H:i:s'); + + $ownerid = $obj->column_fields['assigned_user_id']; + if(!isset($ownerid) || $ownerid=='') + $ownerid = $current_user->id; + + $current_id = $adb->getUniqueID("vtiger_crmentity"); + + $upload_file_path = decideFilePath(); + + //Copy the file from temporary directory into storage directory for upload + $source_file_path = "storage/".$file_name; + $status = copy($source_file_path, $upload_file_path.$current_id."_".$file_name); + //Check wheather the copy process is completed successfully or not. if failed no need to put entry in attachment table + if($status) + { + $query1 = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?,?,?,?,?,?,?)"; + $params1 = array($current_id, $current_user->id, $ownerid, $module." Attachment", $obj->column_fields['description'], $adb->formatDate($date_var, true), $adb->formatDate($date_var, true)); + $adb->pquery($query1, $params1); + + $query2="insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?,?,?,?,?)"; + $params2 = array($current_id, $file_name, $obj->column_fields['description'], 'pdf', $upload_file_path); + $result=$adb->pquery($query2, $params2); + + $query3='insert into vtiger_seattachmentsrel values(?,?)'; + $adb->pquery($query3, array($id, $current_id)); + + // Delete the file that was copied + unlink($source_file_path); + + return true; + } + else + { + $log->debug("pdf not attached"); + return false; + } +} +//this function check email fields profile permission as well as field access permission +function emails_checkFieldVisiblityPermission($fieldname) { + global $current_user; + $ret = getFieldVisibilityPermission('Emails',$current_user->id,$fieldname); + return $ret; +} + +?> diff --git a/oss/vtiger/trunk/modules/Emails/EmailsAjax.php b/oss/vtiger/trunk/modules/Emails/EmailsAjax.php new file mode 100644 index 00000000..63446040 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/EmailsAjax.php @@ -0,0 +1,53 @@ +retrieve_entity_info($crmid,"Emails"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Emails"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +elseif($_REQUEST['ajaxmode'] == 'qcreate') +{ + require_once('quickcreate.php'); +} +else +{ + require_once('include/Ajax/CommonAjax.php'); +} +?> diff --git a/oss/vtiger/trunk/modules/Emails/GmailBookmarklet.js b/oss/vtiger/trunk/modules/Emails/GmailBookmarklet.js new file mode 100644 index 00000000..0f95c0ea --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/GmailBookmarklet.js @@ -0,0 +1,552 @@ +function init(){ + function XHR(type,url,params){ + this.xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); + this.url = url; + this.params = params; + this.type = type; + }; + XHR.prototype.load=function(async,callback){ + this.onload=callback; + this.async=async; + + if(this.type.toLowerCase()=="get"){ + this.url = this.url+"?"+this.params; + } + + this.xhr.open(this.type,this.url,this.async); + try{ + if(async){ + var request = this; + this.xhr.onreadystatechange=function(){ + request.readyStateChange(); + } + } + if(this.type.toLowerCase()=="post"){ + this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); + this.xhr.setRequestHeader("Content-length", this.params.length); + } + this.xhr.send(this.params); + }catch(e){ + alert("error: "+e); + } + }; + XHR.prototype.readyStateChange=function(){ + var ready=this.xhr.readyState; + if(ready==4){ + var httpStatus=null; + httpStatus=this.xhr.status; + if(httpStatus==200 || httpStatus==0){ + if(this.async){ + this.onload.call(this,this.xhr); + } + } + } + }; + + function VtigerWebservice(vtigerurl,username,accesskey){ + var vtigerURL=vtigerurl; + var username=username; + var accessKey=accesskey; + var userId=null; + var sessionId=null; + + function getResult(response){ + return response.result; + } + + function getError(response){ + return response.error; + } + + function extendsession(){ + var req = new XHR("post",vtigerURL,"operation=extendsession"); + req.load(false); + var res = JSON.parse(req.xhr.responseText); + if(res.success){ + var result = getResult(res); + this.userId=result.userId; + this.sessionId=result.sessionName; + } + } + + function create(object, objectType, callback){ + var objectJson = JSON.stringify(object); + var req = new XHR("post",doc.vtigerURL,("operation=create&elementType="+objectType+"&sessionName="+this.sessionId+ + "&element="+encodeURIComponent(objectJson))); + req.load(true,callback); + } + + function query(query, callback){ + var req = new XHR("get",doc.vtigerURL,"operation=query&query="+encodeURIComponent(query)+"&sessionName="+this.sessionId); + req.load(true,callback); + } + return {extendSession:extendsession,query:query,getResult:getResult,userId:userId,create:create,getError:getError}; + }; + if (!this.JSON) { + JSON = function () { + function f(n) { + return n < 10 ? "0" + n : n; + } + Date.prototype.toJSON = function () { + return this.getUTCFullYear() + "-" + + f(this.getUTCMonth() + 1) + "-" + + f(this.getUTCDate()) + "T" + + f(this.getUTCHours()) + ":" + + f(this.getUTCMinutes()) + ":" + + f(this.getUTCSeconds()) + "Z"; + }; + var m = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "\"" : "\\\"", + "\\": "\\\\" + }; + function stringify(value, whitelist) { + var a, // The array holding the partial texts. + i, // The loop counter. + k, // The member key. + l, // Length. + r = /["\\\x00-\x1f\x7f-\x9f]/g, + v; // The member value. + switch (typeof value) { + case "string": + return r.test(value) ? + "\"" + value.replace(r, function (a) { + var c = m[a]; + if (c) { + return c; + } + c = a.charCodeAt(); + return "\\u00" + Math.floor(c / 16).toString(16) + + (c % 16).toString(16); + }) + "\"" : + "\"" + value + "\""; + case "number": + return isFinite(value) ? String(value) : "null"; + case "boolean": + case "null": + return String(value); + case "object": + if (!value) { + return "null"; + } + if (typeof value.toJSON === "function") { + return stringify(value.toJSON()); + } + a = []; + if (typeof value.length === "number" && + !(value.propertyIsEnumerable("length"))) { + l = value.length; + for (i = 0; i < l; i += 1) { + a.push(stringify(value[i], whitelist) || "null"); + } + return "[" + a.join(",") + "]"; + } + if (whitelist) { + l = whitelist.length; + for (i = 0; i < l; i += 1) { + k = whitelist[i]; + if (typeof k === "string") { + v = stringify(value[k], whitelist); + if (v) { + a.push(stringify(k) + ":" + v); + } + } + } + } else { + for (k in value) { + if (typeof k === "string") { + v = stringify(value[k], whitelist); + if (v) { + a.push(stringify(k) + ":" + v); + } + } + } + } + return "{" + a.join(",") + "}"; + } + return undefined; + } + return { + stringify: stringify, + parse: function (text, filter) { + var j; + function walk(k, v) { + var i, n; + if (v && typeof v === "object") { + for (i in v) { + if (Object.prototype.hasOwnProperty.apply(v, [i])) { + n = walk(i, v[i]); + if (n !== undefined) { + v[i] = n; + } + } + } + } + return filter(k, v); + } + if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, "@"). + replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g, "]"). + replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) { + j = eval("(" + text + ")"); + return typeof filter === "function" ? walk("", j) : j; + } + throw new SyntaxError("parseJSON"); + } + }; + }(); + } + + var doc = document; + + function trim(str) { + var s = str.replace(/\s+$/, ""); + s = s.replace(/^\s+/, ""); + return s; + } + + function getGmailSubject() { + var subject = top.document.title; + var firstIndexOf = subject.indexOf("-"); + var lastIndexOf = subject.lastIndexOf("-"); + subject = subject.substring(firstIndexOf+1, lastIndexOf-1); + return trim(subject); + } + + function getVtigerBaseURL(){ + var url = document.location.href.substring(0,document.location.href.lastIndexOf('/')+1); + if(url.length > 0){ + if(url.charAt(url.length-1) !="/"){ + url += "/"; + } + return url; + } + return null; + } + + function getVtigerURL(){ + if(doc.vtigerBaseURL.length > 0){ + var url =doc.vtigerBaseURL; + url +="webservice.php"; + return url; + } + return null; + } + + function getGmailURL() { + var locationhref = location.href; + if(locationhref.indexOf("?")) { + var lsplits = locationhref.split("?"); + locationhref = lsplits[0]; + } else if(locationhref.indexOf("#")) { + var lsplits = locationhref.split("#"); + locationhref = lsplits[0]; + } + return locationhref; + } + + var elementId = "__vtigerBookMarkletDiv__"; + var busyElementId = "__vtigerBookMarkletDivBusy__" + function showBookMarkletUI(){ + var bookMarkletDiv = doc.getElementById(elementId); + if(bookMarkletDiv == null){ + bookMarkletDiv.style.display="block"; + } + } + + function hideBookMarkletUI(){ + var bookMarkletDiv = doc.getElementById(elementId); + if(bookMarkletDiv != null){ + bookMarkletDiv.style.display="none"; + } + } + + function destroyBookMarkletUI(){ + var closeElementId = '__vtigetGmailCloseElement'; + var parentLocation = location.href.split("location="); + if(parentLocation.length>1){ + var closeElement = doc.getElementById(closeElementId); + if(closeElement==null){ + closeElement = doc.createElement("iframe"); + closeElement.style.width="0px"; + closeElement.frameBorder="0px"; + closeElement.style.height="0px"; + closeElement.style.display="none"; + closeElement.id = closeElementId; + closeElement.src = decodeURIComponent(parentLocation[1])+"#"; + doc.body.appendChild(closeElement); + } + closeElement.onload=function(){ + eval('window.parent.parent.removeMe()'); + } + } + } + + function showBusy(){ + var bookMarkletDiv = doc.getElementById(elementId); + var busyElem = doc.getElementById(busyElementId); + if(busyElem==null){ + busyElem = doc.createElement('div'); + busyElem.id = busyElementId; + busyElem.innerHTML="Working..."; + busyElem.style.position="absolute"; + busyElem.style.top="5px"; + busyElem.style.right="5px"; + busyElem.style.color="white"; + busyElem.style.backgroundColor="#D75235"; + busyElem.style.padding="2px"; + bookMarkletDiv.appendChild(busyElem); + }else{ + busyElem.style.display="block"; + } + + } + + function hideBusy(){ + var busyElem = doc.getElementById(busyElementId); + if(busyElem!=null){ + busyElem.style.display="none"; + } + } + + if(typeof doc.vtigerURL =="undefined" || doc.vtigerURL == null || doc.vtigerURL == ""){ + doc.vtigerBaseURL = getVtigerBaseURL(); + if(doc.vtigerBaseURL ==null){ + alert("Please Provide a Valid URL"); + return; + } + doc.vtigerURL = getVtigerURL(); + } + var client = new VtigerWebservice(doc.vtigerURL,null,null); + + showBusy(); + client.extendSession(); + hideBusy(); + showBookMarkletUI(); + + function onReady(id,callback){ + var interval = window.setInterval(function(){ + var elem = doc.getElementById(id); + if(elem != null && typeof elem != "undefined"){ + callback(); + window.clearInterval(interval); + } + },10); + } + + function createBookMarkletUI(){ + + onReady("__saveVtigerEmail__",function(){ + doc.getElementById("__saveVtigerEmail__").onclick=function(){ + createEmail(); + } + }); + onReady("parentType",function(){ + doc.getElementById("parentName").innerHTML = "No "+doc.getElementById("parentType").value+" Selected."; + doc.getElementById("parentType").onchange=function(){ + doc.getElementById("parentName").innerHTML = "No "+this.value+" Selected."; + } + }); + + function getQuery(searchValue){ + + var moduleName = doc.getElementById("parentType").value; + var moduleDetails = JSON.parse(moduleNameFields); + var entityNameFields = moduleDetails[moduleName]; + var selectFields = ''; + var whereFields = ''; + each(entityNameFields,function(k,v){ + if(selectFields.length > 0){ + selectFields +=','; + } + selectFields += v; + if(whereFields.length > 0){ + whereFields +=" or "; + } + whereFields += v+" like '%"+searchValue+"%'"; + }); + return "select "+selectFields+" from "+moduleName+" where "+whereFields+";"; + } + + onReady("__searchVtigerAccount__",function(){ + doc.getElementById("__searchVtigerAccount__").onclick=function(e){ + var elem = doc.getElementById("__vtigerAccountSearchList___"); + elem.style.display=""; + + var accountName = doc.getElementById("__searchaccount__").value; + if(accountName.length < 1){ + alert("Please enter the search critiria"); + return; + } + showBusy(); + var q = getQuery(accountName); + var moduleName = doc.getElementById("parentType").value; + var responseElem = doc.getElementById("__vtigerAccountSearchResponse___"); + if(responseElem != null){ + responseElem.innerHTML = ''; + } + client.query(q,function(response){ + var responseElem = doc.getElementById("__vtigerAccountSearchResponse___"); + if(responseElem == null){ + var sibling = doc.createElement("tr"); + var td = doc.createElement("td"); + td.colSpan = "3"; + str = "
"; + td.innerHTML = str; + sibling.appendChild(td); + elem.parentNode.appendChild(sibling); + } + onReady("__vtigerAccountSearchResponse___",function(){ + displaySearchResult(moduleName,response,accountName); + }); + }); + } + }); + } + + function getSiblingByTagName(elem,tagName){ + var sibling = elem.nextSibling; + while(sibling.nodeName.toLowerCase()!=tagName.toLowerCase()){ + sibling = sibling.nextSibling; + } + return sibling; + } + + function each(object,callback){ + var name, i = 0, length = object.length; + if ( length == undefined ) { + for ( name in object ) + if ( callback.call( object[ name ], name, object[ name ] ) === false ) + break; + } else + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} + return object; + } + + function findObject(array,needle){ + var name, i = 0, length = array.length; + var propect = null; + for (; i < length; ++i ){ + var object = array[i]; + for ( name in object ){ + if(object[name] === needle){ + prospect=object; + break; + } + } + } + return prospect; + } + + function getEntityName(moduleName,row){ + var moduleDetails = JSON.parse(moduleNameFields); + var entityNameFields = moduleDetails[moduleName]; + var entityName = ''; + var entityNameField = ''; + each(entityNameFields,function(k,v){ + if(entityName.length>0){ + entityName += " "; + } + entityName +=row[v]; + }); + return entityName; + } + + function displaySearchResult(moduleName,response,accountName){ + hideBusy(); + var queryResponse = JSON.parse(response.responseText); + if(queryResponse.success == true){ + var queryResult = client.getResult(queryResponse); + var str ="
    "; + if(queryResult.length > 0){ + each(queryResult, function(i, row){ + var entityName = getEntityName(moduleName,row); + str+="
  • "+ + entityName+"
  • "; + }); + }else{ + str +="
  • No Record Match \""+accountName+"\"
  • "; + } + str += "
"; + var elem = doc.getElementById("__vtigerAccountSearchResponse___"); + elem.style.height="120px"; + elem.innerHTML = str; + each(elem.getElementsByTagName("a"),function(i,v){ + v.onclick=function(){ + var elem = findObject(queryResult,this.id); + var entityName = getEntityName(moduleName,elem); + setAccountId(elem.id,entityName); + var wrap = doc.getElementById("__vtigerAccountSearchList___"); + wrap.style.display="none"; + doc.getElementById('__searchaccount__').value=''; + } + }); + }else{ + var error = client.getError(queryResponse); + alert("Vtiger returned Error: \nerrorCode: "+error.code+"\nerror Message: "+error.message); + } + } + + function waitForObject(obj,callback){ + var interval = window.setInterval(function(){ + if(typeof obj != "undefined"){ + callback(); + window.clearInterval(interval); + } + },10); + } + + function setAccountId(id,entityName){ + var elem = doc.getElementById("parent_id"); + var elemName = doc.getElementById("parentName"); + elem.value = id; + elemName.innerHTML = entityName; + } + + function closeOnSuccess(response){ + var createResponse = JSON.parse(response.responseText); + if(createResponse.success == true){ + alert("Email added to vtigerCRM."); + }else{ + doc.getElementById("__saveVtigerEmail__").disabled=false; + var error = client.getError(createResponse); + alert("Error while creating: \nerrorCode: "+error.code+"\nerror Message: "+error.message); + } + } + + function getTodayDate(format){ + var date = new Date(); + return date.getDay()+"-"+date.getMonth()+"-"+date.getFullYear(); + } + + function createEmail(){ + var parent_id = doc.getElementById("parent_id").value; + var type = doc.getElementById("parentType").value; + if(parent_id.length < 1){ + alert("No "+type+" selected."); + return ; + } + var subject = doc.getElementById("subject").value; + if(subject.length < 1){ + alert("Please provide a value for Subject"); + return; + } + + var description = doc.getElementById("description").value; + if(description.length < 1){ + alert("Please provide a value for Body of the email."); + return; + } + doc.getElementById("__saveVtigerEmail__").disabled=true; + var email ={"description":description,"subject":subject, + "description":description,"assigned_user_id":client.userId, + "date_start":getTodayDate(),"activitytype":"Emails","parent_id": parent_id}; + client.create(email,"Emails",closeOnSuccess) + } + createBookMarkletUI(); +} diff --git a/oss/vtiger/trunk/modules/Emails/GmailBookmarkletTrigger.js b/oss/vtiger/trunk/modules/Emails/GmailBookmarkletTrigger.js new file mode 100644 index 00000000..9ec19ad4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/GmailBookmarkletTrigger.js @@ -0,0 +1,99 @@ +javascript:(function(){var doc = top.document; +var elementId="__vtigerBookMarkletDivWrap__"; +if(navigator.userAgent.toLowerCase().indexOf("msie") == -1){ + var bookMarkletDiv = doc.getElementById(elementId); + if(bookMarkletDiv == null){ + bookMarkletDiv = doc.createElement("div"); + bookMarkletDiv.style.border = "2px solid #73ABFA"; + bookMarkletDiv.style.backgroundColor = "white"; + bookMarkletDiv.innerHTML = ""; + bookMarkletDiv.id = elementId; + bookMarkletDiv.style.position="absolute"; + bookMarkletDiv.style.top="5px"; + bookMarkletDiv.style.right="35px"; + bookMarkletDiv.style.width="562px"; + bookMarkletDiv.style.height="450px"; + bookMarkletDiv.style.zIndex="100000"; + bookMarkletDiv.innerHTML=" "; + bookMarkletDiv.style.overflow = 'hidden'; + bookMarkletDiv.style.fontSize = '11px'; + bookMarkletDiv.style.fontFamily = 'Arial, sans-serif'; + + var closeMe = doc.createElement("span"); + closeMe.style.position="absolute"; + closeMe.style.top="5px"; + closeMe.style.right="5px"; + closeMe.style.color="#0070BA"; + closeMe.style.textDecoration="underline"; + closeMe.style.width="100%"; + closeMe.style.textAlign="right"; + closeMe.style.cursor="pointer"; + closeMe.innerHTML = ""; + closeMe.onclick = function(){ + window.removeMe(); + } + bookMarkletDiv.appendChild(closeMe); + + var popUp = doc.createElement("iframe"); + popUp.id="__vtigerBookmarkletFrame__"; + popUp.name="__vtigerBookmarkletFrame__"; + popUp.style.border="0px"; + popUp.frameBorder="0px"; + popUp.marginHeight="0px"; + popUp.marginWidth="0px"; + popUp.style.width="100%"; + popUp.style.height="100%"; + popUp.src = getTargetURL(); + bookMarkletDiv.appendChild(popUp); + doc.body.appendChild(bookMarkletDiv); + }else{ + bookMarkletDiv.style.display="block"; + } +}else{ + var vtigerGmailBookmarkletWindow = window.open(getTargetURL(),elementId, + "scrollbars=1,top=40,left=40,resizable=1,height=450,width=562"); +} + +function getTargetURL(){ + var threadid = top.location.hash.split("/"); + var mailId = threadid[threadid.length-1]; + var description = encodeURIComponent(getGmailURL()+"?fs=1&tf=1&source=atom&view=cv&search=all&shva=1&th="+mailId); + return doc.vtigerURL+"index.php?module=Emails&action=SaveBookmarklet&subject="+ + encodeURIComponent(getGmailSubject())+"&description="+description+ + "&location="+encodeURIComponent(getGmailURL()); +} + +function trim(str) { + var s = str.replace(/\s+$/, ""); + s = s.replace(/^\s+/, ""); + return s; +} + +function getGmailSubject() { + var subject = top.document.title; + var firstIndexOf = subject.indexOf("-"); + var lastIndexOf = subject.lastIndexOf("-"); + subject = subject.substring(firstIndexOf+1, lastIndexOf-1); + return trim(subject); +} + +function getGmailURL() { + var locationhref = location.href; + if(locationhref.indexOf("?")!==-1) { + var lsplits = locationhref.split("?"); + locationhref = lsplits[0]; + } else if(locationhref.indexOf("#")!==-1) { + var lsplits = locationhref.split("#"); + locationhref = lsplits[0]; + } + return locationhref; +} +window.top.removeMe = function(){ + if(navigator.userAgent.toLowerCase().indexOf("msie") == -1){ + doc.body.removeChild(bookMarkletDiv); + }else{ + vtigerGmailBookmarkletWindow.close(); + } +} +})(); \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/ListView.php b/oss/vtiger/trunk/modules/Emails/ListView.php new file mode 100644 index 00000000..f72af282 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/ListView.php @@ -0,0 +1,202 @@ +initSortbyField('Emails'); +// END +$smarty = new vtigerCRM_Smarty; +$other_text = Array(); + +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +if($_REQUEST['order_by'] != '') + $order_by = $adb->sql_escape_string($_REQUEST['order_by']); +else + $order_by = (($_SESSION['EMAILS_ORDER_BY'] != '')?($_SESSION['EMAILS_ORDER_BY']):($focus->default_order_by)); + +if($_REQUEST['sorder'] != '') + $sorder = $adb->sql_escape_string($_REQUEST['sorder']); +else + $sorder = (($_SESSION['EMAILS_SORT_ORDER'] != '')?($_SESSION['EMAILS_SORT_ORDER']):($focus->default_sort_order)); + +$_SESSION['EMAILS_ORDER_BY'] = $order_by; +$_SESSION['EMAILS_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + + +// focus_list is the means of passing data to a ListView. +global $focus_list; + +//<<<>>>>>> +$oCustomView = new CustomView("Emails"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//<<<<>>>> + +// Buttons and View options +if(isPermitted('Emails','Delete','') == 'yes') +{ + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +} + +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +global $email_title; +$display_title = $mod_strings['LBL_LIST_FORM_TITLE']; +if($email_title)$display_title = $email_title; + +//to get the search vtiger_field if exists +if(isset($_REQUEST['search']) && $_REQUEST['search'] != '' && $_REQUEST['search_text'] != '') +{ + $url_string .= "&search=".vtlib_purify($_REQUEST['search'])."&search_field=".vtlib_purify($_REQUEST['search_field'])."&search_text=".vtlib_purify($_REQUEST['search_text']); + if($_REQUEST['search_field'] != 'join') + $where = $adb->sql_escape_string($_REQUEST['search_field'])." like '". formatForSqlLike($_REQUEST['search_text']) ."'"; + else + $where = "(subject like '". formatForSqlLike($_REQUEST['search_text']) ."' OR vtiger_users.user_name like '". formatForSqlLike($_REQUEST['search_text']) ."')"; +} + + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Emails"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Emails"); +} +else +{ + $list_query = getListQuery("Emails"); +} +//<<<<<<<>>>>>>>> + +if(isset($where) && $where != '') +{ + $list_query .= " AND " .$where; +} +if($_REQUEST['folderid'] =='2') +{ + $list_query .= " AND vtiger_seactivityrel.crmid in (select contactid from vtiger_contactdetails) AND vtiger_emaildetails.email_flag !='WEBMAIL'"; +} +if($_REQUEST['folderid'] =='3') +{ + $list_query .= " AND vtiger_seactivityrel.crmid in (select accountid from vtiger_account)"; +} +if($_REQUEST['folderid'] =='4') +{ + $list_query .= " AND vtiger_seactivityrel.crmid in (select leadid from vtiger_leaddetails)"; +} +if($_REQUEST['folderid'] =='5') +{ + $list_query .= " AND vtiger_salesmanactivityrel.smid in (select id from vtiger_users)"; +} +if($_REQUEST['folderid'] =='6') +{ + $list_query .= " AND vtiger_emaildetails.email_flag ='WEBMAIL'"; +} +if(isset($order_by) && $order_by != '') +{ + $tablename = getTableNameForField('Emails',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + $list_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; +} + +$list_result = $adb->query($list_query); + +//Constructing the list view +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Email'); +$smarty->assign("BUTTONS",$other_text); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +//Retreiving the no of rows +$noofrows = $adb->num_rows($list_result); + +//Retreive the Navigation array +$_REQUEST['allflag'] = 'All'; +$navigation_array = getNavigationValues(1, $noofrows, $noofrows); + +//Retreive the List View Table Header +if($viewid !='') + $url_string .="&viewname=".$viewid; +if(isset($_REQUEST['folderid']) && $_REQUEST['folderid'] != '') + $url_string .= "&folderid=".vtlib_purify($_REQUEST['folderid']); +$listview_header = getListViewHeader($focus,"Emails",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_entries = getListViewEntries($focus,"Emails",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); +//--------------------------added to fix the ticket(4386)------------------------START +foreach($listview_entries as $key=>$value) +{ + $sql="select email_flag from vtiger_emaildetails where emailid=?"; + $result=$adb->pquery($sql, array($key)); + $email_flag=$adb->query_result($result,0,"email_flag"); + $emailid[$key] = $email_flag; +} +$smarty->assign("EMAILFALG",$emailid); +//--------------------------added to fix the ticket(4386)------------------------END + +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); + +$smarty->assign("USERID", $current_user->id); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("theme", $theme); +if($_REQUEST['ajax'] != '') + $smarty->display("EmailContents.tpl"); +else + $smarty->display("Emails.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/ListViewPagging.php b/oss/vtiger/trunk/modules/Emails/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/PHPMailer_LICENSE.txt b/oss/vtiger/trunk/modules/Emails/PHPMailer_LICENSE.txt new file mode 100644 index 00000000..f3f1b3b6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/PHPMailer_LICENSE.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/oss/vtiger/trunk/modules/Emails/PrintEmail.php b/oss/vtiger/trunk/modules/Emails/PrintEmail.php new file mode 100644 index 00000000..dfc3b106 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/PrintEmail.php @@ -0,0 +1,89 @@ +assign('MOD',$mod_strings); +$smarty->assign('THEME',$theme); + +if(isset($_REQUEST['record']) && $_REQUEST['record'] !='' && $_REQUEST['mailbox'] == '') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Emails"); + + $focus->name=$focus->column_fields['name']; + if(isset($_REQUEST['print']) && $_REQUEST['print'] !='') + { + $query = 'select idlists,from_email,to_email,cc_email,bcc_email from vtiger_emaildetails where emailid =?'; + $result = $adb->pquery($query, array($focus->id)); + $smarty->assign('FROM_MAIL',$adb->query_result($result,0,'from_email')); + $to_email = vt_suppressHTMLTags(implode(',',$json->decode($adb->query_result($result,0,'to_email')))); + $smarty->assign('TO_MAIL',$to_email); + $cc_add = vt_suppressHTMLTags(implode(',',$json->decode($adb->query_result($result,0,'cc_email')))); + $smarty->assign('CC_MAIL',$cc_add); + $bcc_add = vt_suppressHTMLTags(implode(',',$json->decode($adb->query_result($result,0,'bcc_email')))); + $smarty->assign('BCC_MAIL',$bcc_add); + $smarty->assign('SUBJECT',$focus->column_fields['subject']); + $smarty->assign('DESCRIPTION',$focus->column_fields['description']); + } + $smarty->display('PrintEmail.tpl'); +} + +if(isset($_REQUEST['record']) && isset($_REQUEST['mailbox']) && $_REQUEST['print']) +{ + if(isset($_REQUEST["mailbox"]) && $_REQUEST["mailbox"] != "") +{ + $mailbox=$_REQUEST["mailbox"]; +} +else +{ + $mailbox="INBOX"; +} +$mailid = $_REQUEST['record']; +$MailBox = new MailBox($mailbox); +$mail = $MailBox->mbox; +$email = new Webmails($MailBox->mbox,$mailid); +$status=imap_setflag_full($MailBox->mbox,$mailid,"\\Seen"); +$attach_tab=array(); +$email->loadMail($attach_tab); +echo "\n"; +$subject = utf8_decode(utf8_encode(imap_utf8($email->subject))); +$from = decode_header($email->from); +$to = decode_header($email->to[0]); +$cc = decode_header($email->cc_header); +$date = decode_header($email->date); +for($i=0;$iattname);$i++){ + $attachment_links .= $email->anchor_arr[$i].decode_header($email->attname[$i])."
                     "; +} +$content['body'] = $email->body; +$content['attachtab'] = $email->attachtab; + +$smarty->assign('FROM_MAIL',$from); +$smarty->assign('TO_MAIL',trim($to,",").","); +$smarty->assign('SUBJECT',$subject); +$smarty->assign('DESCRIPTION',$content['body']); +$smarty->display('PrintEmail.tpl'); +} + +?> diff --git a/oss/vtiger/trunk/modules/Emails/Save.php b/oss/vtiger/trunk/modules/Emails/Save.php new file mode 100644 index 00000000..7fda806b --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/Save.php @@ -0,0 +1,254 @@ +num_rows($adb->pquery($sql, array('email')),0,"id"); + if($records != '') + echo 'SUCCESS'; + else + echo 'FAILURE'; + die; +} + +//Added on 09-11-2005 to avoid loading the webmail vtiger_files in Email process +if($_REQUEST['smodule'] != '') +{ + define('SM_PATH','modules/squirrelmail-1.4.4/'); + /* SquirrelMail required vtiger_files. */ + require_once(SM_PATH . 'functions/strings.php'); + require_once(SM_PATH . 'functions/imap_general.php'); + require_once(SM_PATH . 'functions/imap_messages.php'); + require_once(SM_PATH . 'functions/i18n.php'); + require_once(SM_PATH . 'functions/mime.php'); + require_once(SM_PATH .'include/load_prefs.php'); + //require_once(SM_PATH . 'class/mime/Message.class.php'); + require_once(SM_PATH . 'class/mime.class.php'); + sqgetGlobalVar('key', $key, SQ_COOKIE); + sqgetGlobalVar('username', $username, SQ_SESSION); + sqgetGlobalVar('onetimepad',$onetimepad, SQ_SESSION); + $mailbox = 'INBOX'; +} + +require_once('modules/Emails/Emails.php'); +require_once('include/logging.php'); +require_once('include/database/PearDatabase.php'); + +$local_log =& LoggerManager::getLogger('index'); + +$focus = new Emails(); + +global $current_user,$mod_strings,$app_strings; +if(isset($_REQUEST['description']) && $_REQUEST['description'] !='') + $_REQUEST['description'] = fck_from_html($_REQUEST['description']); + +$all_to_ids = $_REQUEST["hidden_toid"]; +$all_to_ids .= $_REQUEST["saved_toid"]; +$_REQUEST["saved_toid"] = $all_to_ids; +//we always save the email with "save" status and when it is sent it is marked as SENT +$_REQUEST['email_flag'] = 'SAVED'; +setObjectValuesFromRequest($focus); +//Check if the file is exist or not. +//$file_name = ''; +if(isset($_REQUEST['filename_hidden'])) { + $file_name = $_REQUEST['filename_hidden']; +} else { + $file_name = $_FILES['filename']['name']; +} +$errorCode = $_FILES['filename']['error']; +$errormessage = ""; +if($file_name != '' && $_FILES['filename']['size'] == 0) +{ + if($errorCode == 4 || $errorCode == 0) + { + if($_FILES['filename']['size'] == 0) + $errormessage = "".$mod_strings['LBL_PLEASE_ATTACH']."
"; + } + else if($errorCode == 2) + { + $errormessage = "".$mod_strings['LBL_EXCEED_MAX'].$upload_maxsize.$mod_strings['LBL_BYTES']."
"; + } + else if($errorCode == 6) + { + $errormessage = "".$mod_strings['LBL_KINDLY_UPLOAD']."
" ; + } + else if($errorCode == 3 ) + { + if($_FILES['filename']['size'] == 0) + $errormessage = "".$mod_strings['LBL_PLEASE_ATTACH']."
"; + } + else{} + if($errormessage != ""){ + $ret_error = 1; + $ret_parentid = $_REQUEST['parent_id']; + $ret_toadd = $_REQUEST['parent_name']; + $ret_subject = $_REQUEST['subject']; + $ret_ccaddress = $_REQUEST['ccmail']; + $ret_bccaddress = $_REQUEST['bccmail']; + $ret_description = $_REQUEST['description']; + echo $errormessage; + include("EditView.php"); + exit(); + } +} + + +if($_FILES["filename"]["size"] == 0 && $_FILES["filename"]["name"] != '') +{ + $file_upload_error = true; + $_FILES = ''; +} + +if((isset($_REQUEST['deletebox']) && $_REQUEST['deletebox'] != null) && $_REQUEST['addbox'] == null) +{ + imap_delete($mbox,$_REQUEST['deletebox']); + imap_expunge($mbox); + header("Location: index.php?module=Emails&action=index"); + exit(); +} + +function checkIfContactExists($mailid) +{ + global $log; + $log->debug("Entering checkIfContactExists(".$mailid.") method ..."); + global $adb; + $sql = "select contactid from vtiger_contactdetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid where vtiger_crmentity.deleted=0 and email= ?"; + $result = $adb->pquery($sql, array($mailid)); + $numRows = $adb->num_rows($result); + if($numRows > 0) + { + $log->debug("Exiting checkIfContactExists method ..."); + return $adb->query_result($result,0,"contactid"); + } + else + { + $log->debug("Exiting checkIfContactExists method ..."); + return -1; + } +} +//assign the focus values +$focus->filename = $_REQUEST['file_name']; +$focus->parent_id = $_REQUEST['parent_id']; +$focus->parent_type = $_REQUEST['parent_type']; +$focus->column_fields["assigned_user_id"]=$current_user->id; +$focus->column_fields["activitytype"]="Emails"; +$focus->column_fields["date_start"]= date(getNewDisplayDate());//This will be converted to db date format in save +$focus->save("Emails"); +$return_id = $focus->id; + +require_once("modules/Emails/mail.php"); +if(isset($_REQUEST['send_mail']) && $_REQUEST['send_mail'] && $_REQUEST['parent_id'] != '') +{ + $user_mail_status = send_mail('Emails',$current_user->column_fields['email1'],$current_user->user_name,'',$_REQUEST['subject'],$_REQUEST['description'],$_REQUEST['ccmail'],$_REQUEST['bccmail'],'all',$focus->id); + + //if block added to fix the issue #3759 + if($user_mail_status != 1){ + $query = "select crmid,attachmentsid from vtiger_seattachmentsrel where crmid=?"; + $result = $adb->pquery($query, array($email_id)); + $numOfRows = $adb->num_rows($result); + for($i=0; $i<$numOfRows; $i++) + { + $attachmentsid = $adb->query_result($result,0,"attachmentsid"); + if($attachmentsid > 0) + { + $query1="delete from vtiger_crmentity where crmid=?"; + $adb->pquery($query1, array($attachmentsid)); + } + + $crmid=$adb->query_result($result,0,"crmid"); + $query2="delete from vtiger_crmentity where crmid=?"; + $adb->pquery($query2, array($crmid)); + } + + $query = "delete from vtiger_emaildetails where emailid=?"; + $adb->pquery($query, array($focus->id)); + + $error_msg = "".$mod_strings['LBL_CHECK_USER_MAILID'].""; + $ret_error = 1; + $ret_parentid = $_REQUEST['parent_id']; + $ret_toadd = $_REQUEST['parent_name']; + $ret_subject = $_REQUEST['subject']; + $ret_ccaddress = $_REQUEST['ccmail']; + $ret_bccaddress = $_REQUEST['bccmail']; + $ret_description = $_REQUEST['description']; + echo $error_msg; + include("EditView.php"); + exit(); + } + +} + +$focus->retrieve_entity_info($return_id,"Emails"); + +//this is to receive the data from the Select Users button +if($_REQUEST['source_module'] == null) +{ + $module = 'users'; +} +//this will be the case if the Select Contact button is chosen +else +{ + $module = $_REQUEST['source_module']; +} + +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") + $return_module = vtlib_purify($_REQUEST['return_module']); +else + $return_module = "Emails"; + +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") + $return_action = vtlib_purify($_REQUEST['return_action']); +else + $return_action = "DetailView"; + +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") + $return_id = vtlib_purify($_REQUEST['return_id']); + +if(isset($_REQUEST['filename']) && $_REQUEST['filename'] != "") + $filename = vtlib_purify($_REQUEST['filename']); + +$local_log->debug("Saved record with id of ".$return_id); + +if(isset($_REQUEST['send_mail']) && $_REQUEST['send_mail'] && $_REQUEST['parent_id'] == ''){ + if($_REQUEST["parent_name"] != '' && isset($_REQUEST["parent_name"])) { + include("modules/Emails/webmailsend.php"); + } + +} elseif( isset($_REQUEST['send_mail']) && $_REQUEST['send_mail']) + include("modules/Emails/mailsend.php"); + + + +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] == 'mailbox') + header("Location: index.php?module=$return_module&action=index"); +else { + if($_REQUEST['return_viewname'] == '') $return_viewname='0'; + if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + //Added for 4600 + $inputs=""; + echo $inputs; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/SaveBookmarklet.php b/oss/vtiger/trunk/modules/Emails/SaveBookmarklet.php new file mode 100644 index 00000000..f5982634 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/SaveBookmarklet.php @@ -0,0 +1,71 @@ +assign("subject",$_REQUEST['subject']); +$smarty->assign("description",$_REQUEST['description']); + +Zend_Json::$useBuiltinEncoderDecoder = true; +$json = new Zend_Json(); + +$elementType = $_REQUEST['module']; + +global $log,$adb; +$webserviceObject = VtigerWebserviceObject::fromName($adb,$elementType); +$handlerPath = $webserviceObject->getHandlerPath(); +$handlerClass = $webserviceObject->getHandlerClass(); + +require_once $handlerPath; + +$handler = new $handlerClass($webserviceObject,$current_user,$adb,$log); +$meta = $handler->getMeta(); +$meta->retrieveMeta(); + +$types = vtws_listtypes($current_user); +if(!in_array($elementType,$types['types'])){ + throw new WebServiceException(WebServiceErrorCode::$ACCESSDENIED,"Permission to perform the operation is denied"); +} + +$wsFieldDetails = $handler->getField('parent_id'); + +$moduleEntityNameDetails = array(); +foreach ($wsFieldDetails['type']['refersTo'] as $type) { + $moduleEntityNameDetails[$type] = vtws_getEntityNameFields($type); +} + +$smarty->assign("types",$wsFieldDetails['type']['refersTo']); +$smarty->assign("entityNameFields",$json->encode($moduleEntityNameDetails)); + +$smarty->display("modules/Bookmarklet/Bookmarklet.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/TrackAccess.php b/oss/vtiger/trunk/modules/Emails/TrackAccess.php new file mode 100644 index 00000000..95de9f48 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/TrackAccess.php @@ -0,0 +1,40 @@ +pquery("INSERT INTO vtiger_email_access(crmid, mailid, accessdate, accesstime) VALUES(?,?,?,?)", array($crmid, $mailid, date('Y-m-d'), date('H:i:s'))); + +$result = $adb->pquery("select count(*) as count from vtiger_email_access where crmid=? and mailid=?",array($crmid, $mailid)); +$count = $adb->query_result($result,0,'count'); + +$result = $adb->pquery("select * from vtiger_email_track where crmid=? and mailid=?", array($crmid, $mailid)); +if($adb->num_rows($result)>0){ + $adb->pquery("update vtiger_email_track set access_count=? where crmid=? and mailid=?", array($count, $crmid, $mailid)); +} else { + $adb->pquery("insert into vtiger_email_track(crmid,mailid,access_count) values(?,?,?)", array($crmid, $mailid, 1)); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/UnifiedSearch.php b/oss/vtiger/trunk/modules/Emails/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/class.phpmailer.php b/oss/vtiger/trunk/modules/Emails/class.phpmailer.php new file mode 100644 index 00000000..4381935f --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/class.phpmailer.php @@ -0,0 +1,1510 @@ +ContentType = "text/html"; + else + $this->ContentType = "text/plain"; + } + + /** + * Sets Mailer to send message using SMTP. + * @return void + */ + function IsSMTP() { + $this->Mailer = "smtp"; + } + + /** + * Sets Mailer to send message using PHP mail() function. + * @return void + */ + function IsMail() { + $this->Mailer = "mail"; + } + + /** + * Sets Mailer to send message using the $Sendmail program. + * @return void + */ + function IsSendmail() { + $this->Mailer = "sendmail"; + } + + /** + * Sets Mailer to send message using the qmail MTA. + * @return void + */ + function IsQmail() { + $this->Sendmail = "/var/qmail/bin/sendmail"; + $this->Mailer = "sendmail"; + } + + + ///////////////////////////////////////////////// + // RECIPIENT METHODS + ///////////////////////////////////////////////// + + /** + * Adds a "To" address. + * @param string $address + * @param string $name + * @return void + */ + function AddAddress($address, $name = "") { + $cur = count($this->to); + $this->to[$cur][0] = trim($address); + $this->to[$cur][1] = $name; + } + + /** + * Adds a "Cc" address. Note: this function works + * with the SMTP mailer on win32, not with the "mail" + * mailer. + * @param string $address + * @param string $name + * @return void + */ + function AddCC($address, $name = "") { + $cur = count($this->cc); + $this->cc[$cur][0] = trim($address); + $this->cc[$cur][1] = $name; + } + + /** + * Adds a "Bcc" address. Note: this function works + * with the SMTP mailer on win32, not with the "mail" + * mailer. + * @param string $address + * @param string $name + * @return void + */ + function AddBCC($address, $name = "") { + $cur = count($this->bcc); + $this->bcc[$cur][0] = trim($address); + $this->bcc[$cur][1] = $name; + } + + /** + * Adds a "Reply-to" address. + * @param string $address + * @param string $name + * @return void + */ + function AddReplyTo($address, $name = "") { + $cur = count($this->ReplyTo); + $this->ReplyTo[$cur][0] = trim($address); + $this->ReplyTo[$cur][1] = $name; + } + + + ///////////////////////////////////////////////// + // MAIL SENDING METHODS + ///////////////////////////////////////////////// + + /** + * Creates message and assigns Mailer. If the message is + * not sent successfully then it returns false. Use the ErrorInfo + * variable to view description of the error. + * @return bool + */ + function Send() { + $header = ""; + $body = ""; + $result = true; + + if((count($this->to) + count($this->cc) + count($this->bcc)) < 1) + { + $this->SetError($this->Lang("provide_address")); + return false; + } + + // Set whether the message is multipart/alternative + if(!empty($this->AltBody)) + $this->ContentType = "multipart/alternative"; + + $this->error_count = 0; // reset errors + $this->SetMessageType(); + $header .= $this->CreateHeader(); + $body = $this->CreateBody(); + + if($body == "") { return false; } + + // Choose the mailer + switch($this->Mailer) + { + case "sendmail": + $result = $this->SendmailSend($header, html_entity_decode($body,ENT_COMPAT,$this->CharSet)); + break; + case "mail": + $result = $this->MailSend($header, html_entity_decode($body,ENT_COMPAT,$this->CharSet)); + break; + case "smtp": + $result = $this->SmtpSend($header, html_entity_decode($body,ENT_COMPAT,$this->CharSet)); + break; + default: + $this->SetError($this->Mailer . $this->Lang("mailer_not_supported")); + $result = false; + break; + } + + return $result; + } + + /** + * Sends mail using the $Sendmail program. + * @access private + * @return bool + */ + function SendmailSend($header, $body) { + if ($this->Sender != "") + $sendmail = sprintf("%s -oi -f %s -t", $this->Sendmail, $this->Sender); + else + $sendmail = sprintf("%s -oi -t", $this->Sendmail); + + if(!@$mail = popen($sendmail, "w")) + { + $this->SetError($this->Lang("execute") . $this->Sendmail); + return false; + } + + fputs($mail, $header); + fputs($mail, $body); + + $result = pclose($mail) >> 8 & 0xFF; + if($result != 0) + { + $this->SetError($this->Lang("execute") . $this->Sendmail); + return false; + } + + return true; + } + + /** + * Sends mail using the PHP mail() function. + * @access private + * @return bool + */ + function MailSend($header, $body) { + $to = ""; + for($i = 0; $i < count($this->to); $i++) + { + if($i != 0) { $to .= ", "; } + $to .= $this->to[$i][0]; + } + + if ($this->Sender != "" && strlen(ini_get("safe_mode"))< 1) + { + $old_from = ini_get("sendmail_from"); + ini_set("sendmail_from", $this->Sender); + $params = sprintf("-oi -f %s", $this->Sender); + $rt = @mail($to, $this->EncodeHeader($this->Subject), $body, + $header, $params); + } + else + $rt = @mail($to, $this->EncodeHeader($this->Subject), $body, $header); + + if (isset($old_from)) + ini_set("sendmail_from", $old_from); + + if(!$rt) + { + $this->SetError($this->Lang("instantiate")); + return false; + } + + return true; + } + + /** + * Sends mail via SMTP using PhpSMTP (Author: + * Chris Ryan). Returns bool. Returns false if there is a + * bad MAIL FROM, RCPT, or DATA input. + * @access private + * @return bool + */ + function SmtpSend($header, $body) { + include_once($this->PluginDir . "class.smtp.php"); + $error = ""; + $bad_rcpt = array(); + + if(!$this->SmtpConnect()) + return false; + + $smtp_from = ($this->Sender == "") ? $this->From : $this->Sender; + if(!$this->smtp->Mail($smtp_from)) + { + $error = $this->Lang("from_failed") . $smtp_from; + $this->SetError($error); + $this->smtp->Reset(); + return false; + } + + // Attempt to send attach all recipients + for($i = 0; $i < count($this->to); $i++) + { + if(!$this->smtp->Recipient($this->to[$i][0])) + $bad_rcpt[] = $this->to[$i][0]; + } + for($i = 0; $i < count($this->cc); $i++) + { + if(!$this->smtp->Recipient($this->cc[$i][0])) + $bad_rcpt[] = $this->cc[$i][0]; + } + for($i = 0; $i < count($this->bcc); $i++) + { + if(!$this->smtp->Recipient($this->bcc[$i][0])) + $bad_rcpt[] = $this->bcc[$i][0]; + } + + if(count($bad_rcpt) > 0) // Create error message + { + for($i = 0; $i < count($bad_rcpt); $i++) + { + if($i != 0) { $error .= ", "; } + $error .= $bad_rcpt[$i]; + } + $error = $this->Lang("recipients_failed") . $error; + $this->SetError($error); + $this->smtp->Reset(); + return false; + } + + if(!$this->smtp->Data($header . $body)) + { + $this->SetError($this->Lang("data_not_accepted")); + $this->smtp->Reset(); + return false; + } + if($this->SMTPKeepAlive == true) + $this->smtp->Reset(); + else + $this->SmtpClose(); + + return true; + } + + /** + * Initiates a connection to an SMTP server. Returns false if the + * operation failed. + * @access private + * @return bool + */ + function SmtpConnect() { + if($this->smtp == NULL) { $this->smtp = new SMTP(); } + + $this->smtp->do_debug = $this->SMTPDebug; + $hosts = explode(";", $this->Host); + $index = 0; + $connection = ($this->smtp->Connected()); + + // Retry while there is no connection + while($index < count($hosts) && $connection == false) + { + if(strstr($hosts[$index], ":")) + { + #list($host, $port) = explode(":", $hosts[$index]); + $hostA = explode(':', $hosts[$index]); + if (is_numeric(end($hostA))) + $port = array_pop($hostA); + else + $port = $this->Port; + $host = implode(':', $hostA); + } + else + { + $host = $hosts[$index]; + $port = $this->Port; + } + + if($this->smtp->Connect($host, $port, $this->Timeout)) + { + if ($this->Helo != '') + $this->smtp->Hello($this->Helo); + else + $this->smtp->Hello($this->ServerHostname()); + + if($this->SMTPAuth) + { + if(!$this->smtp->Authenticate($this->Username, + $this->Password)) + { + $this->SetError($this->Lang("authenticate")); + $this->smtp->Reset(); + $connection = false; + } + } + $connection = true; + } + $index++; + } + if(!$connection) + $this->SetError($this->Lang("connect_host")); + + return $connection; + } + + /** + * Closes the active SMTP session if one exists. + * @return void + */ + function SmtpClose() { + if($this->smtp != NULL) + { + if($this->smtp->Connected()) + { + $this->smtp->Quit(); + $this->smtp->Close(); + } + } + } + + /** + * Sets the language for all class error messages. Returns false + * if it cannot load the language file. The default language type + * is English. + * @param string $lang_type Type of language (e.g. Portuguese: "br") + * @param string $lang_path Path to the language file directory + * @access public + * @return bool + */ + function SetLanguage($lang_type, $lang_path = "language/") { + global $root_directory; + if(file_exists($root_directory.'/modules/Emails/'.$lang_path.'phpmailer.lang-'.$lang_type.'.php')) + include($root_directory.'/modules/Emails/'.$lang_path.'phpmailer.lang-'.$lang_type.'.php'); + else if(file_exists($root_directory.'/modules/Emails/'.$lang_path.'phpmailer.lang-en.php')) + include($root_directory.'/modules/Emails/'.$lang_path.'phpmailer.lang-en.php'); + else + { + $this->SetError("Could not load language file"); + return false; + } + $this->language = $PHPMAILER_LANG; + + return true; + } + + ///////////////////////////////////////////////// + // MESSAGE CREATION METHODS + ///////////////////////////////////////////////// + + /** + * Creates recipient vtiger_headers. + * @access private + * @return string + */ + function AddrAppend($type, $addr) { + $addr_str = $type . ": "; + $addr_str .= $this->AddrFormat($addr[0]); + if(count($addr) > 1) + { + for($i = 1; $i < count($addr); $i++) + $addr_str .= ", " . $this->AddrFormat($addr[$i]); + } + $addr_str .= $this->LE; + + return $addr_str; + } + + /** + * Formats an address correctly. + * @access private + * @return string + */ + function AddrFormat($addr) { + if(empty($addr[1])) + $formatted = $addr[0]; + else + { + $formatted = $this->EncodeHeader($addr[1], 'phrase') . " <" . + $addr[0] . ">"; + } + + return $formatted; + } + + /** + * Wraps message for use with mailers that do not + * automatically perform wrapping and for quoted-printable. + * Original written by philippe. + * @access private + * @return string + */ + function WrapText($message, $length, $qp_mode = false) { + $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; + + $message = $this->FixEOL($message); + if (substr($message, -1) == $this->LE) + $message = substr($message, 0, -1); + + $line = explode($this->LE, $message); + $message = ""; + for ($i=0 ;$i < count($line); $i++) + { + $line_part = explode(" ", $line[$i]); + $buf = ""; + for ($e = 0; $e $length)) + { + $space_left = $length - strlen($buf) - 1; + if ($e != 0) + { + if ($space_left > 20) + { + $len = $space_left; + if (substr($word, $len - 1, 1) == "=") + $len--; + elseif (substr($word, $len - 2, 1) == "=") + $len -= 2; + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= " " . $part; + $message .= $buf . sprintf("=%s", $this->LE); + } + else + { + $message .= $buf . $soft_break; + } + $buf = ""; + } + while (strlen($word) > 0) + { + $len = $length; + if (substr($word, $len - 1, 1) == "=") + $len--; + elseif (substr($word, $len - 2, 1) == "=") + $len -= 2; + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) + $message .= $part . sprintf("=%s", $this->LE); + else + $buf = $part; + } + } + else + { + $buf_o = $buf; + $buf .= ($e == 0) ? $word : (" " . $word); + + if (strlen($buf) > $length and $buf_o != "") + { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + } + $message .= $buf . $this->LE; + } + + return $message; + } + + /** + * Set the body wrapping. + * @access private + * @return void + */ + function SetWordWrap() { + if($this->WordWrap < 1) + return; + + switch($this->message_type) + { + case "alt": + // fall through + case "alt_attachments": + $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->WrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assembles message header. + * @access private + * @return string + */ + function CreateHeader() { + $result = ""; + + // Set the boundaries + $uniq_id = md5(uniqid(time())); + $this->boundary[1] = "b1_" . $uniq_id; + $this->boundary[2] = "b2_" . $uniq_id; + + $result .= $this->HeaderLine("Date", $this->RFCDate()); + if($this->Sender == "") + $result .= $this->HeaderLine("Return-Path", trim($this->From)); + else + $result .= $this->HeaderLine("Return-Path", trim($this->Sender)); + + // To be created automatically by mail() + if($this->Mailer != "mail") + { + if(count($this->to) > 0) + $result .= $this->AddrAppend("To", $this->to); + else if (count($this->cc) == 0) + $result .= $this->HeaderLine("To", "undisclosed-recipients:;"); + if(count($this->cc) > 0) + $result .= $this->AddrAppend("Cc", $this->cc); + } + + $from = array(); + $from[0][0] = trim($this->From); + $from[0][1] = $this->FromName; + $result .= $this->AddrAppend("From", $from); + + // sendmail and mail() extract Bcc from the header before sending + if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && (count($this->bcc) > 0)) + $result .= $this->AddrAppend("Bcc", $this->bcc); + + if(count($this->ReplyTo) > 0) + $result .= $this->AddrAppend("Reply-to", $this->ReplyTo); + + // mail() sets the subject itself + if($this->Mailer != "mail") + $result .= $this->HeaderLine("Subject", $this->EncodeHeader(trim($this->Subject))); + + $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); + $result .= $this->HeaderLine("X-Priority", $this->Priority); + $result .= $this->HeaderLine("X-Mailer", "PHPMailer [version " . $this->Version . "]"); + + if($this->ConfirmReadingTo != "") + { + $result .= $this->HeaderLine("Disposition-Notification-To", + "<" . trim($this->ConfirmReadingTo) . ">"); + } + + // Add custom vtiger_headers + for($index = 0; $index < count($this->CustomHeader); $index++) + { + $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), + $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); + } + $result .= $this->HeaderLine("MIME-Version", "1.0"); + + switch($this->message_type) + { + case "plain": + $result .= $this->HeaderLine("Content-Transfer-Encoding", $this->Encoding); + $result .= sprintf("Content-Type: %s; charset=\"%s\"", + $this->ContentType, $this->CharSet); + break; + case "attachments": + // fall through + case "alt_attachments": + if($this->InlineImageExists()) + { + $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", + "multipart/related", $this->LE, $this->LE, + $this->boundary[1], $this->LE); + } + else + { + $result .= $this->HeaderLine("Content-Type", "multipart/mixed;"); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + } + break; + case "alt": + $result .= $this->HeaderLine("Content-Type", "multipart/alternative;"); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + } + + if($this->Mailer != "mail") + $result .= $this->LE.$this->LE; + + return $result; + } + + /** + * Assembles the message body. Returns an empty string on failure. + * @access private + * @return string + */ + function CreateBody() { + $result = ""; + + $this->SetWordWrap(); + + switch($this->message_type) + { + case "alt": + $result .= $this->GetBoundary($this->boundary[1], "", + "text/plain", ""); + $result .= $this->EncodeString($this->AltBody, $this->Encoding); + $result .= $this->LE.$this->LE; + $result .= $this->GetBoundary($this->boundary[1], "", + "text/html", ""); + + $result .= $this->EncodeString($this->Body, $this->Encoding); + $result .= $this->LE.$this->LE; + + $result .= $this->EndBoundary($this->boundary[1]); + break; + case "plain": + $result .= $this->EncodeString($this->Body, $this->Encoding); + break; + case "attachments": + $result .= $this->GetBoundary($this->boundary[1], "", "", ""); + $result .= $this->EncodeString($this->Body, $this->Encoding); + $result .= $this->LE; + + $result .= $this->AttachAll(); + break; + case "alt_attachments": + $result .= sprintf("--%s%s", $this->boundary[1], $this->LE); + $result .= sprintf("Content-Type: %s;%s" . + "\tboundary=\"%s\"%s", + "multipart/alternative", $this->LE, + $this->boundary[2], $this->LE.$this->LE); + + // Create text body + $result .= $this->GetBoundary($this->boundary[2], "", + "text/plain", "") . $this->LE; + + $result .= $this->EncodeString($this->AltBody, $this->Encoding); + $result .= $this->LE.$this->LE; + + // Create the HTML body + $result .= $this->GetBoundary($this->boundary[2], "", + "text/html", "") . $this->LE; + + $result .= $this->EncodeString($this->Body, $this->Encoding); + $result .= $this->LE.$this->LE; + + $result .= $this->EndBoundary($this->boundary[2]); + + $result .= $this->AttachAll(); + break; + } + if($this->IsError()) + $result = ""; + + return $result; + } + + /** + * Returns the start of a message boundary. + * @access private + */ + function GetBoundary($boundary, $charSet, $contentType, $encoding) { + $result = ""; + if($charSet == "") { $charSet = $this->CharSet; } + if($contentType == "") { $contentType = $this->ContentType; } + if($encoding == "") { $encoding = $this->Encoding; } + + $result .= $this->TextLine("--" . $boundary); + $result .= sprintf("Content-Type: %s; charset = \"%s\"", + $contentType, $charSet); + $result .= $this->LE; + $result .= $this->HeaderLine("Content-Transfer-Encoding", $encoding); + $result .= $this->LE; + + return $result; + } + + /** + * Returns the end of a message boundary. + * @access private + */ + function EndBoundary($boundary) { + return $this->LE . "--" . $boundary . "--" . $this->LE; + } + + /** + * Sets the message type. + * @access private + * @return void + */ + function SetMessageType() { + if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) + $this->message_type = "plain"; + else + { + if(count($this->attachment) > 0) + $this->message_type = "attachments"; + if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) + $this->message_type = "alt"; + if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) + $this->message_type = "alt_attachments"; + } + } + + /** + * Returns a formatted header line. + * @access private + * @return string + */ + function HeaderLine($name, $value) { + return $name . ": " . $value . $this->LE; + } + + /** + * Returns a formatted mail line. + * @access private + * @return string + */ + function TextLine($value) { + return $value . $this->LE; + } + + ///////////////////////////////////////////////// + // ATTACHMENT METHODS + ///////////////////////////////////////////////// + + /** + * Adds an attachment from a path on the vtiger_filesystem. + * Returns false if the file could not be found + * or accessed. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + function AddAttachment($path, $name = "", $encoding = "base64", + $type = "application/octet-stream") { + if(!@is_file($path)) + { + $this->SetError($this->Lang("file_access") . $path); + return false; + } + + $filename = basename($path); + if($name == "") + $name = $filename; + + $cur = count($this->attachment); + $this->attachment[$cur][0] = $path; + $this->attachment[$cur][1] = $filename; + $this->attachment[$cur][2] = $name; + $this->attachment[$cur][3] = $encoding; + $this->attachment[$cur][4] = $type; + $this->attachment[$cur][5] = false; // isStringAttachment + $this->attachment[$cur][6] = "attachment"; + $this->attachment[$cur][7] = 0; + + return true; + } + + /** + * Attaches all fs, string, and binary vtiger_attachments to the message. + * Returns an empty string on failure. + * @access private + * @return string + */ + function AttachAll() { + // Return text of body + $mime = array(); + + // Add all vtiger_attachments + for($i = 0; $i < count($this->attachment); $i++) + { + // Check for string attachment + $bString = $this->attachment[$i][5]; + if ($bString) + $string = $this->attachment[$i][0]; + else + $path = $this->attachment[$i][0]; + + $filename = $this->attachment[$i][1]; + $name = $this->attachment[$i][2]; + $encoding = $this->attachment[$i][3]; + $type = $this->attachment[$i][4]; + $disposition = $this->attachment[$i][6]; + $cid = $this->attachment[$i][7]; + + $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE); + $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE); + $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); + + if($disposition == "inline") + $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); + + $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", + $disposition, $name, $this->LE.$this->LE); + + // Encode as string attachment + if($bString) + { + $mime[] = $this->EncodeString($string, $encoding); + if($this->IsError()) { return ""; } + $mime[] = $this->LE.$this->LE; + } + else + { + $mime[] = $this->EncodeFile($path, $encoding); + if($this->IsError()) { return ""; } + $mime[] = $this->LE.$this->LE; + } + } + + $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE); + + return join("", $mime); + } + + /** + * Encodes attachment in requested format. Returns an + * empty string on failure. + * @access private + * @return string + */ + function EncodeFile ($path, $encoding = "base64") { + if(!@$fd = fopen($path, "rb")) + { + $this->SetError($this->Lang("file_open") . $path); + return ""; + } + $magic_quotes = get_magic_quotes_runtime(); + set_magic_quotes_runtime(0); + $file_buffer = fread($fd, filesize($path)); + $file_buffer = $this->EncodeString($file_buffer, $encoding); + fclose($fd); + set_magic_quotes_runtime($magic_quotes); + + return $file_buffer; + } + + /** + * Encodes string to requested format. Returns an + * empty string on failure. + * @access private + * @return string + */ + function EncodeString ($str, $encoding = "base64") { + $encoded = ""; + switch(strtolower($encoding)) { + case "base64": + // chunk_split is found in PHP >= 3.0.6 + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case "7bit": + case "8bit": + $encoded = $this->FixEOL($str); + if (substr($encoded, -(strlen($this->LE))) != $this->LE) + $encoded .= $this->LE; + break; + case "binary": + $encoded = $str; + break; + case "quoted-printable": + $encoded = $this->EncodeQP($str); + break; + default: + $this->SetError($this->Lang("encoding") . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string to best of Q, B, quoted or none. + * @access private + * @return string + */ + function EncodeHeader ($str, $position = 'text') { + $x = 0; + + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + // Can't use addslashes as we don't know what value has magic_quotes_sybase. + $encoded = addcslashes($str, "\0..\37\177\\\""); + + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) + return ($encoded); + else + return ("\"$encoded\""); + } + $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + case 'comment': + $x = preg_match_all('/[()"]/', $str, $matches); + // Fall-through + case 'text': + default: + $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($x == 0) + return ($str); + + $maxlen = 75 - 7 - strlen($this->CharSet); + // Try to select the encoding which should produce the shortest output + if (strlen($str)/3 < $x) { + $encoding = 'B'; + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } else { + $encoding = 'Q'; + $encoded = $this->EncodeQ($str, $position); + $encoded = $this->WrapText($encoded, $maxlen, true); + $encoded = str_replace("=".$this->LE, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Encode string to quoted-printable. + * @access private + * @return string + */ + function EncodeQP ($str) { + $encoded = $this->FixEOL($str); + if (substr($encoded, -(strlen($this->LE))) != $this->LE) + $encoded .= $this->LE; + + // Replace every high ascii, control and = characters + $encoded = preg_replace('/([\000-\010\013\014\016-\037\075\177-\377])/e', + "'='.sprintf('%02X', ord('\\1'))", $encoded); + // Replace every spaces and vtiger_tabs when it's the last character on a line + $encoded = preg_replace("/([\011\040])".$this->LE."/e", + "'='.sprintf('%02X', ord('\\1')).'".$this->LE."'", $encoded); + + // Maximum line length of 76 characters before CRLF (74 + space + '=') + $encoded = $this->WrapText($encoded, 74, true); + + return $encoded; + } + + /** + * Encode string to q encoding. + * @access private + * @return string + */ + function EncodeQ ($str, $position = "text") { + // There should not be any EOL in the string + $encoded = preg_replace("[\r\n]", "", $str); + + switch (strtolower($position)) { + case "phrase": + $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); + break; + case "comment": + $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); + case "text": + default: + // Replace every high ascii, control =, ? and _ characters + $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', + "'='.sprintf('%02X', ord('\\1'))", $encoded); + break; + } + + // Replace every spaces to _ (more readable than =20) + $encoded = str_replace(" ", "_", $encoded); + + return $encoded; + } + + /** + * Adds a string or binary attachment (non-filesystem) to the list. + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return void + */ + function AddStringAttachment($string, $filename, $encoding = "base64", + $type = "application/octet-stream") { + // Append to $attachment array + $cur = count($this->attachment); + $this->attachment[$cur][0] = $string; + $this->attachment[$cur][1] = $filename; + $this->attachment[$cur][2] = $filename; + $this->attachment[$cur][3] = $encoding; + $this->attachment[$cur][4] = $type; + $this->attachment[$cur][5] = true; // isString + $this->attachment[$cur][6] = "attachment"; + $this->attachment[$cur][7] = 0; + } + + /** + * Adds an embedded attachment. This can include images, sounds, and + * just about any other document. Make sure to set the $type to an + * image type. For JPEG images use "image/jpeg" and for GIF images + * use "image/gif". + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment. Use this to identify + * the Id for accessing the image in an HTML form. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + function AddEmbeddedImage($path, $cid, $name = "", $encoding = "base64", + $type = "application/octet-stream") { + + if(!@is_file($path)) + { + $this->SetError($this->Lang("file_access") . $path); + return false; + } + + $filename = basename($path); + if($name == "") + $name = $filename; + + // Append to $attachment array + $cur = count($this->attachment); + $this->attachment[$cur][0] = $path; + $this->attachment[$cur][1] = $filename; + $this->attachment[$cur][2] = $name; + $this->attachment[$cur][3] = $encoding; + $this->attachment[$cur][4] = $type; + $this->attachment[$cur][5] = false; // isStringAttachment + $this->attachment[$cur][6] = "inline"; + $this->attachment[$cur][7] = $cid; + + return true; + } + + /** + * Returns true if an inline attachment is present. + * @access private + * @return bool + */ + function InlineImageExists() { + $result = false; + for($i = 0; $i < count($this->attachment); $i++) + { + if($this->attachment[$i][6] == "inline") + { + $result = true; + break; + } + } + + return $result; + } + + ///////////////////////////////////////////////// + // MESSAGE RESET METHODS + ///////////////////////////////////////////////// + + /** + * Clears all recipients assigned in the TO array. Returns void. + * @return void + */ + function ClearAddresses() { + $this->to = array(); + } + + /** + * Clears all recipients assigned in the CC array. Returns void. + * @return void + */ + function ClearCCs() { + $this->cc = array(); + } + + /** + * Clears all recipients assigned in the BCC array. Returns void. + * @return void + */ + function ClearBCCs() { + $this->bcc = array(); + } + + /** + * Clears all recipients assigned in the ReplyTo array. Returns void. + * @return void + */ + function ClearReplyTos() { + $this->ReplyTo = array(); + } + + /** + * Clears all recipients assigned in the TO, CC and BCC + * array. Returns void. + * @return void + */ + function ClearAllRecipients() { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + } + + /** + * Clears all previously set vtiger_filesystem, string, and binary + * vtiger_attachments. Returns void. + * @return void + */ + function ClearAttachments() { + $this->attachment = array(); + } + + /** + * Clears all custom vtiger_headers. Returns void. + * @return void + */ + function ClearCustomHeaders() { + $this->CustomHeader = array(); + } + + + ///////////////////////////////////////////////// + // MISCELLANEOUS METHODS + ///////////////////////////////////////////////// + + /** + * Adds the error message to the error container. + * Returns void. + * @access private + * @return void + */ + function SetError($msg) { + $this->error_count++; + $this->ErrorInfo = $msg; + } + + /** + * Returns the proper RFC 822 formatted date. + * @access private + * @return string + */ + function RFCDate() { + $tz = date("Z"); + $tzs = ($tz < 0) ? "-" : "+"; + $tz = abs($tz); + $tz = ($tz/3600)*100 + ($tz%3600)/60; + $result = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz); + + return $result; + } + + /** + * Returns the appropriate server variable. Should work with both + * PHP 4.1.0+ as well as older versions. Returns an empty string + * if nothing is found. + * @access private + * @return mixed + */ + function ServerVar($varName) { + global $HTTP_SERVER_VARS; + global $HTTP_ENV_VARS; + + if(!isset($_SERVER)) + { + $_SERVER = $HTTP_SERVER_VARS; + if(!isset($_SERVER["REMOTE_ADDR"])) + $_SERVER = $HTTP_ENV_VARS; // must be Apache + } + + if(isset($_SERVER[$varName])) + return $_SERVER[$varName]; + else + return ""; + } + + /** + * Returns the server hostname or 'localhost.localdomain' if unknown. + * @access private + * @return string + */ + function ServerHostname() { + if ($this->Hostname != "") + $result = $this->Hostname; + elseif ($this->ServerVar('SERVER_NAME') != "") + $result = $this->ServerVar('SERVER_NAME'); + else + $result = "localhost.localdomain"; + + return $result; + } + + /** + * Returns a message in the appropriate language. + * @access private + * @return string + */ + function Lang($key) { + require_once('config.inc.php'); + global $default_language; + if(count($this->language) < 1) + $this->SetLanguage($default_language); + + if(isset($this->language[$key])) + return $this->language[$key]; + else + return "Language string failed to load: " . $key; + } + + /** + * Returns true if an error occurred. + * @return bool + */ + function IsError() { + return ($this->error_count > 0); + } + + /** + * Changes every end of line from CR or LF to CRLF. + * @access private + * @return string + */ + function FixEOL($str) { + $str = str_replace("\r\n", "\n", $str); + $str = str_replace("\r", "\n", $str); + $str = str_replace("\n", $this->LE, $str); + return $str; + } + + /** + * Adds a custom header. + * @return void + */ + function AddCustomHeader($custom_header) { + $this->CustomHeader[] = explode(":", $custom_header, 2); + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Emails/class.smtp.php b/oss/vtiger/trunk/modules/Emails/class.smtp.php new file mode 100644 index 00000000..abba3404 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/class.smtp.php @@ -0,0 +1,1050 @@ +smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } + + /************************************************************* + * CONNECTION FUNCTIONS * + ***********************************************************/ + + /** + * Connect to the server specified on the port specified. + * If the port is not specified use the default SMTP_PORT. + * If tval is specified then a connection will try and be + * established with the server for that number of seconds. + * If tval is not specified the default is 30 seconds to + * try on the connection. + * + * SMTP CODE SUCCESS: 220 + * SMTP CODE FAILURE: 421 + * @access public + * @return bool + */ + function Connect($host,$port=0,$tval=30) { + # set the error val to null so there is no confusion + $this->error = null; + + # make sure we are __not__ connected + if($this->connected()) { + # ok we are connected! what should we do? + # for now we will just give an error saying we + # are already connected + $this->error = + array("error" => "Already connected to a server"); + return false; + } + + if(empty($port)) { + $port = $this->SMTP_PORT; + } + + #connect to the smtp server + if(!@$this->smtp_conn = fsockopen($host, # the host of the server + $port, # the port to use + $errno, # error number if any + $errstr, # error message if any + $tval)) # give up after ? secs + { + //echo '
Could Not connect to Mail Server

'; + return false; + } + + # verify we connected properly + if(empty($this->smtp_conn)) { + $this->error = array("error" => "Failed to connect to server", + "errno" => $errno, + "errstr" => $errstr); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": $errstr ($errno)" . $this->CRLF; + } + return false; + } + + # sometimes the SMTP server takes a little longer to respond + # so we will give it a longer timeout for the first read + // Windows still does not have support for this timeout function + if(substr(PHP_OS, 0, 3) != "WIN") + socket_set_timeout($this->smtp_conn, $tval, 0); + + # get any vtiger_announcement stuff + $announce = $this->get_lines(); + + # set the timeout of any socket functions at 1/10 of a second + //if(function_exists("socket_set_timeout")) + // socket_set_timeout($this->smtp_conn, 0, 100000); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $announce; + } + + return true; + } + + /** + * Performs SMTP authentication. Must be run after running the + * Hello() method. Returns true if successfully authenticated. + * @access public + * @return bool + */ + function Authenticate($username, $password) { + // Start authentication + fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "AUTH not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + // Send encoded username + fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "Username not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + // Send encoded password + fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 235) { + $this->error = + array("error" => "Password not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + return true; + } + + /** + * Returns true if connected to a server otherwise false + * @access private + * @return bool + */ + function Connected() { + if(!empty($this->smtp_conn)) { + $sock_status = socket_get_status($this->smtp_conn); + if($sock_status["eof"]) { + # hmm this is an odd situation... the socket is + # valid but we aren't connected anymore + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE:" . $this->CRLF . + "EOF caught while checking if connected"; + } + $this->Close(); + return false; + } + return true; # everything looks good + } + return false; + } + + /** + * Closes the socket and cleans up the state of the class. + * It is not considered good to use this function without + * first trying to use QUIT. + * @access public + * @return void + */ + function Close() { + $this->error = null; # so there is no confusion + $this->helo_rply = null; + if(!empty($this->smtp_conn)) { + # close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } + } + + + /*************************************************************** + * SMTP COMMANDS * + *************************************************************/ + + /** + * Issues a data command and sends the msg_data to the server + * finializing the mail transaction. $msg_data is the message + * that is to be send with the vtiger_headers. Each header needs to be + * on a single line followed by a with the message vtiger_headers + * and the message body being seperated by and additional . + * + * Implements rfc 821: DATA + * + * SMTP CODE INTERMEDIATE: 354 + * [data] + * . + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 552,554,451,452 + * SMTP CODE FAILURE: 451,554 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + function Data($msg_data) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Data() without being connected"); + return false; + } + + fputs($this->smtp_conn,"DATA" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 354) { + $this->error = + array("error" => "DATA command not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + # the server is ready to accept data! + # according to rfc 821 we should not send more than 1000 + # including the CRLF + # characters on a single line so we will break the data up + # into lines by \r and/or \n then if needed we will break + # each of those into smaller lines to fit within the limit. + # in addition we will be looking for lines that start with + # a period '.' and append and additional period '.' to that + # line. NOTE: this does not count towards are limit. + + # normalize the line breaks so we know the explode works + $msg_data = str_replace("\r\n","\n",$msg_data); + $msg_data = str_replace("\r","\n",$msg_data); + $lines = explode("\n",$msg_data); + + # we need to find a good way to determine is vtiger_headers are + # in the msg_data or if it is a straight msg body + # currently I'm assuming rfc 822 definitions of msg vtiger_headers + # and if the first vtiger_field of the first line (':' sperated) + # does not contain a space then it _should_ be a header + # and we can process all lines before a blank "" line as + # vtiger_headers. + $field = substr($lines[0],0,strpos($lines[0],":")); + $in_headers = false; + if(!empty($field) && !strstr($field," ")) { + $in_headers = true; + } + + $max_line_length = 998; # used below; set here for ease in change + + while(list(,$line) = @each($lines)) { + $lines_out = null; + if($line == "" && $in_headers) { + $in_headers = false; + } + # ok we need to break this line up into several + # smaller lines + while(strlen($line) > $max_line_length) { + $pos = strrpos(substr($line,0,$max_line_length)," "); + + # Patch to fix DOS attack + if(!$pos) { + $pos = $max_line_length - 1; + } + + $lines_out[] = substr($line,0,$pos); + $line = substr($line,$pos + 1); + # if we are processing vtiger_headers we need to + # add a LWSP-char to the front of the new line + # rfc 822 on long msg vtiger_headers + if($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + # now send the lines to the server + while(list(,$line_out) = @each($lines_out)) { + if(strlen($line_out) > 0) + { + if(substr($line_out, 0, 1) == ".") { + $line_out = "." . $line_out; + } + } + fputs($this->smtp_conn,$line_out . $this->CRLF); + } + } + + # ok all the message data has been sent so lets get this + # over with aleady + fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "DATA not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Expand takes the name and asks the server to list all the + * people who are members of the _list_. Expand will return + * back and array of the result or false if an error occurs. + * Each value in the array returned has the format of: + * [ ] + * The definition of is defined in rfc 821 + * + * Implements rfc 821: EXPN + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 550 + * SMTP CODE ERROR : 500,501,502,504,421 + * @access public + * @return string array + */ + function Expand($name) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Expand() without being connected"); + return false; + } + + fputs($this->smtp_conn,"EXPN " . $name . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "EXPN not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + # parse the reply and place in our array to return to user + $entries = explode($this->CRLF,$rply); + while(list(,$l) = @each($entries)) { + $list[] = substr($l,4); + } + + return $list; + } + + /** + * Sends the HELO command to the smtp server. + * This makes sure that we and the server are in + * the same known state. + * + * Implements from rfc 821: HELO + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 501, 504, 421 + * @access public + * @return bool + */ + function Hello($host="") { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Hello() without being connected"); + return false; + } + + # if a hostname for the HELO wasn't specified determine + # a suitable one to send + if(empty($host)) { + # we need to determine some sort of appopiate default + # to send to the server + $host = "localhost"; + } + + // Send extended hello first (RFC 2821) + if(!$this->SendHello("EHLO", $host)) + { + if(!$this->SendHello("HELO", $host)) + return false; + } + + return true; + } + + /** + * Sends a HELO/EHLO command. + * @access private + * @return bool + */ + function SendHello($hello, $host) { + fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER: " . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => $hello . " not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + $this->helo_rply = $rply; + + return true; + } + + /** + * Gets help information on the keyword specified. If the keyword + * is not specified then returns generic help, ussually contianing + * A list of keywords that help is available on. This function + * returns the results back to the user. It is up to the user to + * handle the returned data. If an error occurs then false is + * returned with $this->error set appropiately. + * + * Implements rfc 821: HELP [ ] + * + * SMTP CODE SUCCESS: 211,214 + * SMTP CODE ERROR : 500,501,502,504,421 + * @access public + * @return string + */ + function Help($keyword="") { + $this->error = null; # to avoid confusion + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Help() without being connected"); + return false; + } + + $extra = ""; + if(!empty($keyword)) { + $extra = " " . $keyword; + } + + fputs($this->smtp_conn,"HELP" . $extra . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 211 && $code != 214) { + $this->error = + array("error" => "HELP not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + return $rply; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. + * + * Implements rfc 821: MAIL FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,421 + * @access public + * @return bool + */ + function Mail($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Mail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "MAIL not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Sends the command NOOP to the SMTP server. + * + * Implements from rfc 821: NOOP + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 421 + * @access public + * @return bool + */ + function Noop() { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Noop() without being connected"); + return false; + } + + fputs($this->smtp_conn,"NOOP" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "NOOP not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Sends the quit command to the server and then closes the socket + * if there is no error or the $close_on_error argument is true. + * + * Implements from rfc 821: QUIT + * + * SMTP CODE SUCCESS: 221 + * SMTP CODE ERROR : 500 + * @access public + * @return bool + */ + function Quit($close_on_error=true) { + $this->error = null; # so there is no confusion + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Quit() without being connected"); + return false; + } + + # send the quit command to the server + fputs($this->smtp_conn,"quit" . $this->CRLF); + + # get any good-bye messages + $byemsg = $this->get_lines(); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $byemsg; + } + + $rval = true; + $e = null; + + $code = substr($byemsg,0,3); + if($code != 221) { + # use e as a tmp var cause Close will overwrite $this->error + $e = array("error" => "SMTP server rejected quit command", + "smtp_code" => $code, + "smtp_rply" => substr($byemsg,4)); + $rval = false; + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $e["error"] . ": " . + $byemsg . $this->CRLF; + } + } + + if(empty($e) || $close_on_error) { + $this->Close(); + } + + return $rval; + } + + /** + * Sends the command RCPT to the SMTP server with the TO: argument of $to. + * Returns true if the recipient was accepted false if it was rejected. + * + * Implements from rfc 821: RCPT TO: + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,552,553,450,451,452 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + function Recipient($to) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Recipient() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250 && $code != 251) { + $this->error = + array("error" => "RCPT not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Sends the RSET command to abort and transaction that is + * currently in progress. Returns true if successful false + * otherwise. + * + * Implements rfc 821: RSET + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500,501,504,421 + * @access public + * @return bool + */ + function Reset() { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Reset() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RSET" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "RSET failed", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the vtiger_users terminal if they are logged + * in. + * + * Implements rfc 821: SEND FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + function Send($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Send() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SEND FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "SEND not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the vtiger_users terminal if they are logged + * in and send them an email. + * + * Implements rfc 821: SAML FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + function SendAndMail($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called SendAndMail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "SAML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the vtiger_users terminal if they are logged + * in or mail it to them if they are not. + * + * Implements rfc 821: SOML FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + function SendOrMail($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called SendOrMail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SOML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "SOML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * This is an optional command for SMTP that this class does not + * support. This method is here to make the RFC821 Definition + * complete for this class and __may__ be implimented in the future + * + * Implements from rfc 821: TURN + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 502 + * SMTP CODE ERROR : 500, 503 + * @access public + * @return bool + */ + function Turn() { + $this->error = array("error" => "This method, TURN, of the SMTP ". + "is not implemented"); + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF; + } + return false; + } + + /** + * Verifies that the name is recognized by the server. + * Returns false if the name could not be verified otherwise + * the response from the server is returned. + * + * Implements rfc 821: VRFY + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,553 + * SMTP CODE ERROR : 500,501,502,421 + * @access public + * @return int + */ + function Verify($name) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Verify() without being connected"); + return false; + } + + fputs($this->smtp_conn,"VRFY " . $name . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250 && $code != 251) { + $this->error = + array("error" => "VRFY failed on name '$name'", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return $rply; + } + + /******************************************************************* + * INTERNAL FUNCTIONS * + ******************************************************************/ + + /** + * Read in as many lines as possible + * either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access private + * @return string + */ + function get_lines() { + $data = ""; + while($str = fgets($this->smtp_conn,515)) { + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data was \"$data\"" . + $this->CRLF; + echo "SMTP -> get_lines(): \$str is \"$str\"" . + $this->CRLF; + } + $data .= $str; + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF; + } + # if the 4th character is a space then we are done reading + # so just break the loop + if(substr($str,3,1) == " ") { break; } + } + return $data; + } + +} + + + ?> diff --git a/oss/vtiger/trunk/modules/Emails/gotodownload.php b/oss/vtiger/trunk/modules/Emails/gotodownload.php new file mode 100644 index 00000000..e6340089 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/gotodownload.php @@ -0,0 +1,82 @@ +parameters[0]->value; + $strFileType = strrev(substr(strrev($strFileName),0,4)); + $fileContent = imap_fetchbody($mbox,$msgno,$file+2); +} + +/** Function to download the File + * @param string $strFileType - File Type + * @param string $strFileName - File Name + * @param string $fileContents- File contents +**/ +function downloadFile($strFileType,$strFileName,$fileContent) +{ + $ContentType = "application/octet-stream"; + + if ($strFileType == ".asf") + $ContentType = "video/x-ms-asf"; + if ($strFileType == ".avi") + $ContentType = "video/avi"; + if ($strFileType == ".doc") + $ContentType = "application/msword"; + if ($strFileType == ".zip") + $ContentType = "application/zip"; + if ($strFileType == ".xls") + $ContentType = "application/vnd.ms-excel"; + if ($strFileType == ".gif") + $ContentType = "image/gif"; + if ($strFileType == ".jpg" || $strFileType == "jpeg") + $ContentType = "image/jpeg"; + if ($strFileType == ".wav") + $ContentType = "audio/wav"; + if ($strFileType == ".mp3") + $ContentType = "audio/mpeg3"; + if ($strFileType == ".mpg" || $strFileType == "mpeg") + $ContentType = "video/mpeg"; + if ($strFileType == ".rtf") + $ContentType = "application/rtf"; + if ($strFileType == ".htm" || $strFileType == "html") + $ContentType = "text/html"; + if ($strFileType == ".xml") + $ContentType = "text/xml"; + if ($strFileType == ".xsl") + $ContentType = "text/xsl"; + if ($strFileType == ".css") + $ContentType = "text/css"; + if ($strFileType == ".php") + $ContentType = "text/php"; + if ($strFileType == ".asp") + $ContentType = "text/asp"; + if ($strFileType == ".pdf") + $ContentType = "application/pdf"; + + header ("Content-Type: $ContentType"); + header("Cache-Control: private"); + header("Content-Description: PHP Generated Data"); + header ("Content-Disposition: attachment; filename=$strFileName"); + echo imap_base64($fileContent); + #echo base64_decode($fileContent); +} +?> diff --git a/oss/vtiger/trunk/modules/Emails/index.php b/oss/vtiger/trunk/modules/Emails/index.php new file mode 100644 index 00000000..0c3a5ef8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/index.php @@ -0,0 +1,31 @@ +'.$mod_strings['LBL_MAIL_CONNECT_ERROR_INFO'].'

'; +} + +include ('modules/Emails/ListView.php'); + +?> diff --git a/oss/vtiger/trunk/modules/Emails/language/en_us.lang.php b/oss/vtiger/trunk/modules/Emails/language/en_us.lang.php new file mode 100644 index 00000000..4b84eafb --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/language/en_us.lang.php @@ -0,0 +1,183 @@ +'General Information', + +'LBL_MODULE_NAME'=>'Email', +'LBL_MODULE_TITLE'=>'Email: Home', +'LBL_SEARCH_FORM_TITLE'=>'Email Search', +'LBL_LIST_FORM_TITLE'=>'Email List', +'LBL_NEW_FORM_TITLE'=>'Track Email', + +'LBL_LIST_SUBJECT'=>'Subject', +'LBL_LIST_CONTACT'=>'Contact', +'LBL_LIST_RELATED_TO'=>'Related to', +'LBL_LIST_DATE'=>'Date Sent', +'LBL_LIST_TIME'=>'Time Sent', + +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", +'LBL_DATE_SENT'=>'Date Sent:', +'LBL_DATE_AND_TIME'=>'Date & Time Sent:', +'LBL_DATE'=>'Date Sent:', +'LBL_TIME'=>'Time Sent:', +'LBL_SUBJECT'=>'Subject:', +'LBL_BODY'=>'Body:', +'LBL_CONTACT_NAME'=>' Contact Name: ', +'LBL_EMAIL'=>'Email:', +'LBL_DETAILVIEW_EMAIL'=>'E-Mail', +'LBL_COLON'=>':', +'LBL_CHK_MAIL'=>'Check Mail', +'LBL_COMPOSE'=>'Compose', +//Single change for 5.0.3 +'LBL_SETTINGS'=>'Incoming Mail Server Settings', +'LBL_EMAIL_FOLDERS'=>'Email Folders', +'LBL_INBOX'=>'Inbox', +'LBL_SENT_MAILS'=>'Sent Mails', +'LBL_TRASH'=>'Trash', +'LBL_JUNK_MAILS'=>'Junk Mails', +'LBL_TO_LEADS'=>'To Leads', +'LBL_TO_CONTACTS'=>'To Contacts', +'LBL_TO_ACCOUNTS'=>'To Accounts', +'LBL_MY_MAILS'=>'My Mails', +'LBL_QUAL_CONTACT'=>'Qualified Mails (As Contacts)', +'LBL_MAILS'=>'Mails', +'LBL_QUALIFY_BUTTON'=>'Qualify', +'LBL_REPLY_BUTTON'=>'Reply', +'LBL_FORWARD_BUTTON'=>'Forward', +'LBL_DOWNLOAD_ATTCH_BUTTON'=>'Download Attachments', +'LBL_FROM'=>'From :', +'LBL_CC'=>'Cc :', +'LBL_BCC'=>'Bcc :', + +'NTC_REMOVE_INVITEE'=>'Are you sure you want to remove this recipient from the email?', +'LBL_INVITEE'=>'Recipients', + +// Added Fields +// Contacts-SubPanelViewContactsAndUsers.php +'LBL_BULK_MAILS'=>'Bulk Mails', +'LBL_ATTACHMENT'=>'Attachment', +'LBL_UPLOAD'=>'Upload', +'LBL_FILE_NAME'=>'File Name', +'LBL_SEND'=>'Send', + +'LBL_EMAIL_TEMPLATES'=>'Email Templates', +'LBL_TEMPLATE_NAME'=>'Template Name', +'LBL_DESCRIPTION'=>'Description', +'LBL_EMAIL_TEMPLATES_LIST'=>'Email Templates List', +'LBL_EMAIL_INFORMATION'=>'Email Information', + + + + +//for v4 release added +'LBL_NEW_LEAD'=>'New Lead', +'LBL_LEAD_TITLE'=>'Leads', + +'LBL_NEW_PRODUCT'=>'New Product', +'LBL_PRODUCT_TITLE'=>'Products', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', +'LBL_NEW_ACCOUNT'=>'New Account', +'LBL_ACCOUNT_TITLE'=>'Accounts', + +// Added vtiger_fields after vtiger4 - Beta +'LBL_USER_TITLE'=>'Users', +'LBL_NEW_USER'=>'New User', + +// Added for 4 GA +'LBL_TOOL_FORM_TITLE'=>'Email Tools', +//Added for 4GA +'Date & Time Sent'=>'Date & Time Sent', +'Sales Enity Module'=>'Sales Enity Module', +'Related To'=>'Related To', +'Assigned To'=>'Assigned To', +'Subject'=>'Subject', +'Attachment'=>'Attachment', +'Description'=>'Description', +'Time Start'=>'Time Start', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', + +'MESSAGE_CHECK_MAIL_SERVER_NAME'=>'Please Check the Mail Server Name...', +'MESSAGE_CHECK_MAIL_ID'=>'Please Check the Email Id of "Assigned To" User...', +'MESSAGE_MAIL_HAS_SENT_TO_USERS'=>'Mail has been sent to the following User(s) :', +'MESSAGE_MAIL_HAS_SENT_TO_CONTACTS'=>'Mail has been sent to the following Contact(s) :', +'MESSAGE_MAIL_ID_IS_INCORRECT'=>'Mail Id is incorrect. Please Check this Mail Id...', +'MESSAGE_ADD_USER_OR_CONTACT'=>'Please Add any User(s) or Contact(s)...', +'MESSAGE_MAIL_SENT_SUCCESSFULLY'=>' Mail(s) sent successfully!', + +// Added for web mail post 4.0.1 release +'LBL_FETCH_WEBMAIL'=>'Fetch Web Mail', +//Added for 4.2 Release -- CustomView +'LBL_ALL'=>'All', +'MESSAGE_CONTACT_NOT_WANT_MAIL'=>'This Contact does not want to receive mails.', +'LBL_WEBMAILS_TITLE'=>'WebMails', +'LBL_EMAILS_TITLE'=>'Email', +'LBL_MAIL_CONNECT_ERROR_INFO'=>'Error connecting mail server!
Check in My Accounts->List Mail Server -> List Mail Account', +'LBL_ALLMAILS'=>'All Mails', +'LBL_TO_USERS'=>'To Users', +'LBL_TO'=>'To:', +'LBL_IN_SUBJECT'=>'in Subject', +'LBL_IN_SENDER'=>'in Sender', +'LBL_IN_SUBJECT_OR_SENDER'=>'in Subject or Sender', +'SELECT_EMAIL'=>'Select Email IDs', +'Sender'=>'Sender', +'LBL_CONFIGURE_MAIL_SETTINGS'=>'Your Incoming Mail Server is not configured', +'LBL_MAILSELECT_INFO1'=>'The following Email ID types are associated to the selected', +'LBL_MAILSELECT_INFO2'=>'Select the Email ID types to which,the email should be sent', +'LBL_MULTIPLE'=>'Multiple', +'LBL_COMPOSE_EMAIL'=>'Compose E-Mail', +'LBL_VTIGER_EMAIL_CLIENT'=>'vtiger Webmail Client', + +//Added for 5.0.3 +'TITLE_VTIGERCRM_MAIL'=>'vtigerCRM Mail', +'TITLE_COMPOSE_MAIL'=>'Compose Mail', + +'MESSAGE_MAIL_COULD_NOT_BE_SEND'=>'Mail could not be sent to the assigned to user.', +'MESSAGE_PLEASE_CHECK_ASSIGNED_USER_EMAILID'=>'Please check the assigned to user email id...', +'MESSAGE_PLEASE_CHECK_THE_FROM_MAILID'=>'Please check the from email id', +'MESSAGE_MAIL_COULD_NOT_BE_SEND_TO_THIS_EMAILID'=>'Mail could not be sent to this email id', +'PLEASE_CHECK_THIS_EMAILID'=>'Please check this mail id...', +'LBL_CC_EMAIL_ERROR'=>'Your cc mailid is not proper', +'LBL_BCC_EMAIL_ERROR'=>'Your bcc mailid is not proper', +'LBL_NO_RCPTS_EMAIL_ERROR'=>'No recepients specified', +'LBL_CONF_MAILSERVER_ERROR'=>'Please configure your outgoing mailserver under Settings ---> Outgoing Server link', +'LBL_VTIGER_EMAIL_CLIENT'=>'vtiger Webmail Client', +'LBL_MAILSELECT_INFO3'=>'You don\'t have permission to view email id(s) of the selected Record(s).', +//Added for script alerts +'FEATURE_AVAILABLE_INFO' => 'This feature is currently only available for Microsoft Internet Explorer 5.5+ users\n\nWait f +or an update!', +'DOWNLOAD_CONFIRAMATION' => 'Do you want to download the file ?', +'LBL_PLEASE_ATTACH' => 'Please give a valid file to attach and try again!', +'LBL_KINDLY_UPLOAD' => 'Please configure upload_tmp_dir variable in php.ini file.', +'LBL_EXCEED_MAX' => 'Sorry, the uploaded file exceeds the maximum filesize limit. Please try a file smaller than ', +'LBL_BYTES' => ' bytes', +'LBL_CHECK_USER_MAILID' => 'Please check the current user mailid.It should be a valid mailid to send Emails', + +// Added/Updated for vtiger CRM 5.0.4 +'Activity Type'=>'Activity Type', +'LBL_MAILSELECT_INFO'=>'has the following Email IDs associated.Please Select the Email IDs to which,the mail should be sent', +'LBL_NO_RECORDS' => 'No Records Found', +'LBL_PRINT_EMAIL'=> 'Print', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Emails/language/phpmailer.lang-en_us.php b/oss/vtiger/trunk/modules/Emails/language/phpmailer.lang-en_us.php new file mode 100644 index 00000000..7b09c424 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/language/phpmailer.lang-en_us.php @@ -0,0 +1,31 @@ +.'; +$PHPMAILER_LANG["file_access"] = 'Could not access file: '; +$PHPMAILER_LANG["file_open"] = 'File Error: Could not open file: '; +$PHPMAILER_LANG["encoding"] = 'Unknown encoding: '; +?> diff --git a/oss/vtiger/trunk/modules/Emails/language/phpmailer.lang-zh_cn.php b/oss/vtiger/trunk/modules/Emails/language/phpmailer.lang-zh_cn.php new file mode 100644 index 00000000..7b09c424 --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/language/phpmailer.lang-zh_cn.php @@ -0,0 +1,31 @@ +.'; +$PHPMAILER_LANG["file_access"] = 'Could not access file: '; +$PHPMAILER_LANG["file_open"] = 'File Error: Could not open file: '; +$PHPMAILER_LANG["encoding"] = 'Unknown encoding: '; +?> diff --git a/oss/vtiger/trunk/modules/Emails/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Emails/language/zh_cn.lang.php new file mode 100644 index 00000000..6fa50c4b --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/language/zh_cn.lang.php @@ -0,0 +1,184 @@ + '一般信息', + + 'LBL_MODULE_NAME' => '邮件', + 'LBL_MODULE_TITLE' => '邮件: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻邮件', + 'LBL_LIST_FORM_TITLE' => '邮件列表', + 'LBL_NEW_FORM_TITLE' => '追踪邮件', + + 'LBL_LIST_SUBJECT' => '标题', + 'LBL_LIST_CONTACT' => '联系人', + 'LBL_LIST_RELATED_TO' => '相关人事', + 'LBL_LIST_DATE' => '寄出日期', + 'LBL_LIST_TIME' => '寄出时间', + + 'ERR_DELETE_RECORD' => '必须有记录编号才能删除该笔账号.', + 'LBL_DATE_SENT' => '寄出日期:', + 'LBL_DATE_AND_TIME' => '寄出日期 & 时间:', + 'LBL_DATE' => '寄出日期:', + 'LBL_TIME' => '寄出时间:', + 'LBL_SUBJECT' => '标题:', + 'LBL_BODY' => '邮件内容:', + 'LBL_CONTACT_NAME' => '联系人名称: ', +'LBL_EMAIL' => '邮件:', +'LBL_DETAILVIEW_EMAIL'=>'邮件', +'LBL_COLON'=>':', +'LBL_CHK_MAIL'=>'检查邮件', +'LBL_COMPOSE'=>'新邮件', +//Single change for 5.0.3 +'LBL_SETTINGS'=>'邮件服务器设置', +'LBL_EMAIL_FOLDERS'=>'邮件数据夹', +'LBL_INBOX' => '收件夹', +'LBL_SENT_MAILS'=>'邮件备份', +'LBL_TRASH' => '垃圾桶', + 'LBL_JUNK_MAILS' => '广告邮件', + 'LBL_TO_LEADS' => '转为准客户', + 'LBL_TO_CONTACTS' => '转为联系人', + 'LBL_TO_ACCOUNTS' => '转为客户', + 'LBL_MY_MAILS' => '我的邮件', + 'LBL_QUAL_CONTACT' => '已转换邮件(转为联系人)', + 'LBL_MAILS' => '邮件', + 'LBL_QUALIFY_BUTTON' => '转换', + 'LBL_REPLY_BUTTON' => '回应', + 'LBL_FORWARD_BUTTON' => '转寄', + 'LBL_DOWNLOAD_ATTCH_BUTTON' => '下载附加档案', + 'LBL_FROM' => '寄件人:', + 'LBL_CC' => '副本:', + 'LBL_BCC' => '密件副本:', + + 'NTC_REMOVE_INVITEE' => '您确定要移除这封来信?', +'LBL_INVITEE'=>'接收者', + +// Added Fields +// Contacts-SubPanelViewContactsAndUsers.php + 'LBL_BULK_MAILS' => '大量寄信', + 'LBL_ATTACHMENT' => '附件', +'LBL_UPLOAD' => '上传', + 'LBL_FILE_NAME' => '文件名称', + 'LBL_SEND' => '寄出', + +'LBL_EMAIL_TEMPLATES' => '邮件样版', + 'LBL_TEMPLATE_NAME' => '样版名称', + 'LBL_DESCRIPTION' => '描述', + 'LBL_EMAIL_TEMPLATES_LIST' => '邮件样版列表', + 'LBL_EMAIL_INFORMATION' => '邮件信息', + + + + +//for v4 release added + 'LBL_NEW_LEAD' => '新增潜在客户', + 'LBL_LEAD_TITLE' => '潜在客户', + + 'LBL_NEW_PRODUCT' => '新增商品', + 'LBL_PRODUCT_TITLE' => '商品', + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_CONTACT_TITLE' => '联系人', + 'LBL_NEW_ACCOUNT' => '新增公司', + 'LBL_ACCOUNT_TITLE' => '公司', + +// Added vtiger_fields after vtiger4 - Beta +'LBL_USER_TITLE' => '使用者', + 'LBL_NEW_USER' => '新增使用者', + +// Added for 4 GA + 'LBL_TOOL_FORM_TITLE' => '邮件编辑器', +//Added for 4GA +'Date & Time Sent' => '寄出日期 & 时间', + 'Sales Enity Module' => '客服模块', + + 'Related To' => '相关人事', + 'Assigned To' => '负责人', + 'Subject' => '标题', + 'Attachment' => '附件', + 'Description' => '描述', + 'Time Start' => '开始时间', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + + 'MESSAGE_CHECK_MAIL_SERVER_NAME' => '请检查电子邮件服务器名称...', + 'MESSAGE_CHECK_MAIL_ID' => '请检查负责人的信箱编号...', + 'MESSAGE_MAIL_HAS_SENT_TO_USERS' => '邮件将会寄出给指定的使用者:', + 'MESSAGE_MAIL_HAS_SENT_TO_CONTACTS' => '邮件将会寄出给指定的联系人:', + 'MESSAGE_MAIL_ID_IS_INCORRECT' => '邮件格式不正确. 请检查这封邮件的Id...', + 'MESSAGE_ADD_USER_OR_CONTACT' => '请新增其它位使用者或联系人...', + 'MESSAGE_MAIL_SENT_SUCCESSFULLY' => ' 邮件已顺利寄出!', + +// Added for web mail post 4.0.1 release + 'LBL_FETCH_WEBMAIL' => '取得网页邮件', +//Added for 4.2 Release -- CustomView + 'LBL_ALL' => '全部', + 'MESSAGE_CONTACT_NOT_WANT_MAIL' => '这个联系人不想要收到电子邮件', + 'LBL_WEBMAILS_TITLE' => '网页邮件', + 'LBL_EMAILS_TITLE' => '电子邮件', + 'LBL_MAIL_CONNECT_ERROR_INFO' => '联机到邮件服务器时发生错误,检查我的账号=>邮件服务器列表=>邮件账号', + 'LBL_ALLMAILS' => '所有邮件', + 'LBL_TO_USERS' => '给使用者', + 'LBL_TO' => '收件人:', +'LBL_IN_SUBJECT' => '主旨', + 'LBL_IN_SENDER' => '寄件人', + 'LBL_IN_SUBJECT_OR_SENDER' => '主旨或寄件人', + 'SELECT_EMAIL' => '选择邮件编号', + 'Sender' => '寄件人', + 'LBL_CONFIGURE_MAIL_SETTINGS' => '您的收件邮件服务器还没设定', + 'LBL_MAILSELECT_INFO' => '有下面相关邮件编号,请选择要寄送的邮件编号', + 'LBL_MAILSELECT_INFO1' => '下面的邮件编号与选择的项目有关', + 'LBL_MAILSELECT_INFO2' => '选择要寄送的邮件编号类型', + 'LBL_MULTIPLE' => '多选', + 'LBL_COMPOSE_EMAIL' => '发送邮件', + 'LBL_VTIGER_EMAIL_CLIENT'=>'vtiger Webmail 客户', + +//Added for 5.0.3 +'TITLE_VTIGERCRM_MAIL'=>'vtigerCRM 邮件', +'TITLE_COMPOSE_MAIL'=>'组成邮件', + +'MESSAGE_MAIL_COULD_NOT_BE_SEND'=>'邮件不能寄发到被分配的用户.', +'MESSAGE_PLEASE_CHECK_ASSIGNED_USER_EMAILID'=>'请检查被分配的用户电子邮件id...', +'MESSAGE_PLEASE_CHECK_THE_FROM_MAILID'=>'请检查电子邮件id', +'MESSAGE_MAIL_COULD_NOT_BE_SEND_TO_THIS_EMAILID'=>'邮件不能寄发到这电子邮件id', +'PLEASE_CHECK_THIS_EMAILID'=>'请检查这邮件id...', +'LBL_CC_EMAIL_ERROR'=>'您的CC邮件ID不是适当的', +'LBL_BCC_EMAIL_ERROR'=>'您的BCC邮件ID不是适当的', +'LBL_NO_RCPTS_EMAIL_ERROR'=>'没有指定移植对象', +'LBL_CONF_MAILSERVER_ERROR'=>'请设置您外部的邮件服务器 ---> 外出的服务器链接', +'LBL_VTIGER_EMAIL_CLIENT'=>'vtiger Webmail 客户', +'LBL_MAILSELECT_INFO3'=>'您不能查看选择记录的邮件ID.', +'LBL_NO_RECORDS' => '这个文件夹没有记录', +//Added for script alerts +'FEATURE_AVAILABLE_INFO' => '这个特点只支持Microsoft Internet Explorer 5.5+或更高!', +'DOWNLOAD_CONFIRAMATION' => '您想要下载文件 ?', +'LBL_PLEASE_ATTACH' => '请再尝试附上一个合法的文件', +'LBL_KINDLY_UPLOAD' => '请配置 upload_tmp_dir variable in php.ini file.', +'LBL_EXCEED_MAX' => '抱歉, 上传的文件超出最大值极限。请尝试一个小文件 ', +'LBL_BYTES' => ' 字节', +'LBL_CHECK_USER_MAILID' => '请检查当前用户的电邮ID是否正确', + +// Added/Updated for vtiger CRM 5.0.4 +'Activity Type'=>'任务类型', +'LBL_MAILSELECT_INFO'=>'has the following Email IDs associated.Please Select the Email IDs to which,the mail should be sent', +'LBL_NO_RECORDS' => 'No Records Found', +'LBL_PRINT_EMAIL'=> 'Print', +); + +?> diff --git a/oss/vtiger/trunk/modules/Emails/mail.php b/oss/vtiger/trunk/modules/Emails/mail.php new file mode 100644 index 00000000..e8bbcf2e --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/mail.php @@ -0,0 +1,519 @@ +println("To id => '".$to_email."'\nSubject ==>'".$subject."'\nContents ==> '".$contents."'"); + + //Get the email id of assigned_to user -- pass the value and name, name must be "user_name" or "id"(field names of vtiger_users vtiger_table) + //$to_email = getUserEmailId('id',$assigned_user_id); + + //if module is HelpDesk then from_email will come based on support email id + if($from_email == '')//$module != 'HelpDesk') + $from_email = getUserEmailId('user_name',$from_name); + if($module != "Calendar") + $contents = addSignature($contents,$from_name); + + $mail = new PHPMailer(); + + setMailerProperties($mail,$subject,$contents,$from_email,$from_name,trim($to_email,","),$attachment,$emailid,$module,$logo); + setCCAddress($mail,'cc',$cc); + setCCAddress($mail,'bcc',$bcc); + + // vtmailscanner customization: If Support Reply to is defined use it. + global $HELPDESK_SUPPORT_EMAIL_REPLY_ID; + if($HELPDESK_SUPPORT_EMAIL_REPLY_ID && $HELPDESK_SUPPORT_EMAIL_ID != $HELPDESK_SUPPORT_EMAIL_REPLY_ID) { + $mail->AddReplyTo($HELPDESK_SUPPORT_EMAIL_REPLY_ID); + } + // END + + // Fix: Return immediately if Outgoing server not configured + if(empty($mail->Host)) { + return 0; + } + // END + + $mail_status = MailSend($mail); + + if($mail_status != 1) + { + $mail_error = getMailError($mail,$mail_status,$mailto); + } + else + { + $mail_error = $mail_status; + } + + return $mail_error; +} + +/** Function to get the user Email id based on column name and column value + * $name -- column name of the vtiger_users vtiger_table + * $val -- column value + */ +function getUserEmailId($name,$val) +{ + global $adb; + $adb->println("Inside the function getUserEmailId. --- ".$name." = '".$val."'"); + if($val != '') + { + //$sql = "select email1, email2, yahoo_id from vtiger_users where ".$name." = '".$val."'"; + //done to resolve the PHP5 specific behaviour + $sql = "SELECT email1, email2, yahoo_id from vtiger_users WHERE status='Active' AND ". $adb->sql_escape_string($name)." = ?"; + $res = $adb->pquery($sql, array($val)); + $email = $adb->query_result($res,0,'email1'); + if($email == '') + { + $email = $adb->query_result($res,0,'email2'); + if($email == '') + { + $email = $adb->query_result($res,0,'yahoo_id'); + } + } + $adb->println("Email id is selected => '".$email."'"); + return $email; + } + else + { + $adb->println("User id is empty. so return value is ''"); + return ''; + } +} + +/** Funtion to add the user's signature with the content passed + * $contents -- where we want to add the signature + * $fromname -- which user's signature will be added to the contents + */ +function addSignature($contents, $fromname) +{ + global $adb; + $adb->println("Inside the function addSignature"); + + $sign = nl2br($adb->query_result($adb->pquery("select signature from vtiger_users where user_name=?", array($fromname)),0,"signature")); + if($sign != '') + { + $contents .= '

'.$sign; + $adb->println("Signature is added with the body => '.".$sign."'"); + } + else + { + $adb->println("Signature is empty for the user => '".$fromname."'"); + } + return $contents; +} + +/** Function to set all the Mailer properties + * $mail -- reference of the mail object + * $subject -- subject of the email you want to send + * $contents -- body of the email you want to send + * $from_email -- from email id which will be displayed in the mail + * $from_name -- from name which will be displayed in the mail + * $to_email -- to email address -- This can be an email in a single string, a comma separated + * list of emails or an array of email addresses + * $attachment -- whether we want to attach the currently selected file or all vtiger_files. + [values = current,all] - optional + * $emailid -- id of the email object which will be used to get the vtiger_attachments - optional + */ +function setMailerProperties($mail,$subject,$contents,$from_email,$from_name,$to_email,$attachment='',$emailid='',$module='',$logo='') +{ + global $adb; + $adb->println("Inside the function setMailerProperties"); + if($module == "Support" || $logo ==1) + $mail->AddEmbeddedImage('themes/images/logo_mail.jpg', 'logo', 'logo.jpg',"base64","image/jpg"); + + $mail->Subject = $subject; + $mail->Body = $contents; + //$mail->Body = html_entity_decode(nl2br($contents)); //if we get html tags in mail then we will use this line + $mail->AltBody = strip_tags(preg_replace(array("/

/i","/
/i","/
/i"),array("\n","\n","\n"),$contents)); + + $mail->IsSMTP(); //set mailer to use SMTP + //$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server + + setMailServerProperties($mail); + + //Handle the from name and email for HelpDesk + $mail->From = $from_email; + $rs = $adb->pquery("select first_name,last_name from vtiger_users where user_name=?", array($from_name)); + if($adb->num_rows($rs) > 0) + $from_name = $adb->query_result($rs,0,"first_name")." ".$adb->query_result($rs,0,"last_name"); + + $mail->FromName = decode_html($from_name); + + if($to_email != '') + { + if(is_array($to_email)) { + for($j=0,$num=count($to_email);$j<$num;$j++) { + $mail->addAddress($to_email[$j]); + } + } else { + $_tmp = explode(",",$to_email); + for($j=0,$num=count($_tmp);$j<$num;$j++) { + $mail->addAddress($_tmp[$j]); + } + } + } + + $mail->AddReplyTo($from_email); + $mail->WordWrap = 50; + + //If we want to add the currently selected file only then we will use the following function + if($attachment == 'current' && $emailid != '') + { + if (isset($_REQUEST['filename_hidden'])) { + $file_name = $_REQUEST['filename_hidden']; + } else { + $file_name = $_FILES['filename']['name']; + } + addAttachment($mail,$file_name,$emailid); + } + + //This will add all the vtiger_files which are related to this record or email + if($attachment == 'all' && $emailid != '') + { + addAllAttachments($mail,$emailid); + } + + $mail->IsHTML(true); // set email format to HTML + + return; +} + +/** Function to set the Mail Server Properties in the object passed + * $mail -- reference of the mailobject + */ +function setMailServerProperties($mail) +{ + global $adb; + $adb->println("Inside the function setMailServerProperties"); + + $res = $adb->pquery("select * from vtiger_systems where server_type=?", array('email')); + if(isset($_REQUEST['server'])) + $server = $_REQUEST['server']; + else + $server = $adb->query_result($res,0,'server'); + if(isset($_REQUEST['server_username'])) + $username = $_REQUEST['server_username']; + else + $username = $adb->query_result($res,0,'server_username'); + if(isset($_REQUEST['server_password'])) + $password = $_REQUEST['server_password']; + else + $password = $adb->query_result($res,0,'server_password'); + // Prasad: First time read smtp_auth from the request + if(isset($_REQUEST['smtp_auth'])) + { + $smtp_auth = $_REQUEST['smtp_auth']; + if($smtp_auth == 'on') + $smtp_auth = 'true'; + } + else if (isset($_REQUEST['module']) && $_REQUEST['module'] == 'Settings' && (!isset($_REQUEST['smtp_auth']))) + { + //added to avoid issue while editing the values in the outgoing mail server. + $smtp_auth = 'false'; + } + else + $smtp_auth = $adb->query_result($res,0,'smtp_auth'); + + $adb->println("Mail server name,username & password => '".$server."','".$username."','".$password."'"); + if($smtp_auth == "true"){ + $mail->SMTPAuth = true; // turn on SMTP authentication + } + $mail->Host = $server; // specify main and backup server + $mail->Username = $username ; // SMTP username + $mail->Password = $password ; // SMTP password + + return; +} + +/** Function to add the file as attachment with the mail object + * $mail -- reference of the mail object + * $filename -- filename which is going to added with the mail + * $record -- id of the record - optional + */ +function addAttachment($mail,$filename,$record) +{ + global $adb, $root_directory; + $adb->println("Inside the function addAttachment"); + $adb->println("The file name is => '".$filename."'"); + + //This is the file which has been selected in Email EditView + if(is_file($filename) && $filename != '') + { + $mail->AddAttachment($root_directory."test/upload/".$filename); + } +} + +/** Function to add all the vtiger_files as attachment with the mail object + * $mail -- reference of the mail object + * $record -- email id ie., record id which is used to get the all vtiger_attachments from database + */ +function addAllAttachments($mail,$record) +{ + global $adb,$log, $root_directory; + $adb->println("Inside the function addAllAttachments"); + + //Retrieve the vtiger_files from database where avoid the file which has been currently selected + $sql = "select vtiger_attachments.* from vtiger_attachments inner join vtiger_seattachmentsrel on vtiger_attachments.attachmentsid = vtiger_seattachmentsrel.attachmentsid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_attachments.attachmentsid where vtiger_crmentity.deleted=0 and vtiger_seattachmentsrel.crmid=?"; + $res = $adb->pquery($sql, array($record)); + $count = $adb->num_rows($res); + + for($i=0;$i<$count;$i++) + { + $fileid = $adb->query_result($res,$i,'attachmentsid'); + $filename = decode_html($adb->query_result($res,$i,'name')); + $filepath = $adb->query_result($res,$i,'path'); + $filewithpath = $root_directory.$filepath.$fileid."_".$filename; + + //if the file is exist in test/upload directory then we will add directly + //else get the contents of the file and write it as a file and then attach (this will occur when we unlink the file) + if(is_file($filewithpath)) + { + $mail->AddAttachment($filewithpath,$filename); + } + } +} + +/** Function to set the CC or BCC addresses in the mail + * $mail -- reference of the mail object + * $cc_mod -- mode to set the address ie., cc or bcc + * $cc_val -- addresss with comma seperated to set as CC or BCC in the mail + */ +function setCCAddress($mail,$cc_mod,$cc_val) +{ + global $adb; + $adb->println("Inside the functin setCCAddress"); + + if($cc_mod == 'cc') + $method = 'AddCC'; + if($cc_mod == 'bcc') + $method = 'AddBCC'; + if($cc_val != '') + { + $ccmail = explode(",",trim($cc_val,",")); + for($i=0;$i"); + } + if($ccmail[$i] != '') + $mail->$method($addr,$cc_name); + } + } +} + +/** Function to send the mail which will be called after set all the mail object values + * $mail -- reference of the mail object + */ +function MailSend($mail) +{ + global $log; + $log->info("Inside of Send Mail function."); + if(!$mail->Send()) + { + $log->debug("Error in Mail Sending : Error log = '".$mail->ErrorInfo."'"); + return $mail->ErrorInfo; + } + else + { + $log->info("Mail has been sent from the vtigerCRM system : Status : '".$mail->ErrorInfo."'"); + return 1; + } +} + +/** Function to get the Parent email id from HelpDesk to send the details about the ticket via email + * $returnmodule -- Parent module value. Contact or Account for send email about the ticket details + * $parentid -- id of the parent ie., contact or vtiger_account + */ +function getParentMailId($parentmodule,$parentid) +{ + global $adb; + $adb->println("Inside the function getParentMailId. \n parent module and id => ".$parentmodule."&".$parentid); + + if($parentmodule == 'Contacts') + { + $tablename = 'vtiger_contactdetails'; + $idname = 'contactid'; + $first_email = 'email'; + $second_email = 'yahooid'; + } + if($parentmodule == 'Accounts') + { + $tablename = 'vtiger_account'; + $idname = 'accountid'; + $first_email = 'email1'; + $second_email = 'email2'; + } + if($parentid != '') + { + //$query = 'select * from '.$tablename.' where '.$idname.' = '.$parentid; + $query = 'select * from '.$tablename.' where '. $idname.' = ?'; + $res = $adb->pquery($query, array($parentid)); + $mailid = $adb->query_result($res,0,$first_email); + $mailid2 = $adb->query_result($res,0,$second_email); + } + if($mailid == '' && $mailid2 != '') + $mailid = $mailid2; + + return $mailid; +} + +/** Function to parse and get the mail error + * $mail -- reference of the mail object + * $mail_status -- status of the mail which is sent or not + * $to -- the email address to whom we sent the mail and failes + * return -- Mail error occured during the mail sending process + */ +function getMailError($mail,$mail_status,$to) +{ + //Error types in class.phpmailer.php + /* + provide_address, mailer_not_supported, execute, instantiate, file_access, file_open, encoding, data_not_accepted, authenticate, + connect_host, recipients_failed, from_failed + */ + + global $adb; + $adb->println("Inside the function getMailError"); + + $msg = array_search($mail_status,$mail->language); + $adb->println("Error message ==> ".$msg); + + if($msg == 'connect_host') + { + $error_msg = $msg; + } + elseif(strstr($msg,'from_failed')) + { + $error_msg = $msg; + } + elseif(strstr($msg,'recipients_failed')) + { + $error_msg = $msg; + } + else + { + $adb->println("Mail error is not as connect_host or from_failed or recipients_failed"); + //$error_msg = $msg; + } + + $adb->println("return error => ".$error_msg); + return $error_msg; +} + +/** Function to get the mail status string (string of sent mail status) + * $mail_status_str -- concatenated string with all the error messages with &&& seperation + * return - the error status as a encoded string + */ +function getMailErrorString($mail_status_str) +{ + global $adb; + $adb->println("Inside getMailErrorString function.\nMail status string ==> ".$mail_status_str); + + $mail_status_str = trim($mail_status_str,"&&&"); + $mail_status_array = explode("&&&",$mail_status_str); + $adb->println("All Mail status ==>\n".$mail_status_str."\n"); + + foreach($mail_status_array as $key => $val) + { + $list = explode("=",$val); + $adb->println("Mail id & status ==> ".$list[0]." = ".$list[1]); + if($list[1] == 0) + { + $mail_error_str .= $list[0]."=".$list[1]."&&&"; + } + } + $adb->println("Mail error string => '".$mail_error_str."'"); + if($mail_error_str != '') + { + $mail_error_str = 'mail_error='.base64_encode($mail_error_str); + } + return $mail_error_str; +} + +/** Function to parse the error string + * $mail_error_str -- base64 encoded string which contains the mail sending errors as concatenated with &&& + * return - Error message to display + */ +function parseEmailErrorString($mail_error_str) +{ + //TODO -- we can modify this function for better email error handling in future + global $adb, $mod_strings; + $adb->println("Inside the parseEmailErrorString function.\n encoded mail error string ==> ".$mail_error_str); + + $mail_error = base64_decode($mail_error_str); + $adb->println("Original error string => ".$mail_error); + $mail_status = explode("&&&",trim($mail_error,"&&&")); + foreach($mail_status as $key => $val) + { + $status_str = explode("=",$val); + $adb->println('Mail id => "'.$status_str[0].'".........status => "'.$status_str[1].'"'); + if($status_str[1] != 1 && $status_str[1] != '') + { + $adb->println("Error in mail sending"); + if($status_str[1] == 'connect_host') + { + $adb->println("if part - Mail sever is not configured"); + $errorstr .= '
'.$mod_strings['MESSAGE_CHECK_MAIL_SERVER_NAME'].''; + break; + } + elseif($status_str[1] == '0') + { + $adb->println("first elseif part - status will be 0 which is the case of assigned to vtiger_users's email is empty."); + $errorstr .= '
'.$mod_strings['MESSAGE_MAIL_COULD_NOT_BE_SEND'].' '.$mod_strings['MESSAGE_PLEASE_CHECK_FROM_THE_MAILID'].''; + //Added to display the message about the CC && BCC mail sending status + if($status_str[0] == 'cc_success') + { + $cc_msg = 'But the mail has been sent to CC & BCC addresses.'; + $errorstr .= '
'.$cc_msg.''; + } + } + elseif(strstr($status_str[1],'from_failed')) + { + $adb->println("second elseif part - from email id is failed."); + $from = explode('from_failed',$status_str[1]); + $errorstr .= "
".$mod_strings['MESSAGE_PLEASE_CHECK_THE_FROM_MAILID']." '".$from[1]."'"; + } + else + { + $adb->println("else part - mail send process failed due to the following reason."); + $errorstr .= "
".$mod_strings['MESSAGE_MAIL_COULD_NOT_BE_SEND_TO_THIS_EMAILID']." '".$status_str[0]."'. ".$mod_strings['PLEASE_CHECK_THIS_EMAILID'].""; + } + } + } + $adb->println("Return Error string => ".$errorstr); + return $errorstr; +} +?> diff --git a/oss/vtiger/trunk/modules/Emails/mailSelect.php b/oss/vtiger/trunk/modules/Emails/mailSelect.php new file mode 100644 index 00000000..5bb49f3a --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/mailSelect.php @@ -0,0 +1,109 @@ +id; + +$querystr = "select fieldid, fieldname, fieldlabel, columnname from vtiger_field where tabid=? and uitype=13 and vtiger_field.presence in (0,2)"; +$res=$adb->pquery($querystr, array(getTabid($pmodule))); +$numrows = $adb->num_rows($res); +$returnvalue = Array(); +for($i = 0; $i < $numrows; $i++) +{ + $value = Array(); + $fieldname = $adb->query_result($res,$i,"fieldname"); + $permit = getFieldVisibilityPermission($pmodule, $userid, $fieldname); + if($permit == '0') + { + $temp=$adb->query_result($res,$i,'columnname'); + $columnlists [] = $temp; + $fieldid=$adb->query_result($res,$i,'fieldid'); + $fieldlabel =$adb->query_result($res,$i,'fieldlabel'); + $value[] = getTranslatedString($fieldlabel); + $returnvalue [$fieldid]= $value; + } +} + +if($single_record && count($columnlists) > 0) +{ + $count = 0; + $val_cnt = 0; + switch($pmodule) + { + case 'Accounts': + $query = 'select accountname,'.implode(",",$columnlists).' from vtiger_account left join vtiger_accountscf on vtiger_accountscf.accountid = vtiger_account.accountid where vtiger_account.accountid = ?'; + $result=$adb->pquery($query, array($idlist)); + foreach($columnlists as $columnname) + { + $acc_eval = $adb->query_result($result,0,$columnname); + $field_value[$count++] = $acc_eval; + if($acc_eval != "") $val_cnt++; + + } + $entity_name = $adb->query_result($result,0,'accountname'); + break; + case 'Leads': + $query = 'select concat(firstname," ",lastname) as leadname,'.implode(",",$columnlists).' from vtiger_leaddetails left join vtiger_leadscf on vtiger_leadscf.leadid = vtiger_leaddetails.leadid where vtiger_leaddetails.leadid = ?'; + $result=$adb->pquery($query, array($idlist)); + foreach($columnlists as $columnname) + { + $lead_eval = $adb->query_result($result,0,$columnname); + $field_value[$count++] = $lead_eval; + if($lead_eval != "") $val_cnt++; + } + $entity_name = $adb->query_result($result,0,'leadname'); + break; + case 'Contacts': + $query = 'select concat(firstname," ",lastname) as contactname,'.implode(",",$columnlists).' from vtiger_contactdetails left join vtiger_contactscf on vtiger_contactscf.contactid = vtiger_contactdetails.contactid where vtiger_contactdetails.contactid = ?'; + $result=$adb->pquery($query, array($idlist)); + foreach($columnlists as $columnname) + { + $con_eval = $adb->query_result($result,0,$columnname); + $field_value[$count++] = $con_eval; + if($con_eval != "") $val_cnt++; + } + $entity_name = $adb->query_result($result,0,'contactname'); + break; + } +} +$smarty->assign('PERMIT',$permit); +$smarty->assign('ENTITY_NAME',$entity_name); +$smarty->assign('ONE_RECORD',$single_record); +$smarty->assign('MAILDATA',$field_value); +$smarty->assign('MAILINFO',$returnvalue); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("IDLIST", $idlist); +$smarty->assign("APP", $app_strings); +$smarty->assign("FROM_MODULE", $pmodule); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +if($single_record && count($columnlists) > 0 && $val_cnt > 0) + $smarty->display("SelectEmail.tpl"); +else if(!$single_record && count($columnlists) > 0) + $smarty->display("SelectEmail.tpl"); +else if($single_record && $val_cnt == 0) + echo "No Mail Ids"; +else + echo "Mail Ids not permitted"; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/mailsend.php b/oss/vtiger/trunk/modules/Emails/mailsend.php new file mode 100644 index 00000000..bcc14e7f --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/mailsend.php @@ -0,0 +1,239 @@ +id;//$_REQUEST['record']; +} + + +$adb->println("\n\nMail Sending Process has been started."); +//This function call is used to send mail to the assigned to user. In this mail CC and BCC addresses will be added. +if($_REQUEST['assigntype' == 'T'] && $_REQUEST['assigned_group_id']!='') +{ + $grp_obj = new GetGroupUsers(); + $grp_obj->getAllUsersInGroup($_REQUEST['assigned_group_id']); + $users_list = constructList($grp_obj->group_users,'INTEGER'); + if (count($users_list) > 0) { + $sql = "select first_name, last_name, email1, email2, yahoo_id from vtiger_users where id in (". generateQuestionMarks($users_list) .")"; + $params = array($users_list); + } else { + $sql = "select first_name, last_name, email1, email2, yahoo_id from vtiger_users"; + $params = array(); + } + $res = $adb->pquery($sql, $params); + $user_email = ''; + while ($user_info = $adb->fetch_array($res)) + { + $email = $user_info['email1']; + if($email == '' || $email == 'NULL') + { + $email = $user_info['email2']; + if($email == '' || $email == 'NULL') + { + $email = $user_info['yahoo_id']; + } + } + if($user_email=='') + $user_email .= $user_info['first_name']." ".$user_info['last_name']."<".$email.">"; + else + $user_email .= ",".$user_info['first_name']." ".$user_info['last_name']."<".$email.">"; + $email=''; + } + $to_email = $user_email; +} +else +{ + $to_email = getUserEmailId('id',$focus->column_fields["assigned_user_id"]); +} +$cc = $_REQUEST['ccmail']; +$bcc = $_REQUEST['bccmail']; +if($to_email == '' && $cc == '' && $bcc == '') +{ + $adb->println("Mail Error : send_mail function not called because To email id of assigned to user, CC and BCC are empty"); + $mail_status_str = "'".$to_email."'=0&&&"; + $errorheader1 = 1; +} +else +{ + $query1 = "select email1 from vtiger_users where id =?"; + $res1 = $adb->pquery($query1, array($current_user->id)); + $val = $adb->query_result($res1,0,"email1"); +// $mail_status = send_mail('Emails',$to_email,$current_user->user_name,'',$_REQUEST['subject'],$_REQUEST['description'],$cc,$bcc,'all',$focus->id); + + $query = 'update vtiger_emaildetails set email_flag ="SENT",from_email =? where emailid=?'; + $adb->pquery($query, array($val, $focus->id)); + //set the errorheader1 to 1 if the mail has not been sent to the assigned to user + if($mail_status != 1)//when mail send fails + { + $errorheader1 = 1; + $mail_status_str = $to_email."=".$mail_status."&&&"; + } + elseif($mail_status == 1 && $to_email == '')//Mail send success only for CC and BCC but the 'to' email is empty + { + $adb->pquery($query, array($val, $focus->id)); + $errorheader1 = 1; + $mail_status_str = "cc_success=0&&&"; + } + else + { + $mail_status_str = $to_email."=".$mail_status."&&&"; + } +} + + +//Added code from mysendmail.php which is contributed by Raju(rdhital) +$parentid= $_REQUEST['parent_id']; +$myids=explode("|",$parentid); +$all_to_emailids = Array(); +$from_name = $current_user->user_name; +$from_address = $current_user->column_fields['email1']; + +for ($i=0;$i<(count($myids)-1);$i++) +{ + $realid=explode("@",$myids[$i]); + $nemail=count($realid); + $mycrmid=$realid[0]; + if($realid[1] == -1) + { + //handle the mail send to vtiger_users + $emailadd = $adb->query_result($adb->pquery("select email1 from vtiger_users where id=?", array($mycrmid)),0,'email1'); + $pmodule = 'Users'; + $description = getMergedDescription($_REQUEST['description'],$mycrmid,$pmodule); + $mail_status = send_mail('Emails',$emailadd,$from_name,$from_address,$_REQUEST['subject'],$description,'','','all',$focus->id); + $all_to_emailids []= $emailadd; + $mail_status_str .= $emailadd."=".$mail_status."&&&"; + } + else + { + //Send mail to vtiger_account or lead or contact based on their ids + $pmodule=getSalesEntityType($mycrmid); + for ($j=1;$j<$nemail;$j++) + { + $temp=$realid[$j]; + $myquery='Select columnname from vtiger_field where fieldid = ? and vtiger_field.presence in (0,2)'; + $fresult=$adb->pquery($myquery, array($temp)); + if ($pmodule=='Contacts') + { + require_once('modules/Contacts/Contacts.php'); + $myfocus = new Contacts(); + $myfocus->retrieve_entity_info($mycrmid,"Contacts"); + } + elseif ($pmodule=='Accounts') + { + require_once('modules/Accounts/Accounts.php'); + $myfocus = new Accounts(); + $myfocus->retrieve_entity_info($mycrmid,"Accounts"); + } + elseif ($pmodule=='Leads') + { + require_once('modules/Leads/Leads.php'); + $myfocus = new Leads(); + $myfocus->retrieve_entity_info($mycrmid,"Leads"); + } + elseif ($pmodule=='Vendors') + { + require_once('modules/Vendors/Vendors.php'); + $myfocus = new Vendors(); + $myfocus->retrieve_entity_info($mycrmid,"Vendors"); + } + else { + // vtlib customization: Enabling mail send from other modules + $myfocus = CRMEntity::getInstance($pmodule); + $myfocus->retrieve_entity_info($mycrmid, $pmodule); + // END + } + $fldname=$adb->query_result($fresult,0,"columnname"); + $emailadd=br2nl($myfocus->column_fields[$fldname]); + +//This is to convert the html encoded string to original html entities so that in mail description contents will be displayed correctly + //$focus->column_fields['description'] = from_html($focus->column_fields['description']); + + if($emailadd != '') + { + $description = getMergedDescription($_REQUEST['description'],$mycrmid,$pmodule); + //Email Open Tracking + global $site_URL, $application_unique_key; + $emailid = $focus->id; + $track_URL = "$site_URL/modules/Emails/TrackAccess.php?record=$mycrmid&mailid=$emailid&app_key=$application_unique_key"; + $description = "$description"; + // END + + $pos = strpos($description, '$logo$'); + if ($pos !== false) + { + + $description =str_replace('$logo$','',$description); + $logo=1; + } + if(isPermitted($pmodule,'DetailView',$mycrmid) == 'yes') + { + $mail_status = send_mail('Emails',$emailadd,$from_name,$from_address,$_REQUEST['subject'],$description,'','','all',$focus->id,$logo); + } + + $all_to_emailids []= $emailadd; + $mail_status_str .= $emailadd."=".$mail_status."&&&"; + //added to get remain the EditView page if an error occurs in mail sending + if($mail_status != 1) + { + $errorheader2 = 1; + } + } + } + } + +} +//Added to redirect the page to Emails/EditView if there is an error in mail sending +if($errorheader1 == 1 || $errorheader2 == 1) +{ + $returnset = 'return_module='.$returnmodule.'&return_action='.$returnaction.'&return_id='.vtlib_purify($_REQUEST['return_id']); + $returnmodule = 'Emails'; + $returnaction = 'EditView'; + //This condition is added to set the record(email) id when we click on send mail button after returning mail error + if($_REQUEST['mode'] == 'edit') + { + $returnid = $_REQUEST['record']; + } + else + { + $returnid = $_REQUEST['currentid']; + } +} +else +{ + global $adb; + $date_var = date('Ymd'); + $query = 'update vtiger_activity set date_start =? where activityid = ?'; + $adb->pquery($query, array($date_var, $returnid)); +} +//The following function call is used to parse and form a encoded error message and then pass to result page +$mail_error_str = getMailErrorString($mail_status_str); +$adb->println("Mail Sending Process has been finished.\n\n"); +if(isset($_REQUEST['popupaction']) && $_REQUEST['popupaction'] != '') +{ + /*this will fix #1211*/ + $inputs=""; + //$inputs=""; + echo $inputs; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/templates/testemailtemplateusage.php b/oss/vtiger/trunk/modules/Emails/templates/testemailtemplateusage.php new file mode 100644 index 00000000..e69de29b diff --git a/oss/vtiger/trunk/modules/Emails/templates/todel.txt b/oss/vtiger/trunk/modules/Emails/templates/todel.txt new file mode 100644 index 00000000..e69de29b diff --git a/oss/vtiger/trunk/modules/Emails/updateRelations.php b/oss/vtiger/trunk/modules/Emails/updateRelations.php new file mode 100644 index 00000000..14be6cbe --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/updateRelations.php @@ -0,0 +1,40 @@ +pquery($sql, array($id, $record)); + } +} +if(isset($_REQUEST['user_id']) && $_REQUEST['user_id'] != '') +{ + $record = $_REQUEST['record']; + $sql = "insert into vtiger_salesmanactivityrel values (?,?)"; + $adb->pquery($sql, array($_REQUEST["user_id"], $record)); +} + +header("Location: index.php?action=CallRelatedList&module=Emails&record=".vtlib_purify($record)); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Emails/webmailsend.php b/oss/vtiger/trunk/modules/Emails/webmailsend.php new file mode 100644 index 00000000..1c54392d --- /dev/null +++ b/oss/vtiger/trunk/modules/Emails/webmailsend.php @@ -0,0 +1,61 @@ +user_name; + $from_add = $current_user->column_fields['email1']; + } + else{ + $from_arr = explode('@',$_REQUEST['from_add']); + $from_name = $from_arr[0]; + $from_add = $_REQUEST['from_add']; + } +$mail_status = send_mail('Emails',$_REQUEST["parent_name"],$from_name,$from_add,$_REQUEST['subject'],$_REQUEST['description'],$_REQUEST["ccmail"],$_REQUEST["bccmail"],'all',$focus->id); + +$query = "update vtiger_emaildetails set email_flag ='SENT' where emailid=?"; +$adb->pquery($query, array($focus->id)); + +//set the errorheader1 to 1 if the mail has not been sent to the assigned to user +if($mail_status != 1) { //when mail send fails + $errorheader1 = 1; + $mail_status_str = $to_email."=".$mail_status."&&&"; + +} elseif($mail_status == 1 && $to_email == '') { //Mail send success only for CC and BCC but the 'to' email is empty + $adb->pquery($query, array($focus->id)); + $errorheader1 = 1; + $mail_status_str = "cc_success=0&&&"; +} else + $mail_status_str = $to_email."=".$mail_status."&&&"; + + + +//Added to redirect the page to Emails/EditView if there is an error in mail sending +if($errorheader1 == 1 || $errorheader2 == 1) +{ + $returnset = 'return_module='.$returnmodule.'&return_action='.$returnaction.'&return_id='.vtlib_purify($_REQUEST['return_id']); + $returnmodule = 'Emails'; + $returnaction = 'EditView'; + if($_REQUEST['mode'] == 'edit') + $returnid = $_REQUEST['record']; + else + $returnid = $_REQUEST['currentid']; +} + +//The following function call is used to parse and form a encoded error message and then pass to result page +$mail_error_str = getMailErrorString($mail_status_str); +$adb->println("Mail Sending Process has been finished.\n\n"); + +if(isset($_REQUEST['popupaction']) && $_REQUEST['popupaction'] != '') +{ + $inputs=""; + echo $inputs; +} +?> diff --git a/oss/vtiger/trunk/modules/Faq/CallRelatedList.php b/oss/vtiger/trunk/modules/Faq/CallRelatedList.php new file mode 100644 index 00000000..9303738c --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/CallRelatedList.php @@ -0,0 +1,77 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['question']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings; + global $currentModule; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array=getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("CATEGORY",$category); + + // 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 + + $smarty->assign("ID",$focus->id); + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$app_strings['Faq']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/CustomView.php b/oss/vtiger/trunk/modules/Faq/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Faq/Delete.php b/oss/vtiger/trunk/modules/Faq/Delete.php new file mode 100644 index 00000000..cc085145 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/Delete.php @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/DetailView.php b/oss/vtiger/trunk/modules/Faq/DetailView.php new file mode 100644 index 00000000..162ec74a --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/DetailView.php @@ -0,0 +1,117 @@ +retrieve_entity_info($_REQUEST['record'],"Faq"); + $focus->id = $_REQUEST['record']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Faq detail view"); +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); + +if(isset($focus->column_fields[question])) + $smarty->assign("NAME", $focus->column_fields[question]); + +$category = getParenttab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); +$smarty->assign("SINGLE_MOD",$currentModule); +$smarty->assign("MODULE",$currentModule); + +// 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 + +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); +if(isPermitted("Faq","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("Faq","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +$tabid = getTabid("Faq"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +//Added to display the Faq comments information +$smarty->assign("COMMENT_BLOCK",$focus->getFAQComments($_REQUEST['record'])); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} +if($singlepane_view == 'true') { + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("SinglePane_View", $singlepane_view); + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); +$smarty->display("DetailView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/DetailViewAjax.php b/oss/vtiger/trunk/modules/Faq/DetailViewAjax.php new file mode 100644 index 00000000..011acc4f --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/DetailViewAjax.php @@ -0,0 +1,56 @@ +retrieve_entity_info($crmid,"Faq"); + + //Added to avoid the comment save, when we edit other fields through ajax edit + if($fieldname != 'comments') + $modObj->column_fields['comments'] = ''; + + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Faq"); + if($modObj->id != "") + { + if($fieldname == "comments") + { + $comments = $modObj->getFAQComments($modObj->id); + echo ":#:SUCCESS".$comments; + } + else + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/EditView.php b/oss/vtiger/trunk/modules/Faq/EditView.php new file mode 100644 index 00000000..5fbd2e6c --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/EditView.php @@ -0,0 +1,141 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if(isset($_REQUEST['record'])) +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Faq"); +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $smarty->assign("BASBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS')); +} + +$smarty->assign("OP_MODE",$disp_view); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",$currentModule); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("ID", $focus->id); +if(isset($focus->column_fields[question])) + $smarty->assign("NAME", $focus->column_fields[question]); + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} + +if(isset($_REQUEST['return_module'])) $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else $smarty->assign("RETURN_MODULE","Faq"); +if(isset($_REQUEST['return_action'])) $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else $smarty->assign("RETURN_ACTION","index"); +if(isset($_REQUEST['return_id'])) $smarty->assign("RETURN_ID", vtlib_purify($_REQUEST['return_id'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + + +$tabid = getTabid("Faq"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + + $smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); + $smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); + $smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +if($_REQUEST['record'] != '') +{ + //Added to display the Faq comments information + $smarty->assign("COMMENT_BLOCK",$focus->getFAQComments($_REQUEST['record'])); +} +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 '
'. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +if($focus->mode == 'edit') + $smarty->display("salesEditView.tpl"); +else + $smarty->display("CreateView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/Faq.js b/oss/vtiger/trunk/modules/Faq/Faq.js new file mode 100644 index 00000000..7fa41f4a --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/Faq.js @@ -0,0 +1,21 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + +function clear_form(form) +{ + for (j = 0; j < form.elements.length; j++) + { + if (form.elements[j].type == 'text' || form.elements[j].type == 'select-one') + { + form.elements[j].value = ''; + } + } +} + diff --git a/oss/vtiger/trunk/modules/Faq/Faq.php b/oss/vtiger/trunk/modules/Faq/Faq.php new file mode 100644 index 00000000..936eba25 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/Faq.php @@ -0,0 +1,200 @@ +'crmid','vtiger_faq'=>'id','vtiger_faqcomments'=>'faqid'); + + var $entity_table = "vtiger_crmentity"; + + var $column_fields = Array(); + + var $sortby_fields = Array('question','category','id'); + + // This is the list of vtiger_fields that are in the lists. + var $list_fields = Array( + 'FAQ Id'=>Array('faq'=>'id'), + 'Question'=>Array('faq'=>'question'), + 'Category'=>Array('faq'=>'category'), + 'Product Name'=>Array('faq'=>'product_id'), + 'Created Time'=>Array('crmentity'=>'createdtime'), + 'Modified Time'=>Array('crmentity'=>'modifiedtime') + ); + + var $list_fields_name = Array( + 'FAQ Id'=>'', + 'Question'=>'question', + 'Category'=>'faqcategories', + 'Product Name'=>'product_id', + 'Created Time'=>'createdtime', + 'Modified Time'=>'modifiedtime' + ); + var $list_link_field= 'question'; + + var $search_fields = Array( + 'Account Name'=>Array('account'=>'accountname'), + 'City'=>Array('accountbillads'=>'bill_city'), + ); + + var $search_fields_name = Array( + 'Account Name'=>'accountname', + 'City'=>'bill_city', + ); + + //Added these variables which are used as default order by and sortorder in ListView + var $default_order_by = 'id'; + var $default_sort_order = 'DESC'; + + var $mandatory_fields = Array('question','faq_answer','createdtime' ,'modifiedtime'); + + /** Constructor which will set the column_fields in this object + */ + function Faq() { + $this->log =LoggerManager::getLogger('faq'); + $this->log->debug("Entering Faq() method ..."); + $this->db = PearDatabase::getInstance(); + $this->column_fields = getColumnFields('Faq'); + $this->log->debug("Exiting Faq method ..."); + } + + function save_module($module) + { + //Inserting into Faq comment table + $this->insertIntoFAQCommentTable('vtiger_faqcomments', $module); + + } + + + /** Function to insert values in vtiger_faqcomments table for the specified module, + * @param $table_name -- table name:: Type varchar + * @param $module -- module:: Type varchar + */ + function insertIntoFAQCommentTable($table_name, $module) + { + global $log; + $log->info("in insertIntoFAQCommentTable ".$table_name." module is ".$module); + global $adb; + + $current_time = $adb->formatDate(date('Y-m-d H:i:s'), true); + + if($this->column_fields['comments'] != '') + $comment = $this->column_fields['comments']; + else + $comment = $_REQUEST['comments']; + + if($comment != '') + { + $params = array('', $this->id, from_html($comment), $current_time); + $sql = "insert into vtiger_faqcomments values(?, ?, ?, ?)"; + $adb->pquery($sql, $params); + } + } + + + /** Function to get the list of comments for the given FAQ id + * @param int $faqid - FAQ id + * @return list $list - return the list of comments and comment informations as a html output where as these comments and comments informations will be formed in div tag. + **/ + function getFAQComments($faqid) + { + global $log, $default_charset; + $log->debug("Entering getFAQComments(".$faqid.") method ..."); + global $mod_strings; + $sql = "select * from vtiger_faqcomments where faqid=?"; + $result = $this->db->pquery($sql, array($faqid)); + $noofrows = $this->db->num_rows($result); + + //In ajax save we should not add this div + if($_REQUEST['action'] != 'FaqAjax') + { + $list .= '

'; + $enddiv = '
'; + } + + for($i=0;$i<$noofrows;$i++) + { + $comment = $this->db->query_result($result,$i,'comments'); + $createdtime = $this->db->query_result($result,$i,'createdtime'); + if($comment != '') + { + //this div is to display the comment + if($_REQUEST['action'] == 'FaqAjax') { + $comment = htmlentities($comment, ENT_QUOTES, $default_charset); + } + $list .= '
'.make_clickable(nl2br($comment)).'
'; + + //this div is to display the created time + $list .= '
'.$mod_strings['Created Time']; + $list .= ' : '.$createdtime.'
'; + } + } + + $list .= $enddiv; + + $log->debug("Exiting getFAQComments method ..."); + return $list; + } + + /* + * Function to get the primary query part of a report + * @param - $module Primary module name + * returns the query string formed on fetching the related data for report for primary module + */ + function generateReportsQuery($module){ + $moduletable = $this->table_name; + $moduleindex = $this->table_index; + + $query = "from $moduletable + inner join vtiger_crmentity on vtiger_crmentity.crmid=$moduletable.$moduleindex + left join vtiger_products as vtiger_products$module on vtiger_products$module.productid = vtiger_faq.product_id + left join vtiger_groups as vtiger_groups$module on vtiger_groups$module.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_users$module on vtiger_users$module.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid"; + return $query; + } + + /* + * Function to get the relation tables for related modules + * @param - $secmodule secondary module name + * returns the array with table names and fieldnames storing relations between module and this module + */ + function setRelationTables($secmodule){ + $rel_tables = array ( + "Documents" => array("vtiger_senotesrel"=>array("crmid","notesid"),"vtiger_faq"=>"id"), + ); + return $rel_tables[$secmodule]; + } +} +?> diff --git a/oss/vtiger/trunk/modules/Faq/FaqAjax.php b/oss/vtiger/trunk/modules/Faq/FaqAjax.php new file mode 100644 index 00000000..ce66087f --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/FaqAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Faq/ListFaq.php b/oss/vtiger/trunk/modules/Faq/ListFaq.php new file mode 100644 index 00000000..25ad43f2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/ListFaq.php @@ -0,0 +1,135 @@ +$title,'Header'=>$listview_header,'Entries'=>$listview_entries) where as listview_header and listview_entries are arrays of header and entity values which are returned from function getListViewHeader and getListViewEntries + */ +function getMyFaq($maxval,$calCnt) +{ + require_once("data/Tracker.php"); + require_once('modules/Faq/Faq.php'); + require_once('include/logging.php'); + require_once('include/ListView/ListView.php'); + require_once('include/utils/utils.php'); + require_once('modules/CustomView/CustomView.php'); + + global $current_language,$current_user,$list_max_entries_per_page,$theme,$adb; + $current_module_strings = return_module_language($current_language, 'Faq'); + + $log = LoggerManager::getLogger('faq_list'); + + $url_string = ''; + $sorder = ''; + $oCustomView = new CustomView("Faq"); + $customviewcombo_html = $oCustomView->getCustomViewCombo(); + if(isset($_REQUEST['viewname']) == false || $_REQUEST['viewname']=='') + { + if($oCustomView->setdefaultviewid != "") + { + $viewid = $oCustomView->setdefaultviewid; + }else + { + $viewid = "0"; + } + } + $focus = new Faq(); + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + //Retreive the list from Database + //<<<<<<<<>>>>>>>> + $date_var = date('Y-m-d'); + + $where = ' and vtiger_crmentity.smownerid='.$current_user->id.' and vtiger_faq.status <> \'Obsolete\' ORDER BY vtiger_crmentity.createdtime DESC'; + $query = getListQuery("Faq",$where); + + //<<<<<<<>>>>>>>> + + $query .= " LIMIT 0," . $adb->sql_escape_string($maxval); + + if($calCnt == 'calculateCnt') { + $list_result_rows = $adb->query(mkCountQuery($query)); + return $adb->query_result($list_result_rows, 0, 'count'); + } + + $list_result = $adb->query($query); + + //Retreiving the no of rows + $noofrows = $adb->num_rows($list_result); + + //Retreiving the start value from request + if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') + { + $start = vtlib_purify($_REQUEST['start']); + } + else + { + + $start = 1; + } + + //Retreive the Navigation array + $navigation_array = getNavigationValues($start, $noofrows, $list_max_entries_per_page); + + if ($navigation_array['start'] == 1) + { + if($noofrows != 0) + $start_rec = $navigation_array['start']; + else + $start_rec = 0; + if($noofrows > $list_max_entries_per_page) + { + $end_rec = $navigation_array['start'] + $list_max_entries_per_page - 1; + } + else + { + $end_rec = $noofrows; + } + + } + else + { + if($navigation_array['next'] > $list_max_entries_per_page) + { + $start_rec = $navigation_array['next'] - $list_max_entries_per_page; + $end_rec = $navigation_array['next'] - 1; + } + else + { + $start_rec = $navigation_array['prev'] + $list_max_entries_per_page; + $end_rec = $noofrows; + } + } + + + //Retreive the List View Table Header + $title=array('myFaqs.gif',$current_module_strings['LBL_MY_FAQ'],'home_myfaq'); + $listview_header = getListViewHeader($focus,"Faq",$url_string,$sorder,$order_by,"HomePage",$oCustomView); + $header = Array($listview_header[1],$listview_header[3]); + + $listview_entries = getListViewEntries($focus,"Faq",$list_result,$navigation_array,"HomePage","","EditView","Delete",$oCustomView); + foreach($listview_entries as $crmid=>$valuearray) + { + $entries[$crmid] = Array($valuearray[1],$valuearray[3]); + } + + $search_qry = "&query=true&Fields0=vtiger_faq.status&Condition0=isn&Srch_value0=Obsolete&searchtype=advance&search_cnt=1&matchtype=any"; + + $values=Array('ModuleName'=>'Faq','Title'=>$title,'Header'=>$header,'Entries'=>$entries,'search_qry'=>$search_qry); + if ( ($display_empty_home_blocks && $noofrows == 0 ) || ($noofrows>0) ) + return $values; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/ListView.php b/oss/vtiger/trunk/modules/Faq/ListView.php new file mode 100644 index 00000000..c599c3bf --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/ListView.php @@ -0,0 +1,263 @@ +initSortbyField('Faq'); +// END +$smarty = new vtigerCRM_Smarty; + +$other_text = Array(); + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +$url_string = ''; +//<<<>>>>>> +$oCustomView = new CustomView("Faq"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//<<<<>>>> + +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +if($_REQUEST['order_by'] != '') + $order_by = $adb->sql_escape_string($_REQUEST['order_by']); +else + $order_by = (($_SESSION['FAQ_ORDER_BY'] != '')?($_SESSION['FAQ_ORDER_BY']):($focus->default_order_by)); + +if($_REQUEST['sorder'] != '') + $sorder = $adb->sql_escape_string($_REQUEST['sorder']); +else + $sorder = (($_SESSION['FAQ_SORT_ORDER'] != '')?($_SESSION['FAQ_SORT_ORDER']):($focus->default_sort_order)); + +$_SESSION['FAQ_ORDER_BY'] = $order_by; +$_SESSION['FAQ_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + +if($viewid != 0) +{ + $CActionDtls = $oCustomView->getCustomActionDetails($viewid); +} +elseif($viewid ==0) +{ + echo "
"; + echo "
+ + + + + + + + + +
$app_strings[LBL_PERMISSION]
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + exit; +} + +if(isPermitted('Faq','Delete','') == 'yes') +$other_text ['del'] = $app_strings[LBL_MASS_DELETE]; + + +//Retreive the list from Database +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Faq"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Faq"); +}else +{ + $list_query = getListQuery("Faq"); +} + +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); +} +if(isset($where) && $where != '') +{ + $list_query .= ' and '.$where; +} + + +$view_script = ""; +if(isset($order_by) && $order_by != '') +{ + $tablename = getTableNameForField('Faq',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY '.$tablename.$order_by; + + $list_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; +} +//Constructing the list view + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("BUTTONS",$other_text); +$smarty->assign("CATEGORY",$category); +$smarty->assign("SINGLE_MOD",'Document'); + +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +//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); + +if($viewid !='') +$url_string .= "&viewname=".$viewid; + +//Retreive the List View Table Header +$listview_header = getListViewHeader($focus,"Faq",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search = getSearchListHeaderValues($focus,"Faq",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER",$listview_header_search); + +$listview_entries = getListViewEntries($focus,"Faq",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Faq","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','question','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("SINGLE_MOD" ,'Faq'); + +if(isPermitted('Faq','EditView','') == 'yes') { + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; +} +$smarty->assign("BUTTONS",$other_text); +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/ListViewPagging.php b/oss/vtiger/trunk/modules/Faq/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/MassEdit.php b/oss/vtiger/trunk/modules/Faq/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/MassEditSave.php b/oss/vtiger/trunk/modules/Faq/MassEditSave.php new file mode 100644 index 00000000..2c3d6e86 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/MassEditSave.php @@ -0,0 +1,71 @@ +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]); + } + } + // Avoiding comment update on ticket + $focus->column_fields['comments'] = ''; + $_REQUEST['comments'] = ''; + // END + $focus->save($currentModule); + } + } +} + +$parenttab = getParentTab(); +header("Location: index.php?module=$return_module&action=$return_action&parenttab=$parenttab$rstart"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/Save.php b/oss/vtiger/trunk/modules/Faq/Save.php new file mode 100644 index 00000000..320f42f9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/Save.php @@ -0,0 +1,54 @@ +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("Faq"); +$return_id = $focus->id; + +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Faq"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +$local_log->debug("Saved record with id of ".$return_id); + +header("Location: index.php?action=$return_action&module=$return_module&record=$return_id&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/Settings.php b/oss/vtiger/trunk/modules/Faq/Settings.php new file mode 100644 index 00000000..48a80c0b --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/Settings.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/TagCloud.php b/oss/vtiger/trunk/modules/Faq/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Faq/UnifiedSearch.php b/oss/vtiger/trunk/modules/Faq/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/index.php b/oss/vtiger/trunk/modules/Faq/index.php new file mode 100644 index 00000000..6bb2260c --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/index.php @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Faq/language/en_us.lang.php b/oss/vtiger/trunk/modules/Faq/language/en_us.lang.php new file mode 100644 index 00000000..31615a1d --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/language/en_us.lang.php @@ -0,0 +1,144 @@ +'FAQ', +'LBL_MODULE_TITLE'=>'FAQ: Home', +'LBL_SEARCH_FORM_TITLE'=>'FAQ Search', +'LBL_LIST_FORM_TITLE'=>'FAQ List', +'LBL_NEW_FORM_TITLE'=>'New Faq', +'LBL_MEMBER_ORG_FORM_TITLE'=>'Member Organizations', + +'LBL_LIST_ACCOUNT_NAME'=>'Faq Name', +'LBL_LIST_CITY'=>'City', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_STATE'=>'State', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_EMAIL_ADDRESS'=>'Email Address', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', +'LBL_FAQ_INFORMATION'=>'Faq Information', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'Faq:', +'LBL_ACCOUNT_NAME'=>'Faq Name:', +'LBL_PHONE'=>'Phone:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_TICKER_SYMBOL'=>'Ticker Symbol:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_MEMBER_OF'=>'Member of:', +'LBL_EMAIL'=>'Email:', +'LBL_EMPLOYEES'=>'Employees:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_OWNERSHIP'=>'Ownership:', +'LBL_RATING'=>'Rating:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_SIC_CODE'=>'SIC Code:', +'LBL_TYPE'=>'Type:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_ACCOUNT_INFORMATION'=>'Faq Information', +'LBL_BILLING_ADDRESS'=>'Billing Address:', +'LBL_SHIPPING_ADDRESS'=>'Shipping Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_DESCRIPTION'=>'Description:', +'NTC_COPY_BILLING_ADDRESS'=>'Copy billing address to shipping address', +'NTC_COPY_SHIPPING_ADDRESS'=>'Copy shipping address to billing address', +'NTC_REMOVE_MEMBER_ORG_CONFIRMATION'=>'Are you sure you want to remove this record as a member organization?', +'LBL_DUPLICATE'=>'Potential Duplicate Faq', +'MSG_DUPLICATE' => 'Creating this vtiger_account may vtiger_potentialy create a duplicate vtiger_account. You may either select an vtiger_account from the list below or you may click on Create New Faq to continue creating a new vtiger_account with the previously entered data.', + +'LBL_INVITEE'=>'Contacts', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", + +'LBL_SELECT_ACCOUNT'=>'Select Faq', +'LBL_GENERAL_INFORMATION'=>'General Information', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added for 4GA Release +'Category'=>'Category', +'Related To'=>'Related To', +'Question'=>'Question', +'Answer'=>'Answer', +'Comments'=>'Comments', +'LBL_COMMENTS'=>'Comments',//give the same value given to the above string 'Comments' +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', + +//Added vtiger_fields after 4.2 alpha +'LBL_TICKETS'=>'Tickets', +'LBL_FAQ'=>'FAQ', +'Product Name'=>'Product Name', +'FAQ Id'=>'FAQ Id', +'Add Comment'=>'Add Comment', +'LBL_ADD_COMMENT'=>'Add Comment',//give the same value given to the above string 'Add Comment' +'LBL_COMMENT_INFORMATION'=>'Comment Information', +'Status'=>'Status', + +//Added on 10-12-2005 +'LBL_QUESTION'=>'Question', +'LBL_CATEGORY'=>'Category', +'LBL_MY_FAQ'=>'My Recent FAQs', + +//Added for existing Picklist Entries + +'General'=>'General', + +'Draft'=>'Draft', +'Reviewed'=>'Reviewed', +'Published'=>'Published', +'Obsolete'=>'Obsolete', + +// Module Sequence Numbering +'Faq No' => 'Faq No', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Faq/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Faq/language/zh_cn.lang.php new file mode 100644 index 00000000..b288c92c --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/language/zh_cn.lang.php @@ -0,0 +1,143 @@ + '常见问答', + 'LBL_MODULE_TITLE' => '常见问答: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻问答', + 'LBL_LIST_FORM_TITLE' => '问答列表', + 'LBL_NEW_FORM_TITLE' => '新增问答', + 'LBL_MEMBER_ORG_FORM_TITLE' => '会员所属组织单位', + + 'LBL_LIST_ACCOUNT_NAME' => '问答名称', + 'LBL_LIST_CITY' => '乡镇市区', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '县市', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件地址', + 'LBL_LIST_CONTACT_NAME' => '联系人名称', + 'LBL_FAQ_INFORMATION' => '常见问答信息', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + + 'LBL_ACCOUNT' => '常见问答:', + 'LBL_ACCOUNT_NAME' => '问答名称:', + 'LBL_PHONE' => '电话:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_TICKER_SYMBOL' => '传票符号:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_ANY_PHONE' => '其它电话:', + 'LBL_MEMBER_OF' => '会员:', + 'LBL_EMAIL' => '电子邮件:', + 'LBL_EMPLOYEES' => '员工:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子邮件:', + 'LBL_ANY_EMAIL' => '其它电子邮件:', + 'LBL_OWNERSHIP' => '所有人:', + 'LBL_RATING' => '评价:', + 'LBL_INDUSTRY' => '企业:', + 'LBL_SIC_CODE' => '统一编号:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年营业额:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_ACCOUNT_INFORMATION' => '问答信息', + 'LBL_BILLING_ADDRESS' => '发票地址:', + 'LBL_SHIPPING_ADDRESS' => '送货地址:', + 'LBL_ANY_ADDRESS' => '其它地址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '县市:', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '国家:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息', + 'LBL_DESCRIPTION' => '描述:', + 'NTC_COPY_BILLING_ADDRESS' => '复制发票地址到送货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '复制送货地址至发票地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '您确定要移除关于这笔会员组织单位的记录?', + 'LBL_DUPLICATE' => '复制具有潜力的问答', + 'MSG_DUPLICATE' => '建立这个客户数据可能造成数据重复,您可以从下面选择一个客户的资料来更新或是点选建立新问答来透过刚刚输入的数据建立新项目。', + + 'LBL_INVITEE' => '联系人', + 'ERR_DELETE_RECORD' => '在删除公司前必须输入正确的记录编号.', + + 'LBL_SELECT_ACCOUNT' => '选择问答', + 'LBL_GENERAL_INFORMATION' => '一般信息', + +//for v4 release added +'LBL_NEW_POTENTIAL' => '新增潜在案件', + 'LBL_POTENTIAL_TITLE' => '潜在案件', + +'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '电子邮件', + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_CONTACT_TITLE' => '联系人', + +//Added for 4GA Release +'Category' => '类别', + 'Related To' => '相关人事', + 'Question' => '问题', + 'Answer' => '回答', + 'Comments' => '意见', +'LBL_COMMENTS'=>'意见',//give the same value given to the above string 'Comments' + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + +//Added vtiger_fields after 4.2 alpha +'LBL_TICKETS' => '传票', + 'LBL_FAQ' => '常见问答', + 'Product Name' => '产品名称', + 'FAQ Id' => '常见问答编号', + 'Add Comment' => '新增意见', +'LBL_ADD_COMMENT'=>'新增意见',//give the same value given to the above string 'Add Comment' +'LBL_COMMENT_INFORMATION'=>'意见信息', +'Status'=>'状态', + +//Added on 10-12-2005 +'LBL_QUESTION'=>'问题', +'LBL_CATEGORY'=>'类别', +'LBL_MY_FAQ'=>'我的最近常见问题', + +//Added for existing Picklist Entries + + 'General' => '一般', + +'Draft' => '草稿', + 'Reviewed' => '已审阅', + 'Published' => '已发布', + 'Obsolete' => '过期', + +// Module Sequence Numbering +'Faq No' => 'Faq No', +// END +); + +?> diff --git a/oss/vtiger/trunk/modules/Faq/updateRelations.php b/oss/vtiger/trunk/modules/Faq/updateRelations.php new file mode 100644 index 00000000..e333a98f --- /dev/null +++ b/oss/vtiger/trunk/modules/Faq/updateRelations.php @@ -0,0 +1,48 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=$forCRMRecord&parenttab=$parenttab"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulas.js b/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulas.js new file mode 100644 index 00000000..fa3b1af1 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulas.js @@ -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. + ******************************************************************************/ \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulas.php b/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulas.php new file mode 100644 index 00000000..921b17b9 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulas.php @@ -0,0 +1,62 @@ +getUniqueID('vtiger_settings_field'); + $blockid = getSettingsBlockId('LBL_MODULE_MANAGER'); + + $seq_res = $adb->query("SELECT max(sequence) AS max_seq FROM vtiger_settings_field"); + $seq = 1; + if ($adb->num_rows($seq_res) > 0) { + $cur_seq = $adb->query_result($seq_res, 0, 'max_seq'); + if ($cur_seq != null) $seq = $cur_seq + 1; + } + + $adb->pquery('INSERT INTO vtiger_settings_field(fieldid, blockid, name, iconpath, description, linkto, sequence) + VALUES (?,?,?,?,?,?,?)', array($fieldid, $blockid, 'LBL_FIELDFORMULAS', 'modules/FieldFormulas/resources/FieldFormulas.png', 'LBL_FIELDFORMULAS_DESCRIPTION', 'index.php?module=FieldFormulas&action=index&parenttab=Settings', $seq)); + + $tabid = getTabid('FieldFormulas'); + if(isset($tabid) && $tabid!='') { + $adb->pquery('DELETE FROM vtiger_profile2tab WHERE tabid = ?', array($tabid)); + } + + // Mark the module as Standard module + $adb->pquery('UPDATE vtiger_tab SET customized=0 WHERE name=?', array($moduleName)); + + } else if($eventType == 'module.disabled') { + $em = new VTEventsManager($adb); + $em->setHandlerInActive('VTFieldFormulasEventHandler'); + + } else if($eventType == 'module.enabled') { + $em = new VTEventsManager($adb); + $em->setHandlerActive('VTFieldFormulasEventHandler'); + + } else if($eventType == 'module.preuninstall') { + // TODO Handle actions when this module is about to be deleted. + } else if($eventType == 'module.preupdate') { + // TODO Handle actions before this module is updated. + } else if($eventType == 'module.postupdate') { + // TODO Handle actions after this module is updated. + } + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulasAjax.php b/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulasAjax.php new file mode 100644 index 00000000..8cd39c44 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/FieldFormulasAjax.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/VTFieldFormulasEventHandler.inc b/oss/vtiger/trunk/modules/FieldFormulas/VTFieldFormulasEventHandler.inc new file mode 100644 index 00000000..00276257 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/VTFieldFormulasEventHandler.inc @@ -0,0 +1,20 @@ +getModuleName(); + $mem = new VTModuleExpressionsManager($adb); + $me = $mem->retrieve($moduleName); + $me->update($data); + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/VTModuleExpressionsManager.inc b/oss/vtiger/trunk/modules/FieldFormulas/VTModuleExpressionsManager.inc new file mode 100644 index 00000000..8b68e864 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/VTModuleExpressionsManager.inc @@ -0,0 +1,179 @@ +adb = $adb; + } + + /** Caching logic **/ + private static $cache = array(); + static function addToCache($key, $value) { + self::$cache[$key] = $value; + } + static function fromCache($key) { + if(isset(self::$cache[$key])) return self::$cache[$key]; + return false; + } + static function clearCache() { + self::$cache = array(); + } + /** END **/ + + function retrieve($moduleName){ + $adb = $this->adb; + + // Look at cache if we have the information + $cachedinfo = self::fromCache($moduleName); + if($cachedinfo === false) { + + $result = $adb->pquery('select * from vtiger_fieldformulas where modulename=?', array($moduleName)); + if($adb->num_rows($result)==0){ + self::addToCache($moduleName, array() ); + }else{ + $ee = unserialize(decode_html($adb->query_result($result, 0, "expression_engine"))); + $id = $adb->query_result($result, 0, "expressionid"); + self::addToCache($moduleName, array('expressionid'=>$id, 'expression_engine'=>$ee)); + } + // Retrieve information from cache for consistency + $cachedinfo = self::fromCache($moduleName); + } + + $me = new VTModuleExpressions($moduleName, new VTExpressionEngine()); + if(!empty($cachedinfo)) { + $me = new VTModuleExpressions($moduleName, $cachedinfo['expression_engine']); + $me->id = $cachedinfo['expressionid']; + } + return $me; + + } + + function save($moduleExpressions){ + $adb = $this->adb; + if(isset($moduleExpressions->id)){ + $adb->pquery('update vtiger_fieldformulas set expression_engine=? where expressionid=?', + array(serialize($moduleExpressions->expressionEngine), $moduleExpressions->id)); + }else{ + $id = $adb->getUniqueId('vtiger_fieldformulas'); + $adb->pquery('insert into vtiger_fieldformulas + (expressionid, modulename, expression_engine) values(?,?,?)', + array($id, $moduleExpressions->moduleName, + serialize($moduleExpressions->expressionEngine))); + $moduleExpressions->id = $id; + } + // Invalidate cache information + self::clearCache(); + } + + + function expressionFields($moduleName){ + global $current_user; + $result = vtws_describe($moduleName, $current_user); + $fields = $result['fields']; + $arr = array(); + foreach($fields as $field){ + //Use the field name to figure out the custom field + if(preg_match('/cf_\d+/', $field['name']) && + in_array($field['type']['name'], array('text', 'string','integer', 'double'))){ + $arr[$field['name']] = getTranslatedString($field['label'], $moduleName); + } + } + return $arr; + } + + function fields($moduleName){ + global $current_user; + $result = vtws_describe($moduleName, $current_user); + $fields = $result['fields']; + $arr = array(); + foreach($fields as $field){ + $arr[$field['name']] = $field['label']; + } + return $arr; + } + + function expressionFunctions(){ + return array('concat' => 'concat(a,b)'); + } + + private function fieldNames($query, $moduleName){ + $adb = $this->adb; + $result = $adb->pquery($query, array($moduleName)); + $it = new SqlResultIterator($adb, $result); + $arr = array(); + foreach($it as $row){ + $arr[$row->fieldname]=$row->fieldlabel; + } + return $arr; + } + + function expressionsForModule($moduleName){ + return $this->retrieve($moduleName)->asArray(); + } +} + +class VTModuleExpressions{ + function __construct($moduleName, $expressionEngine){ + $this->moduleName=$moduleName; + $this->expressionEngine=$expressionEngine; + } + + function add($fieldName, $expression){ + try{ + $this->expressionEngine->loadExpressions(array($fieldName=>$expression)); + $this->state='savable'; + }catch(VTExpressionException $e){ + $this->state='error'; + $this->message=$e->getMessage(); + } + } + + function remove($fieldName){ + $this->expressionEngine->removeExpression($fieldName); + } + + function asArray(){ + return $this->expressionEngine->unparsedExpressions; + } + + function parseExpression($expr){ + $parser = new VTParser(new SpaceFilter(new VTTokenizer($expr))); + return $parser->expression(); + } + + function update($entity){ + $bound = $this->expressionEngine->evaluate($entity->getData()); + foreach($bound as $field => $value){ + $entity->set($field, $value); + } + } + + function getFieldsFromExpr($expr){ + function __getFieldsFromExpr($expr, &$arr){ + switch(get_class($expr)){ + case 'VTTreeNode': + $params = $expr->getParams(); + foreach($params as $param){ + __vtGetFieldsFromExpr($param, $arr); + } + return; + case 'Symbol': + $arr[$expr->value] = $expr; + return; + default: + return; + } + } + __vtGetFieldsFromExpr($expr, $arr); + return array_keys($arr); + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/deleteexpressionjson.php b/oss/vtiger/trunk/modules/FieldFormulas/deleteexpressionjson.php new file mode 100644 index 00000000..96ca3663 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/deleteexpressionjson.php @@ -0,0 +1,23 @@ +retrieve($moduleName); + $me->remove($fieldName); + $mem->save($me); + echo Zend_Json::encode(array('status'=>'success')); +} + +vtDeleteExpressionJson($adb, $_GET); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/editexpressions.php b/oss/vtiger/trunk/modules/FieldFormulas/editexpressions.php new file mode 100644 index 00000000..4c7783e1 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/editexpressions.php @@ -0,0 +1,80 @@ +assign('APP', $appStrings); + + $mod = array_merge( + return_module_language($current_language,'FieldFormulas'), + return_module_language($current_language,'Settings')); + + $jsStrings = array( + 'NEED_TO_ADD_A'=>$mod['NEED_TO_ADD_A'], + 'CUSTOM_FIELD' =>$mod['LBL_CUSTOM_FIELD'], + 'LBL_USE_FUNCTION_DASHDASH'=>$mod['LBL_USE_FUNCTION_DASHDASH'], + 'LBL_USE_FIELD_VALUE_DASHDASH'=>$mod['LBL_USE_FIELD_VALUE_DASHDASH'], + 'LBL_DELETE_EXPRESSION_CONFIRM'=>$mod['LBL_DELETE_EXPRESSION_CONFIRM'] + ); + $smarty->assign("JS_STRINGS", Zend_Json::encode($jsStrings)); + + $smarty->assign("MOD", $mod); + $smarty->assign("THEME",$theme); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE_NAME", 'FieldFormulas'); + $smarty->assign("PAGE_NAME", 'LBL_FIELDFORMULAS'); + $smarty->assign("PAGE_TITLE", 'LBL_FIELDFORMULAS'); + $smarty->assign("PAGE_DESC", 'LBL_FIELDFORMULAS_DESCRIPTION'); + $smarty->assign("FORMODULE", $formodule); + + if(file_exists("modules/$formodule/$formodule.php")) { + $focus = CRMEntity::getInstance($formodule); + $validationArray = split_validationdataArray(getDBValidationData($focus->tab_name, getTabid($formodule))); + $smarty->assign('VALIDATION_DATA_FIELDNAME',$validationArray['fieldname']); + $smarty->assign('VALIDATION_DATA_FIELDDATATYPE',$validationArray['datatype']); + $smarty->assign('VALIDATION_DATA_FIELDLABEL',$validationArray['fieldlabel']); + } + + $smarty->display(vtlib_getModuleTemplate('FieldFormulas', 'EditExpressions.tpl')); +} + +$modules = vtGetModules($adb); +if(vtlib_isModuleActive('FieldFormulas') && in_array(getTranslatedString($_REQUEST['formodule']),$modules)) { + vtEditExpressions($adb, $app_strings, $current_language, $theme, $_REQUEST['formodule']); +} else { + echo "
"; + echo "
+ + + + + + + + + +
".$app_strings['LBL_PERMISSION']."
+ $app_strings[LBL_BACK]
+
"; + echo "
";die; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTExpressionEngine.inc b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTExpressionEngine.inc new file mode 100644 index 00000000..28cd8696 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTExpressionEngine.inc @@ -0,0 +1,174 @@ +expr = new VTExpressionEvaluater($expr); + $this->env = $env; + } + + function get(){ + if(!isset($this->val)){ + $this->val = $this->expr->evaluate($this->env); + } + return $this->val; + } +} + +class VTExpressionEngineEnv implements VTEnv{ + function __construct($data){ + $this->data = $data; + $this->vars = array(); + } + + function bind($name, $expr){ + $this->vars[$name] = new VTThunk($this, $expr); + } + + function get($var){ + if(array_key_exists($var, $this->vars)){ + return $this->vars[$var]->get(); + }else{ + return $this->data[$var]; + } + } +} + +class VTExpressionEngine{ + function __construct(){ + $this->data = array(); + $this->expressions = array(); + $this->unparsedExpressions = array(); + $this->vars = array(); + } + + + /** + * Load dynamic fields and their expressions + * + */ + function loadExpressions($arr){ + $this->unparsedExpressions = array_merge($this->unparsedExpressions, $arr); + $this->expressions = array_merge($this->expressions, array_map(array($this, 'expression'), $arr)); + $this->regenerate(); + } + + function removeExpression($fieldName){ + unset($this->unparsedExpressions[$fieldName]); + unset($this->expressions[$fieldName]); + $this->regenerate(); + } + + private function regenerate(){ + $this->vars = array_keys($this->expressions); + + $dyn_vars = array(); + foreach($this->expressions as $var => $expr){ + $syms = array_keys($this->getSyms($expr)); + $dyn_vars[$var] = $syms; + } + + $independents = array_keys(array_filter($dyn_vars, array($this, 'isEmpty'))); + $arr = array(); + foreach($dyn_vars as $var => $parents){ + foreach($parents as $parent){ + $arr[$parent][$var] = $var; + } + } + $dependents = array_map('array_keys', $arr); + $this->independents = $independents; + $this->dependents = $dependents; + $this->checkForCycles(); + } + + + /** + * Evaluate the expressions using the data in the array + * provided. + * + * @param $data An array of bound variables containing the + * the variable name as the key and the value as data. + * @return An array containing the variables bound to the expressions + * and their values. + */ + function evaluate($data){ + $env = new VTExpressionEngineEnv($data); + foreach($this->expressions as $var=>$expr){ + $env->bind($var, $expr); + } + + $out = array(); + foreach($this->vars as $var){ + $out[$var] = $env->get($var); + } + return $out; + } + + private function checkForCycles(){ + foreach($this->independents as $independent){ + $this->testCall($independent, array(), sizeof($this->dependents)); + } + } + + private function testCall($cur, $stack, $n){ + if($n<0){ + throw new VTExpressionException('There appears to be a loop in ('.implode(", ", $stack).')'); + } + $dependents = $this->dependents; + if(array_key_exists($cur, $dependents)){ + foreach($dependents[$cur] as $var){ + $this->testCall($var, array_merge($stack, array($cur)), $n-1); + } + } + } + + private function getSyms($expr){ + if($expr instanceof VTTreeNode){ + $params = $expr->getParams(); + if(sizeof($params)!=0){ + $sym_arr = array_map(array($this, "getSyms"), $params); + if(sizeof($sym_arr)>1){ + $syms = call_user_func_array('array_merge', $sym_arr); + + }else{ + $syms = $sym_arr[0]; + } + }else{ + $syms = array(); + } + return $syms; + }else if($expr instanceof Symbol && in_array($expr->value, $this->vars)){ + return array($expr->value=>$expr); + }else{ + return array(); + } + } + + private function loadExpression($var, $expr){ + $this->expressions[$var] = $value; + } + + private private function parse($str){ + $parser = new VTParser(new SpaceFilter(new VTTokenizer($str))); + return $parser->expression(); + } + + private function isEmpty($arr){ + return sizeof($arr)!=0; + } + + private function expression($str){ + $parser = new VTParser(new SpaceFilter(new VTTokenizer($str))); + return $parser->expression(); + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTExpressionEvaluater.inc b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTExpressionEvaluater.inc new file mode 100644 index 00000000..5cc3e4f4 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTExpressionEvaluater.inc @@ -0,0 +1,117 @@ += $arr[1]; +} + +function _vt_lt($arr) { + return $arr[0] < $arr[1]; +} + +function _vt_gt($arr) { + return $arr[0] > $arr[1]; +} + +function _vt_concat($arr){ + return implode($arr); +} + +class VTExpressionEvaluater{ + function __construct($expr){ + + $this->operators = array( + '+' => '_vt_add', + '-' => '_vt_sub', + '*' => '_vt_mul', + '/' => '_vt_div', + '==' => '_vt_equals', + '<=' => '_vt_ltequals', + '>=' => '_vt_gtequals', + '<' => '_vt_lt', + '>' => '_vt_gt', + ); + $this->functions = array( + 'concat'=>'_vt_concat' + ); + + $this->operations = array_merge($this->functions, $this->operators); + $this->expr = $expr; + + } + + function evaluate($env){ + $this->env = $env; + return $this->exec($this->expr); + } + + function exec($expr){ + if($expr instanceof Symbol){ + return $this->env($expr); + }else if($expr instanceof VTTreeNode){ + $op = $expr->getName(); + if($op->value=='if'){ + $params = $expr->getParams(); + $cond = $this->exec($params[0]); + if($cond){ + return $this->exec($params[1]); + }else{ + return $this->exec($params[2]); + } + }else{ + $params = array_map(array($this, 'exec'), $expr->getParams()); + $func = $this->operations[$op->value]; + return $func($params); + } + }else{ + return $expr; + } + } + + function env($sym){ + return $this->env->get($sym->value); + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTParser.inc b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTParser.inc new file mode 100644 index 00000000..061e0585 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTParser.inc @@ -0,0 +1,184 @@ +arr = $arr; + } + + function getParams(){ + $arr = $this->arr; + return array_slice($arr, 1, sizeof($arr)-1); + } + + function getName(){ + return $this->arr[0]; + } +} + + +class Symbol{ + function __construct($value){ + $this->value = $value; + } + + function __toString(){ + return "Symbol({$this->value})"; + } +} + +class VTParser{ + function __construct($tokens){ + $this->tokens = $tokens; + $this->tokenQueue = array(); + } + + function nextToken(){ + if(sizeof($this->tokenQueue)==0){ + return $this->tokens->nextToken(); + }else{ + return array_shift($this->tokenQueue); + } + } + + function la($n = 1){ + for($i=sizeof($this->tokenQueue); $i<$n; $i++){ + $token = $this->tokens->nextToken(); + $this->tokenQueue[] = $token; + } + return $this->tokenQueue[$n-1]; + } + + function consume($label, $value){ + $token=$this->nextToken(); + if($token->label!=$label || $token->value!=$value){ + echo "Was expecting a $label of value $value got a {$token->label} of {$token->value} instead."; + throw new Exception("Was expecting a $label of value $value got a {$token->label} of {$token->value} instead."); + } + } + + function consumeSymbol($sym){ + $this->consume('SYMBOL', new Symbol($sym)); + } + + + function check($token, $label, $value){ + return $token->label == $label && $token->value==$value; + } + + function checkSymbol($token, $sym){ + return $this->check($token, 'SYMBOL', new Symbol($sym)); + } + + function atom(){ + $token = $this->nextToken(); + switch($token->label){ + case "STRING": + return $token->value; + case "INTEGER": + return $token->value; + case "FLOAT": + return $token->value; + case "SYMBOL": + return $token->value; + case "OPEN_BRACKET": + $val = $this->expression(); + $close = $this->nextToken(); + if($close->label != 'CLOSE_BRACKET'){ + throw new Exception("Was expecting a close bracket"); + } + return $val; + default: + print_r($token); + throw new Exception(); + } + } + + function ifCondition(){ + $this->consumeSymbol('if'); + $cond = $this->expression(); + $this->consumeSymbol('then'); + $ifTrue = $this->expression(); + $this->consumeSymbol('else'); + if($this->checkSymbol($this->la(), 'if')){ + $ifFalse = $this->ifCondition(); + }else{ + $ifFalse = $this->expression(); + $this->consumeSymbol('end'); + } + return new VTTreeNode(array(new Symbol('if'), $cond, $ifTrue, $ifFalse)); + } + + function expression(){ + $la1 = $this->la(1); + $la2 = $this->la(2); + if($this->checkSymbol($la1, 'if')){ + return $this->ifCondition(); + }else if($la1->label=='SYMBOL' && $la2->label=='OPEN_BRACKET'){ + $arr = array($this->nextToken()->value); + $this->nextToken(); + if($this->la()->label != 'CLOSE_BRACKET'){ + $arr[] = $this->expression(); + $comma = $this->nextToken(); + while($comma->label == 'COMMA'){ + $arr[] = $this->expression(); + $comma = $this->nextToken(); + } + if($comma->label != 'CLOSE_BRACKET'){ + throw new Exception("Was expecting a closing bracket"); + } + }else{ + $this->consume('CLOSE_BRACKET', new Symbol(')')); + } + return new VTTreeNode($arr); + }else{ + return $this->binOp(); + } + } + + var $precedence = array( + array('*', '/'), + array('+', '-'), + array('and', 'or'), + array('==', '>=', '<=', '>', '<') + ); + + function binOp(){ + return $this->binOpPrec(sizeof($this->precedence)-1); + } + + private function binOpPrec($prec){ + if($prec>=0){ + $lhs = $this->binOpPrec($prec-1); + $la = $this->la(); + if($la->label == 'OPERATOR' && in_array($la->value->value, $this->precedence[$prec])){ + $operator = $this->nextToken()->value; + $rhs = $this->binOpPrec($prec); + return new VTTreeNode(array($operator, $lhs, $rhs)); + }else{ + return $lhs; + } + }else{ + return $this->unaryOp(); + } + } + + function unaryOp(){ + $la = $this->la(); + if($la->label=="OPERATOR" && in_array($la->value->value, array('+', '-'))){ + $token = $this->nextToken(); + $operator = $la->value; + $operand = $this->unaryOp(); + return new VTTreeNode(array($operator, $operand)); + }else{ + return $this->atom(); + } + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTTokenizer.inc b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTTokenizer.inc new file mode 100644 index 00000000..d9c46c80 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/VTTokenizer.inc @@ -0,0 +1,91 @@ +label = $label; + } +} + +function _processtoken_id($token){ + return $token; +} + +function _processtoken_symbol($token){ + return new Symbol($token); +} + +class VTTokenizer{ + function __construct($expr){ + $tokenTypes = array( + "SPACE" => array('\s+', '_processtoken_id'), + "SYMBOL" => array('[a-zA-Z][\w]*', '_processtoken_symbol'), + "ESCAPED_SYMBOL" => array('?:`([^`]+)`', '_processtoken_symbol'), + "STRING" => array('?:"((?:\\\\"|[^"])+)"', 'stripcslashes'), + "FLOAT" => array('\d+[.]\d+', 'floatval'), + "INTEGER" => array('\d+', 'intval'), + 'OPERATOR' => array('[+]|[-]|[*]|>=|<=|[<]|[>]|==|\/', '_processtoken_symbol'), + // NOTE: Any new Operator added should be updated in VTParser.inc::$precedence and operation at VTExpressionEvaluater + 'OPEN_BRACKET' => array('[(]', '_processtoken_symbol'), + 'CLOSE_BRACKET' => array('[)]', '_processtoken_symbol'), + 'COMMA' => array('[,]', '_processtoken_symbol') + ); + $tokenReArr = array(); + $tokenNames = array(); + $this->tokenTypes = $tokenTypes; + + foreach($tokenTypes as $tokenName => $code){ + list($re, $processtoken) = $code; + $tokenReArr[] = '('.$re.')'; + $tokenNames[] = $tokenName; + } + $this->tokenNames = $tokenNames; + $tokenRe = '/'.implode('|', $tokenReArr).'/'; + $this->EOF = new VTToken("EOF"); + + $matches = array(); + preg_match_all($tokenRe, $expr, $matches, PREG_SET_ORDER); + $this->matches = $matches; + $this->idx = 0; + } + function nextToken(){ + $matches = $this->matches; + $idx = $this->idx; + if($idx == sizeof($matches)){ + return $this->EOF; + }else{ + $match = $matches[$idx]; + $this->idx = $idx + 1; + $i=1; + while($match[$i]==null){ + $i+=1; + } + $tokenName = $this->tokenNames[$i-1]; + $token = new VTToken($tokenName); + $token->value = $this->tokenTypes[$tokenName][1]($match[$i]); + return $token; + } + } +} + +class SpaceFilter{ + function __construct($tokens){ + $this->tokens = $tokens; + } + + function nextToken(){ + do{ + $token = $this->tokens->nextToken(); + }while($token->label == "SPACE"); + return $token; + } +} + + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/include.inc b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/include.inc new file mode 100644 index 00000000..ba288b64 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/expression_engine/include.inc @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/getexpressionlistjson.php b/oss/vtiger/trunk/modules/FieldFormulas/getexpressionlistjson.php new file mode 100644 index 00000000..031e37d6 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/getexpressionlistjson.php @@ -0,0 +1,19 @@ +expressionsForModule($moduleName); + echo Zend_Json::encode($arr); +} +vtGetExpressionListJson($adb, $_GET); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/getfieldsjson.php b/oss/vtiger/trunk/modules/FieldFormulas/getfieldsjson.php new file mode 100644 index 00000000..4444f31c --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/getfieldsjson.php @@ -0,0 +1,24 @@ +expressionFields($moduleName); + $fields = $mem->fields($moduleName); + echo Zend_Json::encode(array('exprFields'=>$expressionFields, 'moduleFields'=>$fields)); +} +vtJsonFields($adb, $_REQUEST); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/getfunctionsjson.php b/oss/vtiger/trunk/modules/FieldFormulas/getfunctionsjson.php new file mode 100644 index 00000000..a60dffb2 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/getfunctionsjson.php @@ -0,0 +1,19 @@ +expressionFunctions(); + echo Zend_Json::encode($functions); +} +vtJsonFields($adb, $_REQUEST); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/include.inc b/oss/vtiger/trunk/modules/FieldFormulas/include.inc new file mode 100644 index 00000000..131c99c4 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/include.inc @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/index.php b/oss/vtiger/trunk/modules/FieldFormulas/index.php new file mode 100644 index 00000000..42f4cabf --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/index.php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/language/en_us.lang.php b/oss/vtiger/trunk/modules/FieldFormulas/language/en_us.lang.php new file mode 100644 index 00000000..55efd168 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/language/en_us.lang.php @@ -0,0 +1,33 @@ + 'Field Formulas', +'LBL_FIELDFORMULAS' => 'Field Formulas', +'LBL_FIELDFORMULAS_DESCRIPTION' => 'Add custom equations to custom fields', +'LBL_FIELDS' => 'Fields', +'LBL_FUNCTIONS' => 'Functions', +'LBL_FIELD' => 'Field', +'LBL_EXPRESSION' => 'Expression', +'LBL_SETTINGS' => 'Settings', +'LBL_NEW_FIELD_EXPRESSION_BUTTON' => 'New Field Expression', +'LBL_EDIT_EXPRESSION' => 'Edit Expression', +'LBL_MODULE_INFO' => 'Forumlas defined for ', +'NEED_TO_ADD_A' =>'You need to add a string or integer type ', +'LBL_CUSTOM_FIELD' =>'Custom field', +'LBL_CHECKING'=>'Checking...', +'LBL_SELECT_ONE_DOTDOTDOT'=>'Select One...', +'LBL_TARGET_FIELD'=>'Target Field', +'LBL_DELETE_EXPRESSION_CONFIRM'=>'Are you sure to delete the expression?', +'LBL_EXAMPLES'=>'Examples', +'LBL_USE_FIELD_VALUE_DASHDASH'=>'-- Use Field Value --', +'LBL_USE_FUNCTION_DASHDASH'=>'-- Use Function --', +); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/FieldFormulas/language/zh_cn.lang.php new file mode 100644 index 00000000..7c48f9d1 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/language/zh_cn.lang.php @@ -0,0 +1,33 @@ + '字段公式', +'LBL_FIELDFORMULAS' => '字段公式', +'LBL_FIELDFORMULAS_DESCRIPTION' => '为自定义字段添加公式', +'LBL_FIELDS' => '字段', +'LBL_FUNCTIONS' => '函数', +'LBL_FIELD' => '字段', +'LBL_EXPRESSION' => '表达式', +'LBL_SETTINGS' => '设置', +'LBL_NEW_FIELD_EXPRESSION_BUTTON' => '新字段表达式', +'LBL_EDIT_EXPRESSION' => '编辑表达式', +'LBL_MODULE_INFO' => '定义公式- ', +'NEED_TO_ADD_A' =>'要求添加字符型或数字型 ', +'LBL_CUSTOM_FIELD' =>'自定义字段', +'LBL_CHECKING'=>'检查...', +'LBL_SELECT_ONE_DOTDOTDOT'=>'选择...', +'LBL_TARGET_FIELD'=>'目标字段', +'LBL_DELETE_EXPRESSION_CONFIRM'=>'你确定要删除这个表达式?', +'LBL_EXAMPLES'=>'示例', +'LBL_USE_FIELD_VALUE_DASHDASH'=>'-- 使用字段 --', +'LBL_USE_FUNCTION_DASHDASH'=>'-- 使用函数 --', +); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/FieldFormulas/resources/FieldFormulas.png b/oss/vtiger/trunk/modules/FieldFormulas/resources/FieldFormulas.png new file mode 100644 index 00000000..d1ebb5a5 Binary files /dev/null and b/oss/vtiger/trunk/modules/FieldFormulas/resources/FieldFormulas.png differ diff --git a/oss/vtiger/trunk/modules/FieldFormulas/resources/editexpressionscript.js b/oss/vtiger/trunk/modules/FieldFormulas/resources/editexpressionscript.js new file mode 100644 index 00000000..33de7842 --- /dev/null +++ b/oss/vtiger/trunk/modules/FieldFormulas/resources/editexpressionscript.js @@ -0,0 +1,319 @@ +/*+******************************************************************************* + * 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. + ******************************************************************************/ +jQuery.noConflict(); +function editexpressionscript($){ + function errorDialog(message){ + alert(message); + } + + function handleError(fn){ + return function(status, result){ + if(status){ + fn(result); + }else{ + errorDialog('Failure:'+result); + } + }; + } + + + var ep;//ep is defined in the document.ready block. + + function errorDialog(message){ + alert(message); + } + + + function jsonget(operation, params, callback){ + var obj = { + module:'FieldFormulas', + action:'FieldFormulasAjax', + file:operation, ajax:'true'}; + $.each(params,function(key, value){ + obj[key] = value; + }); + $.get('index.php', obj, + function(result){ + var parsed = JSON.parse(result); + callback(parsed); + }); + } + + function getfieldlabel(fieldname) { + var fieldlabel = false; + if(typeof(meta_fieldnames) != 'undefined' && typeof(meta_fieldlabels) != 'undefined') { + fieldlabel = meta_fieldlabels[meta_fieldnames.indexOf(fieldname)]; + } + if(!fieldlabel) fieldlabel = fieldname; + return fieldlabel; + } + + function addFieldExpression(moduleName, fieldName, fieldLabel, expression){ + editLink = format('Edit', fieldName); + deleteLink = format('Delete', fieldName); + row = format('
%s%s%s | %s
", "
" ] || + + !tags.indexOf("", "" ] || + + // matched above + (!tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + // IE can't serialize and + +EOQ; + +return $the_script; +} + +/** + * Create HTML form to enter a new record with the minimum necessary fields. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_new_record_form () { + //TODO: To be implemented +} + +?> diff --git a/oss/vtiger/trunk/modules/Help/index.php b/oss/vtiger/trunk/modules/Help/index.php new file mode 100644 index 00000000..2d9e8bbd --- /dev/null +++ b/oss/vtiger/trunk/modules/Help/index.php @@ -0,0 +1,22 @@ + +Sorry! The module has not yet been implemented. +

+Stay tuned for an upcoming release of vtigerCRM! diff --git a/oss/vtiger/trunk/modules/Help/language/en_us.lang.php b/oss/vtiger/trunk/modules/Help/language/en_us.lang.php new file mode 100644 index 00000000..07614bed --- /dev/null +++ b/oss/vtiger/trunk/modules/Help/language/en_us.lang.php @@ -0,0 +1,29 @@ +'Accounts', +'LBL_MODULE_TITLE'=>'Accounts: Home', +'LBL_SEARCH_FORM_TITLE'=>'Account Search', +'LBL_LIST_FORM_TITLE'=>'Account List', +'LBL_NEW_FORM_TITLE'=>'New Account', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the account.", +); + +?> diff --git a/oss/vtiger/trunk/modules/Help/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Help/language/zh_cn.lang.php new file mode 100644 index 00000000..890d4690 --- /dev/null +++ b/oss/vtiger/trunk/modules/Help/language/zh_cn.lang.php @@ -0,0 +1,29 @@ + '客户', + 'LBL_MODULE_TITLE' => '客户: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻客户', + 'LBL_LIST_FORM_TITLE' => '客户列表', + 'LBL_NEW_FORM_TITLE' => '新增客户', + 'ERR_DELETE_RECORD' => '必须指定其记录编号才能删除客户数据。', +); + +?> diff --git a/oss/vtiger/trunk/modules/HelpDesk/CallRelatedList.php b/oss/vtiger/trunk/modules/HelpDesk/CallRelatedList.php new file mode 100644 index 00000000..98ea390e --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/CallRelatedList.php @@ -0,0 +1,78 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['ticket_title']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings; + global $currentModule; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array=getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("CATEGORY",$category); + + // 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 + + $smarty->assign("ID",$focus->id); + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$app_strings['Ticket']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/ConvertAsFAQ.php b/oss/vtiger/trunk/modules/HelpDesk/ConvertAsFAQ.php new file mode 100644 index 00000000..4333ec40 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/ConvertAsFAQ.php @@ -0,0 +1,68 @@ + vtiger_faq column where ticket column is the troubletikcets vtiger_field name & vtiger_faq - column_fields +$ticket_faq_mapping_fields = Array( + 'title'=>'question', + 'product_id'=>'product_id', + 'description'=>'faq_answer', + //'ticketstatus'=>'faqstatus', + //'ticketcategories'=>'faqcategories' + ); +$sql = " select ticketid, title, product_id,vtiger_crmentity.description, solution,vtiger_troubletickets.status, category from vtiger_troubletickets inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid where ticketid=?"; +$res = $adb->pquery($sql, array($_REQUEST['record'])); + +//set all the ticket values to FAQ +foreach($ticket_faq_mapping_fields as $ticket_column => $faq_column) +{ + $focus->column_fields[$faq_column] = $adb->query_result($res,0,$ticket_column); +} + +$focus->save("Faq"); + +if($focus->id != '') +{ + $description = $adb->query_result($res,0,'description'); + $solution = $adb->query_result($res,0,'solution'); + + //Add the solution of the ticket with the FAQ answer + $answer = $description; + if($solution != '') + { + $answer .= "\r\n\r\n".$app_strings['LBL_SOLUTION'].":\r\n".$solution; + } + + //Retrive the ticket comments from the vtiger_ticketcomments vtiger_table and added into the vtiger_faq answer + $sql = "select ticketid, comments, createdtime from vtiger_ticketcomments where ticketid=?"; + $res = $adb->pquery($sql, array($_REQUEST['record'])); + $noofrows = $adb->num_rows($res); + + if($noofrows > 0) + $answer .= "\r\n\r\n".$app_strings['LBL_COMMENTS'].":"; + for($i=0; $i < $noofrows; $i++) + { + $comments = $adb->query_result($res,$i,'comments'); + if($comments != '') + { + $answer .= "\r\n".$comments; + } + } + + $sql1 = "update vtiger_faq set answer=? where id=?"; + $adb->pquery($sql1, array($answer, $focus->id)); +} + +header("Location:index.php?module=Faq&action=DetailView&record=$focus->id&return_module=Faq&return_action=DetailView&return_id=$focus->id"); + +?> diff --git a/oss/vtiger/trunk/modules/HelpDesk/ConvertToEntities.php b/oss/vtiger/trunk/modules/HelpDesk/ConvertToEntities.php new file mode 100644 index 00000000..804da174 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/ConvertToEntities.php @@ -0,0 +1,45 @@ +pquery($query, array()); +for($i=0;$ipquery('select * from vtiger_users where user_name=?', array($_REQUEST['assigned_user_id'])); + $changevalue=$adb->query_result($resultset,0,"id"); + $changekey='assigned_user_id'; + } + $sql="update vtiger_troubletickets set $changekey = ? where id = ?"; + $adb->pquery($sql, array($changevalue, $id)); +} +header("Location: index.php?action=index&module=HelpDesk"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/CustomView.php b/oss/vtiger/trunk/modules/HelpDesk/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/Delete.php b/oss/vtiger/trunk/modules/HelpDesk/Delete.php new file mode 100644 index 00000000..a177c2c8 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/Delete.php @@ -0,0 +1,41 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/DetailView.php b/oss/vtiger/trunk/modules/HelpDesk/DetailView.php new file mode 100644 index 00000000..7792d33c --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/DetailView.php @@ -0,0 +1,146 @@ +retrieve_entity_info($_REQUEST['record'],"HelpDesk"); + $focus->name=$focus->column_fields['ticket_title']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; +} + +//Added code for Error display in sending mail to assigned to user when ticket is created or updated. +if($_REQUEST['mail_error'] != '') +{ + require_once("modules/Emails/mail.php"); + $ticket_owner = getUserName($focus->column_fields['assigned_user_id']); + $error_msg = strip_tags(parseEmailErrorString($_REQUEST['mail_error'])); + $error_msg = $app_strings['LBL_MAIL_NOT_SENT_TO_USER']. ' ' . $ticket_owner. '. ' .$app_strings['LBL_PLS_CHECK_EMAIL_N_SERVER']; + echo $mod_strings['LBL_MAIL_SEND_STATUS'].' '.$error_msg.''; +} + +global $app_strings; +global $mod_strings; +global $currentModule, $singlepane_view; + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$focus->id = $_REQUEST['record']; +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); +$smarty->assign("TICKETID", vtlib_purify($_REQUEST['record'])); + +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("SINGLE_MOD", 'HelpDesk'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); +$smarty->assign("UPDATEINFO",updateInfo($_REQUEST['record'])); + +if(isPermitted("HelpDesk","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("HelpDesk","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +//Added button for Convert the ticket to FAQ +if(isPermitted("Faq","EditView",'') == 'yes') + $smarty->assign("CONVERTASFAQ","permitted"); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +// 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 + +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); +if(isPermitted("HelpDesk","Merge",'') == 'yes') +{ + global $current_user; + require("user_privileges/user_privileges_".$current_user->id.".php"); + require_once('include/utils/UserInfoUtil.php'); + $wordTemplateResult = fetchWordTemplateList("HelpDesk"); + $tempCount = $adb->num_rows($wordTemplateResult); + $tempVal = $adb->fetch_array($wordTemplateResult); + for($templateCount=0;$templateCount<$tempCount;$templateCount++) + { + $optionString[$tempVal["templateid"]]=$tempVal["filename"]; + $tempVal = $adb->fetch_array($wordTemplateResult); + } + if($is_admin) + $smarty->assign("MERGEBUTTON","permitted"); + elseif($tempCount >0) + $smarty->assign("MERGEBUTTON","permitted"); + $smarty->assign("TEMPLATECOUNT",$tempCount); + $smarty->assign("WORDTEMPLATEOPTIONS",$app_strings['LBL_SELECT_TEMPLATE_TO_MAIL_MERGE']); + $smarty->assign("TOPTIONS",$optionString); +} + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$tabid = getTabid("HelpDesk"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +//Added to display the ticket comments information +$smarty->assign("COMMENT_BLOCK",$focus->getCommentInformation($_REQUEST['record'])); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} +$smarty->assign("SinglePane_View", $singlepane_view); + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("DetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/DetailViewAjax.php b/oss/vtiger/trunk/modules/HelpDesk/DetailViewAjax.php new file mode 100644 index 00000000..9bd3d229 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/DetailViewAjax.php @@ -0,0 +1,116 @@ +retrieve_entity_info($crmid,"HelpDesk"); + + //Added to avoid the comment save, when we edit other fields through ajax edit + if($fieldname != 'comments') + $modObj->column_fields['comments'] = ''; + + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + + //Added to construct the update log for Ticket history + $assigned_group_name = getGroupName($_REQUEST['assigned_group_id']); + $assigntype = $_REQUEST['assigntype']; + + $fldvalue = $modObj->constructUpdateLog($modObj, $modObj->mode, $assigned_group_name, $assigntype); + $fldvalue = from_html($fldvalue,($modObj->mode == 'edit')?true:false); + + $modObj->save("HelpDesk"); + global $mod_strings; + if($fieldname == "solution" || $fieldname == "comments" || $fieldname =="assigned_user_id" ||($fieldname == "ticketstatus" && $fieldvalue == $mod_strings['Closed'])){ + require_once('modules/Emails/mail.php'); + $user_emailid = getUserEmailId('id',$modObj->column_fields['assigned_user_id']); + + $subject = $modObj->column_fields['ticket_no'] . ' [ '.$mod_strings['LBL_TICKET_ID'].' : '.$modObj->id.' ] Re : '.$modObj->column_fields['ticket_title']; + $parent_id = $modObj->column_fields['parent_id']; + if(!empty($parent_id) && $parent_id!=0){ + $parent_module = getSalesEntityType($parent_id); + if($parent_module == 'Contacts'){ + $result = $adb->pquery("select * from vtiger_contactdetails where contactid=?", array($parent_id)); + $emailoptout = $adb->query_result($result,0,'emailoptout'); + $contactname = $adb->query_result($result,0,'firstname').' '.$adb->query_result($result,0,'lastname'); + $parentname = $contactname; + $contact_mailid = $adb->query_result($result,0,'email'); + } + if($parent_module == 'Accounts'){ + $result = $adb->pquery("select * from vtiger_account where accountid=?", array($parent_id)); + $emailoptout = $adb->query_result($result,0,'emailoptout'); + $parentname = $adb->query_result($result,0,'accountname'); + } + if($contact_mailid != ''){ + $sql = "select * from vtiger_portalinfo where user_name=?"; + $isactive = $adb->query_result($adb->pquery($sql, array($contact_mailid)),0,'isactive'); + } + + if($isactive == 1){ + $url = "Ticket Details"; + $email_body = $subject.'

'.getPortalInfo_Ticket($modObj->id,$sub,$contactname,$url,"edit"); + }else{ + $data['sub']=$modObj->column_fields['ticket_title']; + $data['parent_name']=$parentname; + $data['status']=$modObj->column_fields['ticketstatus']; + $data['category']=$modObj->column_fields['ticketcategories']; + $data['severity'] = $modObj->column_fields['ticketseverities']; + $data['priority']=$modObj->column_fields['ticketpriorities']; + $data['description']=$modObj->column_fields['description']; + $data['solution'] = $modObj->column_fields['solution']; + $data['mode']= 'edit'; + $email_body = getTicketDetails($modObj->id,$data); + } + } + if($user_emailid != ''){ + $mail_status = send_mail('HelpDesk',$user_emailid,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + } + if($emailoptout == 0){ + //send mail to parent + if(!empty($parent_id)){ + $parent_email = getParentMailId($parent_module,$parent_id); + $mail_status = send_mail('HelpDesk',$parent_email,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + } + } + } + //update the log information for ticket history + $adb->pquery("update vtiger_troubletickets set update_log=? where ticketid=?", array($fldvalue, $modObj->id)); + + if($modObj->id != ""){ + if($fieldname == "comments"){ + $comments = $modObj->getCommentInformation($modObj->id); + echo ":#:SUCCESS".$comments; + }else{ + echo ":#:SUCCESS"; + } + }else{ + echo ":#:FAILURE"; + } + }else{ + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/EditView.php b/oss/vtiger/trunk/modules/HelpDesk/EditView.php new file mode 100644 index 00000000..d7f211ab --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/EditView.php @@ -0,0 +1,147 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if(isset($_REQUEST['record']) && $_REQUEST['record'] !='') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"HelpDesk"); + $focus->name=$focus->column_fields['ticket_title']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $old_id = $_REQUEST['record']; + if (! empty($focus->filename) ) + { + $old_id = $focus->id; + } + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $smarty->assign("BASBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS')); +} + +$smarty->assign("OP_MODE",$disp_view); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Ticket'); + + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); + +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} +$smarty->assign("ID", $focus->id); +$smarty->assign("OLD_ID", $old_id ); +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); + $smarty->assign("OLDSMOWNERID", $focus->column_fields['assigned_user_id']); +} + +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['product_id'])) +$smarty->assign("PRODUCTID", vtlib_purify($_REQUEST['product_id'])); +if (isset($_REQUEST['return_viewname'])) +$smarty->assign("RETURN_VIEWNAME", vtlib_purify($_REQUEST['return_viewname'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +$tabid = getTabid("HelpDesk"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +if($_REQUEST['record'] != '') +{ + //Added to display the ticket comments information + $smarty->assign("COMMENT_BLOCK",$focus->getCommentInformation($_REQUEST['record'])); +} +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 || $adb->num_rows($mod_seq_string) == 0 || $focus->checkModuleSeqNumber($focus->table_name, $mod_seq_field['column'], $mod_seq_prefix.$mod_seq_no)) + echo '
'. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + 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"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/ExportRecords.php b/oss/vtiger/trunk/modules/HelpDesk/ExportRecords.php new file mode 100644 index 00000000..19858676 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/ExportRecords.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/HelpDesk/FindDuplicateRecords.php new file mode 100644 index 00000000..a1ff9757 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/FindDuplicateRecords.php @@ -0,0 +1,106 @@ +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 "
"; + echo "
+ + + + + + + + + +
+ $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
+ $app_strings[LBL_GO_BACK]
+
+
"; + echo "
"; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/HelpDesk.js b/oss/vtiger/trunk/modules/HelpDesk/HelpDesk.js new file mode 100644 index 00000000..c757a9dd --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/HelpDesk.js @@ -0,0 +1,80 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + +document.write(" +pquery($sql, array($templateid)); +$temparray = $adb->fetch_array($result); + +$fileContent = $temparray['data']; +$filename=html_entity_decode($temparray['filename'], ENT_QUOTES, $default_charset); +// Fix For: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$filename= $randomfilename . "_word.doc"; + +$filesize=$temparray['filesize']; +$wordtemplatedownloadpath =$root_directory ."/test/wordtemplatedownload/"; + +$handle = fopen($wordtemplatedownloadpath .$filename,"wb"); +fwrite($handle,base64_decode($fileContent),$filesize); +fclose($handle); + +//<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>> +$mass_merge = $_REQUEST['allselectedboxes']; +$single_record = $_REQUEST['record']; + +if($mass_merge != "") +{ + $mass_merge = explode(";",$mass_merge); + $temp_mass_merge = $mass_merge; + if(array_pop($temp_mass_merge)=="") + array_pop($mass_merge); + //$mass_merge = implode(",",$mass_merge); +} +else if($single_record != "") +{ + $mass_merge = $single_record; +} +else +{ + die("Record Id is not found, cannot merge the document"); +} + +//<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>> + +global $current_user; +require('user_privileges/user_privileges_'.$current_user->id.'.php'); +if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users" || $module == "Emails") +{ + $query1="select vtiger_tab.name,vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where vtiger_field.tabid in (13,4,6) and vtiger_field.uitype <> 61 and block <> 75 and block <> 30 and vtiger_field.presence in (0,2) order by vtiger_field.tablename"; + $params1 = array(); +} +else +{ + $profileList = getCurrentUserProfileList(); + $query1="select vtiger_tab.name,vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid in (13,4,6) and vtiger_field.uitype <> 61 and block <> 75 and block <> 30 AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid order by vtiger_field.tablename"; + $params1 = array($profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query1 = fixPostgresQuery( $query1, $log, 0); +} +$result = $adb->pquery($query1, $params1); +$y=$adb->num_rows($result); + +for ($x=0; $x<$y; $x++) +{ + $tablename = $adb->query_result($result,$x,"tablename"); + $columnname = $adb->query_result($result,$x,"columnname"); + $modulename = $adb->query_result($result,$x,"name"); + + $column_name = $tablename.".".$columnname; + + if($columnname == "parent_id") + { + $column_name = "case crmentityRelHelpDesk.setype when 'Accounts' then accountRelHelpDesk.accountname when 'Contacts' then concat(contactdetailsRelHelpDesk.firstname,' ',contactdetailsRelHelpDesk.lastname) End"; + } + if($columnname == "product_id") + { + $column_name = "productsRel.productname"; + } + if($tablename == "vtiger_crmentity") + { + if($modulename == "Contacts") + { + $tablename = "crmentityContacts"; + $column_name = $tablename.".".$columnname; + } + if($modulename == "Accounts") + { + $tablename = "crmentityAccounts"; + $column_name = $tablename.".".$columnname; + } + + } + + if($columnname == "smownerid") + { + if($modulename == "Accounts") + { + $column_name = "case when (usersAccounts.user_name not like '') then concat(usersAccounts.last_name,' ',usersAccounts.first_name) else groupsAccounts.groupname end as username"; + } + if($modulename == "Contacts") + { + $column_name = "case when (usersContacts.user_name not like '') then concat(usersContacts.last_name,' ',usersContacts.first_name) else groupsContacts.groupname end as username"; + } + if($modulename == "HelpDesk") + { + $column_name = "case when (vtiger_users.user_name not like '') then concat(vtiger_users.last_name,' ',vtiger_users.first_name) else vtiger_groups.groupname end as userhelpname,vtiger_users.first_name,vtiger_users.last_name,vtiger_users.user_name,vtiger_users.yahoo_id,vtiger_users.title,vtiger_users.phone_work,vtiger_users.department,vtiger_users.phone_mobile,vtiger_users.phone_other,vtiger_users.phone_fax,vtiger_users.email1,vtiger_users.phone_home,vtiger_users.email2,vtiger_users.address_street,vtiger_users.address_city,vtiger_users.address_state,vtiger_users.address_postalcode,vtiger_users.address_country"; + } + } + if($columnname == "parentid") + { + $column_name = "accountAccount.accountname"; + } + if($columnname == "accountid") + { + $column_name = "accountContacts.accountname"; + } + if($columnname == "reportsto") + { + $column_name = "contactdetailsContacts.lastname"; + } + + $querycolumns[$x] = $column_name; + + if($modulename == "Accounts") + { + $field_label[$x] = "ACCOUNT_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + } + if($modulename == "Contacts") + { + $field_label[$x] = "CONTACT_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + } + if($modulename == "HelpDesk") + { + $field_label[$x] = "TICKET_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + if($columnname == "smownerid") + { + $field_label[$x] = $field_label[$x].",USER_FIRSTNAME,USER_LASTNAME,USER_USERNAME,USER_YAHOOID,USER_TITLE,USER_OFFICEPHONE,USER_DEPARTMENT,USER_MOBILE,USER_OTHERPHONE,USER_FAX,USER_EMAIL,USER_HOMEPHONE,USER_OTHEREMAIL,USER_PRIMARYADDRESS,USER_CITY,USER_STATE,USER_POSTALCODE,USER_COUNTRY"; + } + } + +} +$csvheader = implode(",",$field_label); +//<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>> + +if(count($querycolumns) > 0) +{ + $selectcolumns = implode($querycolumns,","); + + $query ="select ".$selectcolumns." from vtiger_troubletickets + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid + inner join vtiger_ticketcf on vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + left join vtiger_crmentity as crmentityRelHelpDesk on crmentityRelHelpDesk.crmid = vtiger_troubletickets.parent_id + left join vtiger_account as accountRelHelpDesk on accountRelHelpDesk.accountid=crmentityRelHelpDesk.crmid + left join vtiger_contactdetails as contactdetailsRelHelpDesk on contactdetailsRelHelpDesk.contactid= crmentityRelHelpDesk.crmid + left join vtiger_products as productsRel on productsRel.productid = vtiger_troubletickets.product_id + left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_account on vtiger_account.accountid = vtiger_troubletickets.parent_id + left join vtiger_crmentity as crmentityAccounts on crmentityAccounts.crmid = vtiger_account.accountid + left join vtiger_accountbillads on vtiger_accountbillads.accountaddressid = vtiger_account.accountid + left join vtiger_accountshipads on vtiger_accountshipads.accountaddressid = vtiger_account.accountid + left join vtiger_accountscf on vtiger_accountbillads.accountaddressid = vtiger_accountscf.accountid + left join vtiger_account as accountAccount on accountAccount.accountid = vtiger_troubletickets.parent_id + left join vtiger_users as usersAccounts on usersAccounts.id = crmentityAccounts.smownerid + LEFT JOIN vtiger_groups as groupsAccounts + ON groupsAccounts.groupid = vtiger_crmentity.smownerid + left join vtiger_contactdetails on vtiger_contactdetails.contactid = vtiger_troubletickets.parent_id + left join vtiger_crmentity as crmentityContacts on crmentityContacts.crmid = vtiger_contactdetails.contactid + left join vtiger_contactaddress on vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + left join vtiger_contactsubdetails on vtiger_contactdetails.contactid = vtiger_contactsubdetails.contactsubscriptionid + left join vtiger_contactscf on vtiger_contactdetails.contactid = vtiger_contactscf.contactid + left join vtiger_customerdetails on vtiger_contactdetails.contactid = vtiger_customerdetails.customerid + left join vtiger_contactdetails as contactdetailsContacts on contactdetailsContacts.contactid = vtiger_contactdetails.reportsto + left join vtiger_account as accountContacts on accountContacts.accountid = vtiger_contactdetails.accountid + left join vtiger_users as usersContacts on usersContacts.id = crmentityContacts.smownerid + LEFT JOIN vtiger_groups as groupsContacts + ON groupsContacts.groupid = vtiger_crmentity.smownerid + where vtiger_crmentity.deleted=0 and ((crmentityContacts.deleted=0 || crmentityContacts.deleted is null)||(crmentityAccounts.deleted=0 || crmentityAccounts.deleted is null)) + and vtiger_troubletickets.ticketid in (". generateQuestionMarks($mass_merge) .")"; + + $result = $adb->pquery($query, array($mass_merge)); + $avail_pick_arr = getAccessPickListValues('HelpDesk'); + while($columnValues = $adb->fetch_array($result)) + { + $y=$adb->num_fields($result); + for($x=0; $x<$y; $x++) + { + $value = $columnValues[$x]; + foreach($columnValues as $key=>$val) + { + if($val == $value && $value != '') + { + if(array_key_exists($key,$avail_pick_arr)) + { + if(!in_array($val,$avail_pick_arr[$key])) + { + $value = "Not Accessible"; + } + } + } + } + //<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>> + if(trim($value) == "--None--" || trim($value) == "--none--") + { + $value = ""; + } + //<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>> + $actual_values[$x] = $value; + $actual_values[$x] = str_replace('"'," ",$actual_values[$x]); + //if value contains any line feed or carriage return replace the value with ".value." + if (preg_match ("/(\r\n)/", $actual_values[$x])) + { + $actual_values[$x] = '"'.$actual_values[$x].'"'; + } + $actual_values[$x] = decode_html(str_replace(","," ",$actual_values[$x])); + } + $mergevalue[] = implode($actual_values,","); + } + $csvdata = implode($mergevalue,"###"); +} +else +{ + die("No fields to do Merge"); +} +// Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$datafilename = $randomfilename . "_data.csv"; + +$handle = fopen($wordtemplatedownloadpath.$datafilename,"wb"); +fwrite($handle,$csvheader."\r\n"); +fwrite($handle,str_replace("###","\r\n",$csvdata)); +fclose($handle); + +?> + + + diff --git a/oss/vtiger/trunk/modules/HelpDesk/Popup.php b/oss/vtiger/trunk/modules/HelpDesk/Popup.php new file mode 100644 index 00000000..e2aaa7de --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/Popup.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/ProcessDuplicates.php b/oss/vtiger/trunk/modules/HelpDesk/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/HelpDesk/QuickCreate.php b/oss/vtiger/trunk/modules/HelpDesk/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/Save.php b/oss/vtiger/trunk/modules/HelpDesk/Save.php new file mode 100644 index 00000000..a6761f81 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/Save.php @@ -0,0 +1,189 @@ +pquery("select * from vtiger_crmentity where crmid=?", array($focus->id)); + $old_user_id = $adb->query_result($usr_qry,0,"smownerid"); +} +$grp_name = getGroupName($_REQUEST['assigned_group_id']); + +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']; +} + +$fldvalue = $focus->constructUpdateLog($focus, $mode, $grp_name, $_REQUEST['assigntype']); +$fldvalue = from_html($fldvalue,($mode == 'edit')?true:false); + +$focus->save("HelpDesk"); + +//After save the record, we should update the log +$adb->pquery("update vtiger_troubletickets set update_log=? where ticketid=?", array($fldvalue,$focus->id)); + +$return_id = $focus->id; + +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "HelpDesk"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +if($_REQUEST['mode'] == 'edit') + $reply = 'Re : '; +else + $reply = ''; + +$subject = $focus->column_fields['ticket_no'] . ' [ '.$mod_strings['LBL_TICKET_ID'].' : '.$focus->id.' ] '.$reply.$_REQUEST['ticket_title']; +$bodysubject = $mod_strings['Ticket No'] .":
" . $focus->column_fields['ticket_no'] . "
" . $mod_strings['LBL_TICKET_ID'].' : '.$focus->id.'
'.$mod_strings['LBL_SUBJECT'].$_REQUEST['ticket_title']; + +$emailoptout = 0; + +//To get the emailoptout vtiger_field value and then decide whether send mail about the tickets or not +if($focus->column_fields['parent_id'] != '') +{ + $parent_module = getSalesEntityType($focus->column_fields['parent_id']); + if($parent_module == 'Contacts') + { + $result = $adb->pquery("select * from vtiger_contactdetails where contactid=?", array($focus->column_fields['parent_id'])); + $emailoptout = $adb->query_result($result,0,'emailoptout'); + $contactname = $adb->query_result($result,0,'firstname').' '.$adb->query_result($result,0,'lastname'); + $parentname = $contactname; + $contact_mailid = $adb->query_result($result,0,'email'); + } + if($parent_module == 'Accounts') + { + $result = $adb->pquery("select * from vtiger_account where accountid=?", array($focus->column_fields['parent_id'])); + $emailoptout = $adb->query_result($result,0,'emailoptout'); + $parentname = $adb->query_result($result,0,'accountname'); + } +} + +//Get the status of the vtiger_portal user. if the customer is active then send the vtiger_portal link in the mail +if($contact_mailid != '') +{ + $sql = "select * from vtiger_portalinfo where user_name=?"; + $isactive = $adb->query_result($adb->pquery($sql, array($contact_mailid)),0,'isactive'); +} +if($isactive == 1) +{ + $url = "".$mod_strings['LBL_TICKET_DETAILS'].""; + $email_body = $bodysubject.'

'.getPortalInfo_Ticket($focus->id,$_REQUEST['ticket_title'],$contactname,$url,$_REQUEST['mode']); +} +else +{ + $data['sub']=$_REQUEST['ticket_title']; + $data['parent_name']=$parentname; + $data['status']=$focus->column_fields['ticketstatus']; + $data['category']=$focus->column_fields['ticketcategories']; + $data['severity'] = $focus->column_fields['ticketseverities']; + $data['priority']=$focus->column_fields['ticketpriorities']; + $data['description']=$focus->column_fields['description']; + $data['solution'] = $focus->column_fields['solution']; + $data['mode']= $_REQUEST['mode']; + $email_body = getTicketDetails($focus->id,$data); +} +$_REQUEST['return_id'] = $return_id; + +if($_REQUEST['return_module'] == 'Products' & $_REQUEST['product_id'] != '' && $focus->id != '') + $return_id = vtlib_purify($_REQUEST['product_id']); + +//send mail to the assigned to user and the parent to whom this ticket is assigned +require_once('modules/Emails/mail.php'); +$user_emailid = getUserEmailId('id',$focus->column_fields['assigned_user_id']); + +if($user_emailid != '') +{ + if($_REQUEST['mode'] != 'edit') + { + $mail_status = send_mail('HelpDesk',$user_emailid,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + } + else + { + if(($focus->column_fields['ticketstatus'] == $mod_strings["Closed"]) || ($focus->column_fields['comments'] != '') || ($_REQUEST['helpdesk_solution'] != $_REQUEST['solution']) || ($focus->column_fields['assigned_user_id'] != $old_user_id)) + { + $mail_status = send_mail('HelpDesk',$user_emailid,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + } + + } + + $mail_status_str = $user_emailid."=".$mail_status."&&&"; +} +else +{ + $mail_status_str = "'".$to_email."'=0&&&"; +} +//added condition to check the emailoptout(this is for contacts and vtiger_accounts.) +if($emailoptout == 0) +{ + //send mail to parent + if($_REQUEST['parent_id'] != '' && $_REQUEST['parent_type'] != '') + { + $parentmodule = $_REQUEST['parent_type']; + $parentid = $_REQUEST['parent_id']; + + $parent_email = getParentMailId($parentmodule,$parentid); + if($_REQUEST['mode'] != 'edit') + { + $mail_status = send_mail('HelpDesk',$parent_email,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + } + else + { + if(( $focus->column_fields['ticketstatus']== $mod_strings["Closed"]) || ($focus->column_fields['comments'] != '' ) || ($_REQUEST['helpdesk_solution'] != $_REQUEST['solution'])) + { + $mail_status = send_mail('HelpDesk',$parent_email,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + } + } + $mail_status_str .= $parent_email."=".$mail_status."&&&"; + } +} +else +{ + $adb->println("'".$parentname."' is not want to get the email about the ticket details as emailoptout is selected"); +} + +if ($mail_status != '') { + $mail_error_status = getMailErrorString($mail_status_str); +} + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); +header("Location: index.php?action=$return_action&module=$return_module&parenttab=$parenttab&record=$return_id&$mail_error_status&viewname=$return_viewname&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/Settings.php b/oss/vtiger/trunk/modules/HelpDesk/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/TagCloud.php b/oss/vtiger/trunk/modules/HelpDesk/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/UnifiedSearch.php b/oss/vtiger/trunk/modules/HelpDesk/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/HelpDesk/index.php b/oss/vtiger/trunk/modules/HelpDesk/index.php new file mode 100644 index 00000000..72094552 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/index.php @@ -0,0 +1,17 @@ + diff --git a/oss/vtiger/trunk/modules/HelpDesk/language/en_us.lang.php b/oss/vtiger/trunk/modules/HelpDesk/language/en_us.lang.php new file mode 100644 index 00000000..2d32d06f --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/language/en_us.lang.php @@ -0,0 +1,221 @@ +'Trouble Tickets', +'LBL_GROUP'=>'Group', +'LBL_ACCOUNT_NAME'=>'Account Name', +'LBL_CONTACT_NAME'=>'Contact Name', +'LBL_SUBJECT'=>'Subject', +'LBL_NEW_FORM_TITLE' => 'New Ticket', +'LBL_DESCRIPTION'=>'Description', +'NTC_DELETE_CONFIRMATION'=>'Are you sure you want to delete this record?', +'LBL_CUSTOM_FIELD_SETTINGS'=>'Custom Field Settings:', +'LBL_PICKLIST_FIELD_SETTINGS'=>'Picklist Field Settings:', +'Leads'=>'Lead', +'Accounts'=>'Account', +'Contacts'=>'Contact', +'Opportunities'=>'Opportunity', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', + +'LBL_ACCOUNT'=>'Account', +'LBL_OPPURTUNITY'=>'Oppurtunity', +'LBL_PRODUCT'=>'Product', + +'LBL_COLON'=>':', +'LBL_TICKET'=>'Ticket', +'LBL_CONTACT'=>'Contact', +'LBL_STATUS'=>'Status', +'LBL_ASSIGNED_TO'=>'Assigned To', +'LBL_FAQ'=>'FAQ', +'LBL_VIEW_FAQS'=>'View FAQs', +'LBL_ADD_FAQS'=>'Add FAQs', +'LBL_FAQ_CATEGORIES'=>'FAQ Categories', + +'LBL_PRIORITY'=>'Priority', +'LBL_CATEGORY'=>'Category', + +'LBL_ANSWER'=>'Answer', +'LBL_COMMENTS'=>'COMMENTS', + +'LBL_AUTHOR'=>'Author', +'LBL_QUESTION'=>'Question', + +//Added vtiger_fields for File Attachment and Mail send in Tickets +'LBL_ATTACHMENTS'=>'Attachments', +'LBL_NEW_ATTACHMENT'=>'New Attachment', +'LBL_SEND_MAIL'=>'Send Mail', + +//Added vtiger_fields for search option in TicketsList -- 4Beta +'LBL_CREATED_DATE'=>'Created Date', +'LBL_IS'=>'is', +'LBL_IS_NOT'=>'is not', +'LBL_IS_BEFORE'=>'is before', +'LBL_IS_AFTER'=>'is after', +'LBL_STATISTICS'=>'Statistics', +'LBL_TICKET_ID'=>'Ticket Id', +'LBL_MY_TICKETS'=>'My Tickets', +"LBL_MY_FAQ"=>"My Faq's", +'LBL_ESTIMATED_FINISHING_TIME'=>'Estimated Finishing Time', +'LBL_SELECT_TICKET'=>'Select Ticket', +'LBL_CHANGE_OWNER'=>'Change Owner', +'LBL_CHANGE_STATUS'=>'Change Status', +'LBL_TICKET_TITLE'=>'Title', +'LBL_TICKET_DESCRIPTION'=>'Description', +'LBL_TICKET_CATEGORY'=>'Category', +'LBL_TICKET_PRIORITY'=>'Priority', + +//Added vtiger_fields after 4 -- Beta +'LBL_NEW_TICKET'=>'New Ticket', +'LBL_TICKET_INFORMATION'=>'Ticket Information', + +'LBL_LIST_FORM_TITLE'=>'Tickets List', +'LBL_SEARCH_FORM_TITLE'=>'Ticket Search', + +//Added vtiger_fields after RC1 - Release +'LBL_CHOOSE_A_VIEW'=>'Choose a View...', +'LBL_ALL'=>'All', +'LBL_LOW'=>'Low', +'LBL_MEDIUM'=>'Medium', +'LBL_HIGH'=>'High', +'LBL_CRITICAL'=>'Critical', +//Added vtiger_fields for 4GA +'Assigned To'=>'Assigned To', +'Contact Name'=>'Contact Name', +'Priority'=>'Priority', +'Status'=>'Status', +'Category'=>'Category', +'Update History'=>'Update History', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Title'=>'Title', +'Description'=>'Description', + +'LBL_TICKET_CUMULATIVE_STATISTICS'=>'Ticket Cumulative Statistics:', +'LBL_CASE_TOPIC'=>'Case Topic', +'LBL_OPEN'=>'Open', +'LBL_CLOSED'=>'Closed', +'LBL_TOTAL'=>'Total', +'LBL_TICKET_HISTORY'=>'Ticket History', +'LBL_CATEGORIES'=>'Categories', +'LBL_PRIORITIES'=>'Priorities', +'LBL_SUPPORTERS'=>'Supporters', + +//Added vtiger_fields after 4_0_1 +'LBL_TICKET_RESOLUTION'=>'Solution Information', +'Solution'=>'Solution', +'Add Comment'=>'Add Comment', +'LBL_ADD_COMMENT'=>'Add Comment',//give the same value given to the above string 'Add Comment' + +//Added for 4.2 Release -- CustomView +'Ticket ID'=>'Ticket ID', +'Subject'=>'Subject', + +//Added after 4.2 alpha +'Severity'=>'Severity', +'Product Name'=>'Product Name', +'Related To'=>'Related To', +'LBL_MORE'=>'More', + +'LBL_TICKETS'=>'Tickets', + +//Added on 09-12-2005 +'LBL_CUMULATIVE_STATISTICS'=>'Cumulative Statistics', + +//Added on 12-12-2005 +'LBL_CONVERT_AS_FAQ_BUTTON_TITLE'=>'Convert As FAQ', +'LBL_CONVERT_AS_FAQ_BUTTON_KEY'=>'C', +'LBL_CONVERT_AS_FAQ_BUTTON_LABEL'=>'Convert As FAQ', +'Attachment'=>'Attachment', +'LBL_COMMENT_INFORMATION'=>'Comment Information', + +//Added for existing picklist entries + +'Big Problem'=>'Big Problem', +'Small Problem'=>'Small Problem', +'Other Problem'=>'Other Problem', + +'Low'=>'Low', +'Normal'=>'Normal', +'High'=>'High', +'Urgent'=>'Urgent', + +'Minor'=>'Minor', +'Major'=>'Major', +'Feature'=>'Feature', +'Critical'=>'Critical', + +'Open'=>'Open', +'In Progress'=>'In Progress', +'Wait For Response'=>'Wait For Response', +'Closed'=>'Closed', + +//added to support i18n in ticket mails +'Hi' => 'Hi', +'Dear'=> 'Dear', +'LBL_PORTAL_BODY_MAILINFO'=> 'The Ticket is', +'LBL_DETAIL' => 'the details are :', +'LBL_REGARDS'=> 'Regards', +'LBL_TEAM'=> 'HelpDesk Team', +'LBL_TICKET_DETAILS' => 'Ticket Details', +'LBL_SUBJECT' => 'Subject : ', +'created' => 'created', +'replied' => 'replied', +'reply'=>'There is a reply to', +'customer_portal' => 'in the "Customer Portal" at VTiger.', +'link' => 'You can use the following link to view the replies made:', +'Thanks' => 'Thanks', +'Support_team' => 'Vtiger Support Team', + +// Added/Updated for vtiger CRM 5.0.4 + +//this label for customerportal. +'LBL_STATUS_CLOSED' =>'Closed',//Do not convert this label. This is used to check the status. If the status 'Closed' is changed in vtigerCRM server side then you have to change in customerportal language file also. +'LBL_STATUS_UPDATE' => 'Ticket status is updated as', +'LBL_COULDNOT_CLOSED' => 'Ticket could not be', +'LBL_CUSTOMER_COMMENTS' => 'Customer has provided the following additional information to your reply:', +'LBL_RESPOND'=> 'Kindly respond to above ticket at the earliest.', +'LBL_REGARDS' =>'Regards', +'LBL_SUPPORT_ADMIN' => 'Support Administrator', +'LBL_RESPONDTO_TICKETID' =>'Respond to Ticket ID', +'LBL_CUSTOMER_PORTAL' => 'in Customer Portal - URGENT', +'LBL_LOGIN_DETAILS' => 'Following are your Customer Portal login details :', +'LBL_MAIL_COULDNOT_SENT' =>'Mail could not be sent', +'LBL_USERNAME' => 'User Name :', +'LBL_PASSWORD' => 'Password :', +'LBL_SUBJECT_PORTAL_LOGIN_DETAILS' => 'Regarding your Customer Portal login details', +'LBL_GIVE_MAILID' => 'Please give your email id', +'LBL_CHECK_MAILID' => 'Please check your email id for Customer Portal', +'LBL_LOGIN_REVOKED' => 'Your login is revoked. Please contact your admin.', +'LBL_MAIL_SENT' => 'Mail has been sent to your mail id with the customer portal login details', +'LBL_ALTBODY' => 'This is the body in plain text for non-HTML mail clients', + +// Added after 5.0.4 GA + +// Module Sequence Numbering +'Ticket No' => 'Ticket No', +// END +); + +?> diff --git a/oss/vtiger/trunk/modules/HelpDesk/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/HelpDesk/language/zh_cn.lang.php new file mode 100644 index 00000000..eea95264 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/language/zh_cn.lang.php @@ -0,0 +1,221 @@ + '服务台', + 'LBL_GROUP' => '用户组', + 'LBL_ACCOUNT_NAME' => '客户名称', + 'LBL_CONTACT_NAME' => '联系人名称', + 'LBL_SUBJECT' => '标题', + 'LBL_NEW_FORM_TITLE' => '新增事件', + 'LBL_DESCRIPTION' => '描述', + 'NTC_DELETE_CONFIRMATION' => '您确定要删除这笔记录?', + 'LBL_CUSTOM_FIELD_SETTINGS' => '自订字段设定:', + 'LBL_PICKLIST_FIELD_SETTINGS' => '列表字段设定:', + 'Leads' => '潜在客户', + 'Accounts' => '客户', + 'Contacts' => '联系人', + 'Opportunities' => '潜在案件', + 'LBL_TICKET_INFORMATION' => '事件信息', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息', + 'LBL_ACCOUNT' => '客户', + 'LBL_OPPURTUNITY' => '潜在案件', + 'LBL_PRODUCT' => '商品', + 'LBL_COLON' => ':', + + 'LBL_TICKET' => '事件', + 'LBL_CONTACT' => '联系人', + 'LBL_STATUS' => '职位', + 'LBL_ASSIGNED_TO' => '负责人', + 'LBL_FAQ' => '常见问答', + 'LBL_VIEW_FAQS' => '观看问答', + 'LBL_ADD_FAQS' => '新增问答', + 'LBL_FAQ_CATEGORIES' => '问答类别', + + 'LBL_PRIORITY' => '前置', + 'LBL_CATEGORY' => '类别', + +'LBL_ANSWER'=>'回答', +'LBL_COMMENTS'=>'注释', + +'LBL_AUTHOR'=>'作者', +'LBL_QUESTION'=>'问题', + +//Added vtiger_fields for File Attachment and Mail send in Tickets + 'LBL_ATTACHMENTS' => '附件', + 'LBL_NEW_ATTACHMENT' => '新增附件', + 'LBL_SEND_MAIL' => '寄出邮件', + +//Added vtiger_fields for search option in TicketsList -- 4Beta + 'LBL_CREATED_DATE' => '建立日期', + 'LBL_IS' => '是', + 'LBL_IS_NOT' => '不是', + 'LBL_IS_BEFORE' => '在之前', + 'LBL_IS_AFTER' => '在之后', + 'LBL_STATISTICS' => '统计资料', + 'LBL_TICKET_ID' => '事件编号', + 'LBL_MY_TICKETS' => '我的事件', + 'LBL_MY_FAQ' => '我的问答集', + 'LBL_ESTIMATED_FINISHING_TIME' => '预估完成时间', + 'LBL_SELECT_TICKET' => '选择事件', + 'LBL_CHANGE_OWNER' => '改变拥有人', + 'LBL_CHANGE_STATUS' => '改变职位', + 'LBL_TICKET_TITLE' => '标题', + 'LBL_TICKET_DESCRIPTION' => '描述', + 'LBL_TICKET_CATEGORY' => '类别', + 'LBL_TICKET_PRIORITY' => '前置', + +//Added vtiger_fields after 4 -- Beta +'LBL_NEW_TICKET'=>'新增事件', +'LBL_TICKET_INFORMATION'=>'事件信息', + +'LBL_LIST_FORM_TITLE'=>'事件列表', +'LBL_SEARCH_FORM_TITLE'=>'事件搜索', + +//Added vtiger_fields after RC1 - Release +'LBL_CHOOSE_A_VIEW'=>'选择观看...', +'LBL_ALL' => '全部', + 'LBL_LOW' => '低', + 'LBL_MEDIUM' => '中', + 'LBL_HIGH' => '高', + 'LBL_CRITICAL' => '特急', +//Added vtiger_fields for 4GA +'Assigned To' => '负责人', + 'Contact Name' => '联系人名称', + 'Priority' => '前置', + 'Status' => '状态', + 'Category' => '类别', + 'Update History' => '更新记录', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Title' => '标题', + 'Description' => '描述', + +'LBL_TICKET_CUMULATIVE_STATISTICS' => '事件累计统计信息:', + 'LBL_CASE_TOPIC' => '案件标题', + 'LBL_OPEN' => '开启', + 'LBL_CLOSED' => '关闭', + 'LBL_TOTAL' => '合计', + 'LBL_TICKET_HISTORY' => '事件记录:', + 'LBL_CATEGORIES' => '类别', + 'LBL_PRIORITIES' => '前置', + 'LBL_SUPPORTERS' => '支持者', + +//Added vtiger_fields after 4_0_1 +'LBL_TICKET_RESOLUTION'=>'解决方案详情', +'Solution'=>'解决方案', +'Add Comment'=>'添加注释', +'LBL_ADD_COMMENT'=>'添加注释',//give the same value given to the above string 'Add Comment' + +//Added for 4.2 Release -- CustomView + 'Ticket ID' => '事件编号', + 'Subject' => '主旨', + +//Added after 4.2 alpha + 'Severity' => '俭朴', + 'Product Name' => '产品名称', + 'Related To' => '相关信息', + 'LBL_MORE' => '更多', + + 'LBL_TICKETS' => '事件', + +//Added on 09-12-2005 + 'LBL_CUMULATIVE_STATISTICS' => '累积统计', + +//Added on 12-12-2005 + 'LBL_CONVERT_AS_FAQ_BUTTON_TITLE' => '转换为常见问答', + 'LBL_CONVERT_AS_FAQ_BUTTON_KEY' => 'C', + 'LBL_CONVERT_AS_FAQ_BUTTON_LABEL' => '转换为常见问答', + 'Attachment' => '附加档案', + 'LBL_COMMENT_INFORMATION' => '意见信息', + +//Added for existing picklist entries + +'Big Problem' => '大问题', + 'Small Problem' => '小问题', + 'Other Problem' => '其它问题', + +'Low' => '低', + 'Normal' => '一般', + 'High' => '高', + 'Urgent' => '紧急', + +'Minor' => '较小的', + 'Major' => '主要的', + 'Feature' => '功能', + 'Critical' => '重要', + + 'Open' => '开启', + 'In Progress' => '处理中', + 'Wait For Response' => '等待回应', + 'Closed' => '关闭', + +//added to support i18n in ticket mails +'Hi' => 'Hi', +'Dear'=> 'Dear', +'LBL_PORTAL_BODY_MAILINFO'=> '传票是', +'LBL_DETAIL' => '细节 :', +'LBL_REGARDS'=> '致意', +'LBL_TEAM'=> 'HelpDesk Team', +'LBL_TICKET_DETAILS' => '传票内容', +'LBL_SUBJECT' => '目标 : ', +'created' => '创建', +'replied' => '回复', +'reply'=>'有一个回复关于', +'customer_portal' => '客户门户.', +'link' => '您可以使用下面的链接来查看回复:', +'Thanks' => '谢谢', +'Support_team' => 'Vtiger支持团队', + +// Added/Updated for vtiger CRM 5.0.4 + +//this label for customerportal. +'LBL_STATUS_CLOSED' =>'关闭',//Do not convert this label. This is used to check the status. If the status 'Closed' is changed in vtigerCRM server side then you have to change in customerportal language file also. +'LBL_STATUS_UPDATE' => '事件状态被更新', +'LBL_COULDNOT_CLOSED' => '事件不能是', +'LBL_CUSTOMER_COMMENTS' => '顾客对您的回复提供了以下其它信息:', +'LBL_RESPOND'=> '很荣幸地说上述事件最早.', +'LBL_REGARDS' =>'祝福', +'LBL_SUPPORT_ADMIN' => '管理员支持', +'LBL_RESPONDTO_TICKETID' =>'响应传票ID', +'LBL_CUSTOMER_PORTAL' => '在客户门户中 - 快迅', +'LBL_LOGIN_DETAILS' => '以下是您的客户门户登录信息 :', +'LBL_MAIL_COULDNOT_SENT' =>'邮件发送失败', +'LBL_USERNAME' => '使用名称 :', +'LBL_PASSWORD' => '密码 :', +'LBL_SUBJECT_PORTAL_LOGIN_DETAILS' => '关于你的客户门户登录信息', +'LBL_GIVE_MAILID' => '请留下您的电子邮箱', +'LBL_CHECK_MAILID' => '请检查您的电子邮箱', +'LBL_LOGIN_REVOKED' => '登录被撤销。请与管理员联系。', +'LBL_MAIL_SENT' => '您的登录信息已发送到您的邮箱', +'LBL_ALTBODY' => '这是纯文本正文(非HTML电子邮件客户端)', + +// Added after 5.0.4 GA + +// Module Sequence Numbering +'Ticket No' => '传票号码', +// END +); + +?> diff --git a/oss/vtiger/trunk/modules/HelpDesk/updateRelations.php b/oss/vtiger/trunk/modules/HelpDesk/updateRelations.php new file mode 100644 index 00000000..85798501 --- /dev/null +++ b/oss/vtiger/trunk/modules/HelpDesk/updateRelations.php @@ -0,0 +1,48 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Home/HomeAjax.php b/oss/vtiger/trunk/modules/Home/HomeAjax.php new file mode 100644 index 00000000..27b1041d --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/HomeAjax.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Home/HomeBlock.php b/oss/vtiger/trunk/modules/Home/HomeBlock.php new file mode 100644 index 00000000..10d171a2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/HomeBlock.php @@ -0,0 +1,70 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); + +if(!empty($_REQUEST['homestuffid'])){ + $stuffid = $_REQUEST['homestuffid']; +} +if(!empty($_REQUEST['blockstufftype'])){ + $stufftype = $_REQUEST['blockstufftype']; +} + +if($stufftype=='Tag Cloud'){ + $freetag = new freetag(); + $smarty->assign("ALL_TAG",$freetag->get_tag_cloud_html("",$current_user->id)); + $smarty->display("Home/TagCloud.tpl"); +}elseif($stufftype == 'Notebook'){ + $contents = $homeObj->getNoteBookContents($stuffid); + $smarty->assign("NOTEBOOK_CONTENTS",$contents); + $smarty->assign("NOTEBOOKID", $stuffid); + $smarty->display("Home/notebook.tpl"); +}elseif($stufftype == 'URL'){ + $url = $homeObj->getWidgetURL($stuffid); + if(strpos($url, "://") === false){ + $url = "http://".trim($url); + } + $smarty->assign("URL",$url); + $smarty->assign("WIDGETID", $stuffid); + $smarty->display("Home/HomeWidgetURL.tpl"); +}else{ + $homestuff_values=$homeObj->getHomePageStuff($stuffid,$stufftype); + if($stufftype=="DashBoard"){ + $homeObj->getDashDetails($stuffid,'type'); + $dashdet=$homeObj->dashdetails; + } +} + +$smarty->assign("DASHDETAILS",$dashdet); +$smarty->assign("HOME_STUFFTYPE",$stufftype); +$smarty->assign("HOME_STUFFID",$stuffid); +$smarty->assign("HOME_STUFF",$homestuff_values); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +$smarty->display("Home/HomeBlock.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Home/HomeNews.php b/oss/vtiger/trunk/modules/Home/HomeNews.php new file mode 100644 index 00000000..7226aa2b --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/HomeNews.php @@ -0,0 +1,32 @@ +vt_dofetch('http://feeds.feedburner.com/hawebs/fbDz', $ftimeout); +$items = $fparser->get_items(); +$NEWSLIST = Array(); +foreach($items as $item) { + $NEWSLIST[] = $item; +} + +require_once('Smarty_setup.php'); +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", "themes/$theme/images/"); +$smarty->assign('NEWSLIST', $NEWSLIST); +$smarty->display("HomeNews.tpl"); +?> + diff --git a/oss/vtiger/trunk/modules/Home/HomeUtils.php b/oss/vtiger/trunk/modules/Home/HomeUtils.php new file mode 100644 index 00000000..16840cf3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/HomeUtils.php @@ -0,0 +1,200 @@ +id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + $today = date("Y-m-d", time()); + $upcoming_condition = " AND (date_start = '$today' OR vtiger_recurringevents.recurringdate = '$today')"; + + $list_query = " select vtiger_crmentity.crmid,vtiger_crmentity.smownerid,vtiger_crmentity.setype, vtiger_recurringevents.recurringdate, vtiger_activity.* from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid left outer join vtiger_recurringevents on vtiger_recurringevents.activityid=vtiger_activity.activityid WHERE vtiger_crmentity.deleted=0 and vtiger_activity.activitytype not in ('Emails') AND ( vtiger_activity.status is NULL OR vtiger_activity.status not in ('Completed','Deferred')) and ( vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus not in ('Held','Not Held') )".$upcoming_condition; + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3){ + $sec_parameter=getListViewSecurityParameter('Calendar'); + $list_query .= $sec_parameter; + } + + $list_query.= " GROUP BY vtiger_activity.activityid"; + $list_query.= " ORDER BY date_start,time_start ASC"; + $list_query.= " limit $maxval"; + + $res = $adb->query($list_query); + $noofrecords = $adb->num_rows($res); + if($calCnt == 'calculateCnt'){ + return $noofrecords; + } + + $open_activity_list = array(); + if ($noofrecords>0){ + for($i=0;$i<$noofrecords;$i++){ + $open_activity_list[] = array('name' => $adb->query_result($res,$i,'subject'), + 'id' => $adb->query_result($res,$i,'activityid'), + 'type' => $adb->query_result($res,$i,'activitytype'), + 'module' => $adb->query_result($res,$i,'setype'), + 'date_start' => getDisplayDate($adb->query_result($res,$i,'date_start')), + 'due_date' => getDisplayDate($adb->query_result($res,$i,'due_date')), + 'recurringdate' => getDisplayDate($adb->query_result($res,$i,'recurringdate')), + 'priority' => $adb->query_result($res,$i,'priority'), + ); + } + } + $values = getActivityEntries($open_activity_list); + $values['ModuleName'] = 'Calendar'; + $values['search_qry'] = "&action=ListView&from_homepage=upcoming_activities"; + + return $values; +} + +/** + * this function returns the activity entries in array format + * it takes in an array containing activity details as a parameter + * @param array $open_activity_list - the array containing activity details + * return array $values - activities record in array format + */ +function getActivityEntries($open_activity_list){ + global $current_language, $app_strings; + $current_module_strings = return_module_language($current_language, 'Calendar'); + if(!empty($open_activity_list)){ + $header=array(); + $header[] =$current_module_strings['LBL_LIST_SUBJECT']; + $header[] =$current_module_strings['Type']; + + $entries = array(); + foreach($open_activity_list as $event){ + $recur_date=ereg_replace('--','',$event['recurringdate']); + if($recur_date!=""){ + $event['date_start']=$event['recurringdate']; + } + $font_color_high = "color:#00DD00;"; + $font_color_medium = "color:#DD00DD;"; + + switch ($event['priority']){ + case 'High': + $font_color=$font_color_high; + break; + case 'Medium': + $font_color=$font_color_medium; + break; + default: + $font_color=''; + } + + if($event['type'] != 'Task' && $event['type'] != 'Emails' && $event['type'] != ''){ + $activity_type = 'Events'; + }else{ + $activity_type = 'Task'; + } + + $entries[$event['id']] = array( + '0' => ''.$event["name"].'', + '1' => $event["type"], + ); + } + $values = array('noofactivities'=>count($open_activity_list),'Header'=>$header,'Entries'=>$entries); + }else{ + $values = array('Entries'=>$app_strings['LBL_NO_DATA']); + } + return $values; +} + + +/** + * function to get pending activities for today + * @param integer $maxval - the maximum number of records to display + * @param integer $calCnt - returns the count query if this is set + * return array $values - activities record in array format + */ +function homepage_getPendingActivities($maxval,$calCnt){ + require_once("data/Tracker.php"); + require_once("include/utils/utils.php"); + require_once('include/utils/CommonUtils.php'); + + global $adb; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + + $today = date("Y-m-d", time()); + $pending_condition = " AND (due_date = '$today' OR vtiger_recurringevents.recurringdate = '$today')"; + + $list_query = "select vtiger_crmentity.crmid,vtiger_crmentity.smownerid,vtiger_crmentity.setype, vtiger_recurringevents.recurringdate, vtiger_activity.* from vtiger_activity inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid left outer join vtiger_recurringevents on vtiger_recurringevents.activityid=vtiger_activity.activityid WHERE vtiger_crmentity.deleted=0 and (vtiger_activity.activitytype not in ('Emails')) AND (vtiger_activity.status is NULL OR vtiger_activity.status not in ('Completed','Deferred')) and (vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus not in ('Held','Not Held')) ".$pending_condition; + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[16] == 3){ + $sec_parameter=getListViewSecurityParameter('Calendar'); + $list_query .= $sec_parameter; + } + + $list_query.= " GROUP BY vtiger_activity.activityid"; + $list_query.= " ORDER BY date_start,time_start ASC"; + $list_query.= " limit $maxval"; + + $res = $adb->query($list_query); + $noofrecords = $adb->num_rows($res); + if($calCnt == 'calculateCnt'){ + return $noofrecords; + } + + $open_activity_list = array(); + $noofrows = $adb->num_rows($res); + if (count($res)>0){ + for($i=0;$i<$noofrows;$i++){ + $open_activity_list[] = array('name' => $adb->query_result($res,$i,'subject'), + 'id' => $adb->query_result($res,$i,'activityid'), + 'type' => $adb->query_result($res,$i,'activitytype'), + 'module' => $adb->query_result($res,$i,'setype'), + 'date_start' => getDisplayDate($adb->query_result($res,$i,'date_start')), + 'due_date' => getDisplayDate($adb->query_result($res,$i,'due_date')), + 'recurringdate' => getDisplayDate($adb->query_result($res,$i,'recurringdate')), + 'priority' => $adb->query_result($res,$i,'priority'), + ); + } + } + + $values = getActivityEntries($open_activity_list); + $values['ModuleName'] = 'Calendar'; + $values['search_qry'] = "&action=ListView&from_homepage=pending_activities"; + + return $values; +} + + +/** + * this function returns the number of columns in the home page for the current user. + * if nothing is found in the database it returns 4 by default + * return integer $data - the number of columns + */ +function getNumberOfColumns(){ + global $current_user, $adb; + + $sql = "select * from vtiger_home_layout where userid=?"; + $result = $adb->pquery($sql, array($current_user->id)); + + if($adb->num_rows($result)>0){ + $data = $adb->query_result($result,0,"layout"); + }else{ + $data = 4; //default is 4 column layout for now + } + return $data; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Home/Homestuff.js b/oss/vtiger/trunk/modules/Home/Homestuff.js new file mode 100644 index 00000000..e80aaac9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/Homestuff.js @@ -0,0 +1,648 @@ +/*+******************************************************************************** + * 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. + * + *******************************************************************************/ + +/** + * this function is used to show hide the columns in the add widget div based on the option selected + * @param string typeName - the selected option + */ +function chooseType(typeName){ + $('vtbusy_info').style.display="inline"; + $('stufftype_id').value=typeName; + + var typeLabel = typeName; + if(alert_arr[typeName] != null && alert_arr[typeName] != "" && alert_arr[typeName] != 'undefined'){ + typeLabel = alert_arr[typeName]; + } + $('divHeader').innerHTML=""+alert_arr.LBL_ADD+typeLabel+""; + if(typeName=='Module'){ + $('moduleNameRow').style.display="block"; + $('moduleFilterRow').style.display="block"; + $('modulePrimeRow').style.display="block"; + $('showrow').style.display="block"; + $('rssRow').style.display="none"; + $('dashNameRow').style.display="none"; + $('dashTypeRow').style.display="none"; + $('StuffTitleId').style.display="block"; + //$('homeURLField').style.display = "none"; + }else if(typeName=='DashBoard'){ + $('moduleNameRow').style.display="none"; + $('moduleFilterRow').style.display="none"; + $('modulePrimeRow').style.display="none"; + $('rssRow').style.display="none"; + $('showrow').style.display="none"; + $('dashNameRow').style.display="block"; + $('dashTypeRow').style.display="block"; + $('StuffTitleId').style.display="block"; + //$('homeURLField').style.display = "none"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&dash=dashboard', + onComplete: function(response){ + var responseVal=response.responseText; + $('selDashName').innerHTML=response.responseText; + show('addWidgetsDiv'); + placeAtCenter($('addWidgetsDiv')); + $('vtbusy_info').style.display="none"; + } + } + ); + }else if(typeName=='RSS'){ + $('moduleNameRow').style.display="none"; + $('moduleFilterRow').style.display="none"; + $('modulePrimeRow').style.display="none"; + $('showrow').style.display="block"; + $('rssRow').style.display="block"; + $('dashNameRow').style.display="none"; + $('dashTypeRow').style.display="none"; + $('StuffTitleId').style.display="block"; + $('vtbusy_info').style.display="none"; + //$('homeURLField').style.display = "none"; + }else if(typeName=='Default'){ + $('moduleNameRow').style.display="none"; + $('moduleFilterRow').style.display="none"; + $('modulePrimeRow').style.display="none"; + $('showrow').style.display="none"; + $('rssRow').style.display="none"; + $('dashNameRow').style.display="none"; + $('dashTypeRow').style.display="none"; + $('StuffTitleId').style.display="none"; + $('url_id').style.display = "none"; + }else if(typeName == 'Notebook'){ + $('moduleNameRow').style.display="none"; + $('moduleFilterRow').style.display="none"; + $('modulePrimeRow').style.display="none"; + $('showrow').style.display="none"; + $('rssRow').style.display="none"; + $('dashNameRow').style.display="none"; + $('dashTypeRow').style.display="none"; + $('StuffTitleId').style.display="block"; + $('vtbusy_info').style.display="none"; + //$('homeURLField').style.display = "none"; + } + /*else if(typeName == 'URL'){ + $('moduleNameRow').style.display="none"; + $('moduleFilterRow').style.display="none"; + $('modulePrimeRow').style.display="none"; + $('showrow').style.display="none"; + $('rssRow').style.display="none"; + $('dashNameRow').style.display="none"; + $('dashTypeRow').style.display="none"; + $('StuffTitleId').style.display="block"; + $('vtbusy_info').style.display="none"; + //$('homeURLField').style.display = "block"; + }*/ +} + +/** + * this function is used to set the filter list when the module name is changed + * @param string modName - the modula name for which you want the filter list + */ +function setFilter(modName){ + var modval=modName.value; + document.getElementById('savebtn').disabled = true; + if(modval!=""){ + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&modname='+modval, + onComplete: function(response){ + var responseVal=response.responseText; + $('selModFilter_id').innerHTML=response.responseText; + setPrimaryFld(document.getElementById('selFilterid')); + show('addWidgetsDiv'); + placeAtCenter($('addWidgetsDiv')); + } + } + ); + } +} + +/** + * this function is used to set the field list when the module name is changed + * @param string modName - the modula name for which you want the field list + */ +function setPrimaryFld(Primeval){ + primecvid=Primeval.value; + var fldmodule = $('selmodule_id').options[$('selmodule_id').selectedIndex].value; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&primecvid='+primecvid+'&fieldmodname='+fldmodule, + onComplete: function(response){ + var responseVal=response.responseText; + $('selModPrime_id').innerHTML=response.responseText; + $('selPrimeFldid').selectedIndex = 0; + $('vtbusy_info').style.display="none"; + document.getElementById('savebtn').disabled = false; + } + } + ); +} + +/** + * this function displays the div for selecting the number of rows in a widget + * @param string sid - the id of the widget for which the div is being displayed + */ +function showEditrow(sid){ + $('editRowmodrss_'+sid).className="show_tab"; +} + +/** + * this function is used to hide the div for selecting the number of rows in a widget + * @param string editRow - the id of the div + */ +function cancelEntries(editRow){ + $(editRow).className="hide_tab"; +} + +/** + * this function is used to save the maximum entries that a widget can display + * @param string selMaxName - the widget name + */ +function saveEntries(selMaxName){ + sidarr=selMaxName.split("_"); + sid=sidarr[1]; + $('refresh_'+sid).innerHTML=$('vtbusy_homeinfo').innerHTML; + cancelEntries('editRowmodrss_'+sid) + showmax=$(selMaxName).value; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&showmaxval='+showmax+'&sid='+sid, + onComplete: function(response){ + var responseVal=response.responseText; + eval(response.responseText); + $('refresh_'+sid).innerHTML=''; + } + } + ); +} + +/** + * this function is used to save the dashboard values + */ +function saveEditDash(dashRowId){ + $('refresh_'+dashRowId).innerHTML=$('vtbusy_homeinfo').innerHTML; + cancelEntries('editRowmodrss_'+dashRowId); + var dashVal=''; + var iter=0; + for(iter=0;iter<3;iter++){ + if($('dashradio_'+[iter]).checked) + dashVal=$('dashradio_'+[iter]).value; + } + did=dashRowId; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&dashVal='+dashVal+'&did='+did, + onComplete: function(response){ + var responseVal=response.responseText; + eval(response.responseText); + $('refresh_'+did).innerHTML=''; + } + } + ); +} + +/** + * this function is used to delete widgets form the home page + * @param string sid - the stuffid of the widget + */ +function DelStuff(sid){ + if(confirm("Are you sure you want to delete?")){ + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&homestuffid='+sid, + onComplete: function(response){ + var responseVal=response.responseText; + if(response.responseText.indexOf('SUCCESS') > -1){ + var delchild = $('stuff_'+sid); + odeletedChild = $('MainMatrix').removeChild(delchild); + $('seqSettings').innerHTML= '
Widget deleted sucessfully.
'; + $('seqSettings').style.display = 'block'; + $('seqSettings').style.display = 'none'; + placeAtCenter($('seqSettings')); + Effect.Appear('seqSettings'); + setTimeout(hideSeqSettings,3000); + }else{ + alert("Error while deleting.Please try again.") + } + } + } + ); + } +} + +/** + * this function loads the newly added div to the home page + * @param string stuffid - the id of the newly created div + * @param string stufftype - the stuff type for the new div (for e.g. rss) + */ +function loadAddedDiv(stuffid,stufftype){ + gstuffId = stuffid; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=NewBlock&stuffid='+stuffid+'&stufftype='+stufftype, + onComplete: function(response){ + var responseVal=response.responseText; + $('MainMatrix').style.display= 'none'; + $('MainMatrix').innerHTML = response.responseText + $('MainMatrix').innerHTML; + positionDivInAccord('stuff_'+gstuffId,'',stufftype); + initHomePage(); + loadStuff(stuffid,stufftype); + $('MainMatrix').style.display='block'; + } + } + ); +} + +/** + * this function is used to reload a widgets' content based on its id and type + * @param string stuffid - the widget id + * @param string stufftype - the type of the widget + */ +function loadStuff(stuffid,stufftype){ + $('refresh_'+stuffid).innerHTML=$('vtbusy_homeinfo').innerHTML; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomeBlock&homestuffid='+stuffid+'&blockstufftype='+stufftype, + onComplete: function(response){ + var responseVal=response.responseText; + $('stuffcont_'+stuffid).innerHTML=response.responseText; + if(stufftype=="Module"){ + if($('more_'+stuffid).value != null && $('more_'+stuffid).value != '') + $('a_'+stuffid).href = "index.php?module="+$('more_'+stuffid).value+"&action=ListView&viewname="+$('cvid_'+stuffid).value; + } + if(stufftype=="Default" && typeof($('a_'+stuffid)) != 'undefined'){ + if($('more_'+stuffid).value != ''){ + $('a_'+stuffid).style.display = 'block'; + var url = "index.php?module="+$('more_'+stuffid).value+"&action=index"; + if($('search_qry_'+stuffid)!=''){ + url += $('search_qry_'+stuffid).value; + } + $('a_'+stuffid).href = url; + }else{ + $('a_'+stuffid).style.display = 'none'; + } + } + if(stufftype=="RSS"){ + $('a_'+stuffid).href = $('more_'+stuffid).value; + } + if(stufftype=="DashBoard"){ + $('a_'+stuffid).href = "index.php?module=Dashboard&action=index&type="+$('more_'+stuffid).value; + } + $('refresh_'+stuffid).innerHTML=''; + } + } + ); +} + +/** + * this function validates the form for creating a new widget + */ +function frmValidate(){ + if(trim($('stufftitle_id').value)==""){ + alert("Please enter Window Title"); + $('stufftitle_id').focus(); + return false; + } + if($('stufftype_id').value=="RSS"){ + if($('txtRss_id').value==""){ + alert("Please enter RSS URL"); + $('txtRss_id').focus(); + return false; + } + } + /*if($('stufftype_id').value=="URL"){ + if($('url_id').value==""){ + alert("Please enter URL"); + $('url_id').focus(); + return false; + } + }*/ + if($('stufftype_id').value=="Module"){ + var selLen; + var fieldval=new Array(); + var cnt=0; + selVal=document.Homestuff.PrimeFld; + for(k=0;k2){ + alert("Please select only two fields"); + selVal.focus(); + return false; + }else{ + document.Homestuff.fldname.value=fieldval; + } + } + var stufftype=$('stufftype_id').value; + var stufftitle=$('stufftitle_id').value; + $('stufftitle_id').value = ''; + var selFiltername=''; + var fldname=''; + var selmodule=''; + var maxentries=''; + var txtRss=''; + var seldashbd=''; + var seldashtype=''; + var seldeftype=''; + //var txtURL = ''; + + if(stufftype=="Module"){ + selFiltername =document.Homestuff.selFiltername[document.Homestuff.selFiltername.selectedIndex].value; + fldname = fieldval; + selmodule =$('selmodule_id').value; + maxentries =$('maxentryid').value; + }else if(stufftype=="RSS"){ + txtRss=$('txtRss_id').value; + maxentries =$('maxentryid').value; + }/*else if(stufftype=="URL"){ + txtURL=$('url_id').value; + }*/else if(stufftype=="DashBoard"){ + seldashbd=$('seldashbd_id').value; + seldashtype=$('seldashtype_id').value; + }else if(stufftype=="Default"){ + seldeftype=document.Homestuff.seldeftype[document.Homestuff.seldeftype.selectedIndex].value; + } + + var url="stufftype="+stufftype+"&stufftitle="+stufftitle+"&selmodule="+selmodule+"&maxentries="+maxentries+"&selFiltername="+selFiltername+"&fldname="+encodeURIComponent(fldname)+"&txtRss="+txtRss+"&seldashbd="+seldashbd+"&seldashtype="+seldashtype+"&seldeftype="+seldeftype;//+'&txtURL='+txtURL; + var stuffarr=new Array(); + $('vtbusy_info').style.display="inline"; + + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=Homestuff&'+url, + onComplete: function(response){ + var responseVal=response.responseText; + if(!response.responseText){ + alert("Unable to add homestuff! Please try again"); + $('vtbusy_info').style.display="none"; + $('stufftitle_id').value=''; + $('txtRss_id').value=''; + return false; + }else{ + hide('addWidgetsDiv'); + $('vtbusy_info').style.display="none"; + $('stufftitle_id').value=''; + $('txtRss_id').value=''; + eval(response.responseText); + } + } + } + ); +} + +/** + * this function is used to hide the default widgets + * @param string sid - the id of the widget + */ +function HideDefault(sid){ + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Home&action=HomeAjax&file=HomestuffAjax&stuffid='+sid+"&act=hide", + onComplete: function(response){ + var responseVal=response.responseText; + if(response.responseText.indexOf('SUCCESS') > -1){ + var delchild = $('stuff_'+sid); + odeletedChild = $('MainMatrix').removeChild(delchild); + $('seqSettings').innerHTML= '
'+alert_arr.LBL_WIDGET_HIDDEN+'.'+alert_arr.LBL_RESTORE_FROM_PREFERENCES+'.
'; + $('seqSettings').style.display = 'block'; + $('seqSettings').style.display = 'none'; + placeAtCenter($('seqSettings')); + Effect.Appear('seqSettings'); + setTimeout(hideSeqSettings,3000); + }else{ + alert(alert_arr.ERR_HIDING + '.'+ alert_arr.MSG_TRY_AGAIN + '.'); + } + } + } + ); +} + + +/** + * this function removes the widget dropdown window + */ +function fnRemoveWindow(){ + var tagName = document.getElementById('addWidgetDropDown').style.display= 'none'; +} + +/** + * this function displays the widget dropdown window + */ +function fnShowWindow(){ + var tagName = document.getElementById('addWidgetDropDown').style.display= 'block'; +} + +/** + * this function is used to postion the widgets on home on page resize + * @param string targetDiv - the id of the target widget + * @param string stufftitle - the title of the target widget + * @param string stufftype - the type of the target widget + */ +function positionDivInAccord(targetDiv,stufftitle,stufftype){ + var layout=$('homeLayout').value; + var widgetWidth; + var dashWidth; + + switch(layout){ + case '2': + widgetWidth = 49; + dashWidth = 98.6; + break; + case '3': + widgetWidth = 31; + dashWidth = 64; + break; + case '4': + widgetWidth = 24; + dashWidth = 48.6; + break; + default: + widgetWidth = 24; + dashWidth = 48.6; + break; + } + var mainX = parseInt(document.getElementById("MainMatrix").style.width); + if(stufftitle != vtdashboard_defaultDashbaordWidgetTitle && stufftype != "DashBoard"){ + var dx = mainX * widgetWidth/ 100; + }else{ + var dx = mainX * dashWidth / 100; + } + document.getElementById(targetDiv).style.width=dx + "%"; +} + +/** + * this function hides the seqSettings div + */ +function hideSeqSettings(){ + Effect.Fade('seqSettings'); +} + +/** + * this function fetches the homepage dashboard + * @param string stuffid - the id of the dashboard widget + */ +function fetch_homeDB(stuffid){ + $('refresh_'+stuffid).innerHTML=$('vtbusy_homeinfo').innerHTML; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'module=Dashboard&action=DashboardAjax&file=HomepageDB', + onComplete: function(response){ + $('stuffcont_'+stuffid).style.display = 'none'; + $('stuffcont_'+stuffid).innerHTML=response.responseText; + $('refresh_'+stuffid).innerHTML=''; + Effect.Appear('stuffcont_'+stuffid); + } + } + ); +} + +/** + * this function initializes the homepage + */ +initHomePage = function(){ + Sortable.create( + "MainMatrix", + { + constraint:false,tag:'div',overlap:'Horizontal',handle:'headerrow', + onUpdate:function(){ + matrixarr = Sortable.serialize('MainMatrix').split("&"); + matrixseqarr=new Array(); + seqarr=new Array(); + for(x=0;xstufftype=$_REQUEST['stufftype']; +} + +if(!empty($_REQUEST['stufftitle'])){ + if(strlen($_REQUEST['stufftitle'])>100){ + $temp_str = substr($_REQUEST['stufftitle'],0,97)."..."; + $oHomestuff->stufftitle= $temp_str; + }else{ + $oHomestuff->stufftitle=$_REQUEST['stufftitle']; + } + // Remove HTML/PHP tags from the input + if(isset($oHomestuff->stufftitle)) { + $oHomestuff->stufftitle = strip_tags($oHomestuff->stufftitle); + } +} + +if(!empty($_REQUEST['selmodule'])){ + $oHomestuff->selmodule=$_REQUEST['selmodule']; +} + +if(!empty($_REQUEST['maxentries'])){ + $oHomestuff->maxentries=$_REQUEST['maxentries']; +} + +if(!empty($_REQUEST['selFiltername'])){ + $oHomestuff->selFiltername=$_REQUEST['selFiltername']; +} + +if(!empty($_REQUEST['fldname'])){ + $oHomestuff->fieldvalue=$_REQUEST['fldname']; +} + +if(!empty($_REQUEST['txtRss'])){ + $ooRss=new vtigerRSS(); + if($ooRss->setRSSUrl($_REQUEST['txtRss'])){ + $oHomestuff->txtRss=$_REQUEST['txtRss']; + }else{ + return false; + } +} + +if(!empty($_REQUEST['txtURL'])){ + $oHomestuff->txtURL = $_REQUEST['txtURL']; +} +if(isset($_REQUEST['seldashbd']) && $_REQUEST['seldashbd']!=""){ + $oHomestuff->seldashbd=$_REQUEST['seldashbd']; +} + +if(isset($_REQUEST['seldashtype']) && $_REQUEST['seldashtype']!=""){ + $oHomestuff->seldashtype=$_REQUEST['seldashtype']; +} + +if(isset($_REQUEST['seldeftype']) && $_REQUEST['seldeftype']!=""){ + $seldeftype=$_REQUEST['seldeftype']; + $defarr=explode(",",$seldeftype); + $oHomestuff->defaultvalue=$defarr[0]; + $deftitlehash=$defarr[1]; + $oHomestuff->defaulttitle=str_replace("#"," ",$deftitlehash); +} + +$loaddetail=$oHomestuff->addStuff(); +echo $loaddetail; +?> diff --git a/oss/vtiger/trunk/modules/Home/HomestuffAjax.php b/oss/vtiger/trunk/modules/Home/HomestuffAjax.php new file mode 100644 index 00000000..7f207988 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/HomestuffAjax.php @@ -0,0 +1,192 @@ +id.'.php'); + +$modval=trim($_REQUEST['modname']); +$dash=trim($_REQUEST['dash']); +if(!empty($modval)){ + $tabid = getTabId($modval); + $ssql = "select vtiger_customview.*, vtiger_users.user_name from vtiger_customview inner join vtiger_tab on vtiger_tab.name = vtiger_customview.entitytype + left join vtiger_users on vtiger_customview.userid = vtiger_users.id "; + $ssql .= " where vtiger_tab.tabid=?"; + $sparams = array($tabid); + + if($is_admin == false){ + $ssql .= " and (vtiger_customview.status=0 or vtiger_customview.userid = ? or vtiger_customview.status = 3 or vtiger_customview.userid 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."::%'))"; + array_push($sparams, $current_user->id); + } + $result = $adb->pquery($ssql, $sparams); + + if($adb->num_rows($result)==0){ + echo $mod_strings['MSG_NO_FILTERS']; + die; + }else{ + $html = ''; + } + echo $html; +} + +if(!empty($dash)){ + global $current_language; + $dashbd_strings = return_module_language($current_language, "Dashboard"); + $graph_array = array("leadsource" => $dashbd_strings['leadsource'], + "leadstatus" => $dashbd_strings['leadstatus'], + "leadindustry" => $dashbd_strings['leadindustry'], + "salesbyleadsource" => $dashbd_strings['salesbyleadsource'], + "salesbyaccount" => $dashbd_strings['salesbyaccount'], + "salesbyuser" => $dashbd_strings['salesbyuser'], + "salesbyteam" => $dashbd_strings['salesbyteam'], + "accountindustry" => $dashbd_strings['accountindustry'], + "productcategory" => $dashbd_strings['productcategory'], + "productbyqtyinstock" => $dashbd_strings['productbyqtyinstock'], + "productbypo" => $dashbd_strings['productbypo'], + "productbyquotes" => $dashbd_strings['productbyquotes'], + "productbyinvoice" => $dashbd_strings['productbyinvoice'], + "sobyaccounts" => $dashbd_strings['sobyaccounts'], + "sobystatus" => $dashbd_strings['sobystatus'], + "pobystatus" => $dashbd_strings['pobystatus'], + "quotesbyaccounts" => $dashbd_strings['quotesbyaccounts'], + "quotesbystage" => $dashbd_strings['quotesbystage'], + "invoicebyacnts" => $dashbd_strings['invoicebyacnts'], + "invoicebystatus" => $dashbd_strings['invoicebystatus'], + "ticketsbystatus" => $dashbd_strings['ticketsbystatus'], + "ticketsbypriority" => $dashbd_strings['ticketsbypriority'], + "ticketsbycategory" => $dashbd_strings['ticketsbycategory'], + "ticketsbyuser" => $dashbd_strings['ticketsbyuser'], + "ticketsbyteam" => $dashbd_strings['ticketsbyteam'], + "ticketsbyproduct"=> $dashbd_strings['ticketsbyproduct'], + "contactbycampaign"=> $dashbd_strings['contactbycampaign'], + "ticketsbyaccount"=> $dashbd_strings['ticketsbyaccount'], + "ticketsbycontact"=> $dashbd_strings['ticketsbycontact'],); + + $html=''; + echo $html; +} + +if(!empty($_REQUEST['primecvid'])){ + $cvid=$_REQUEST['primecvid']; + $fieldmodule = vtlib_purify($_REQUEST['fieldmodname']); + $queryprime="select cvid,columnname from vtiger_cvcolumnlist where columnname not like '%::%' and cvid=?"; + $result=$adb->pquery($queryprime,array($cvid)); + global $current_language,$app_strings; + $fieldmod_strings = return_module_language($current_language, $fieldmodule); + if($adb->num_rows($result)==0){ + echo $mod_strings['MSG_NO_FIELDS']; + die; + }else{ + $html = ''; + } + echo $html; +} + +if(!empty($_REQUEST['showmaxval']) && !empty($_REQUEST['sid'])){ + $sid=$_REQUEST['sid']; + $maxval=$_REQUEST['showmaxval']; + global $adb; + $query="select stufftype from vtiger_homestuff where stuffid=?"; + $res=$adb->pquery($query, array($sid)); + $stufftypename=$adb->query_result($res,0,"stufftype"); + if($stufftypename=="Module"){ + $qry="update vtiger_homemodule set maxentries=? where stuffid=?"; + $result=$adb->pquery($qry, array($maxval, $sid)); + }else if($stufftypename=="RSS"){ + $qry="update vtiger_homerss set maxentries=? where stuffid=?"; + $result=$adb->pquery($qry, array($maxval, $sid)); + }else if($stufftypename=="Default"){ + $qry="update vtiger_homedefault set maxentries=? where stuffid=?"; + $result=$adb->pquery($qry, array($maxval, $sid)); + } + echo "loadStuff(".$sid.",'".$stufftypename."')"; +} + +if(!empty($_REQUEST['dashVal'])){ + $did=$_REQUEST['did']; + global $adb; + $qry="update vtiger_homedashbd set dashbdtype=? where stuffid=?"; + $res=$adb->pquery($qry, array($_REQUEST['dashVal'], $did)); + echo "loadStuff(".$did.",'DashBoard')"; +} + +if(!empty($_REQUEST['homestuffid'])){ + $sid=$_REQUEST['homestuffid']; + global $adb; + $query="delete from vtiger_homestuff where stuffid=?"; + $result=$adb->pquery($query, array($sid)); + echo "SUCCESS"; +} + +//Sequencing of blocks starts +if(!empty($_REQUEST['matrixsequence'])){ + global $adb; + $sequence = explode('_',$_REQUEST['matrixsequence']); + for($i=count($sequence)-1, $seq=0;$i>=0;$i--, $seq++){ + $query = 'update vtiger_homestuff set stuffsequence=? where stuffid=?'; + $result = $adb->pquery($query, array($seq, $sequence[$i])); + } + echo "
Layout Saved
"; +} +//Sequencing of blocks ends + +if(isset($_REQUEST['act']) && $_REQUEST['act'] =="hide"){ + $stuffid=$_REQUEST['stuffid']; + global $adb,$current_user; + $qry="update vtiger_homestuff set visible=1 where stuffid=?"; + $res=$adb->pquery($qry, array($stuffid)); + echo "SUCCESS"; +} + +//saving layout here +if(!empty($_REQUEST['layout'])){ + global $adb, $current_user; + + $sql = "delete from vtiger_home_layout where userid=?"; + $result = $adb->pquery($sql, array($current_user->id)); + + $sql = "insert into vtiger_home_layout values (?, ?)"; + $result = $adb->pquery($sql, array($current_user->id, $_REQUEST['layout'])); + if(!$result){ + echo "SUCCESS"; + } +} +//layout save ends here +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Home/LastViewed.php b/oss/vtiger/trunk/modules/Home/LastViewed.php new file mode 100644 index 00000000..cd2f9a0e --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/LastViewed.php @@ -0,0 +1,46 @@ + + + +get_recently_viewed($current_user->id); + +foreach($history as $row) +{ + echo <<< EOQ + + + + +EOQ; +} +?> +
{$row['module_name']}$row[item_summary]
diff --git a/oss/vtiger/trunk/modules/Home/MainHomeBlock.php b/oss/vtiger/trunk/modules/Home/MainHomeBlock.php new file mode 100644 index 00000000..6b541f22 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/MainHomeBlock.php @@ -0,0 +1,30 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); + +//$smarty->assign("HOME_STUFF",$homestuff_values); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->display("Home/MainHomeBlock.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Home/NewBlock.php b/oss/vtiger/trunk/modules/Home/NewBlock.php new file mode 100644 index 00000000..3d70d290 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/NewBlock.php @@ -0,0 +1,44 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$homeselectedframe = $homeObj->getSelectedStuff($stuffid,$stufftype); + +$smarty->assign("tablestuff",$homeselectedframe); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->display("Home/MainHomeBlock.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Home/SaveNotebookContents.php b/oss/vtiger/trunk/modules/Home/SaveNotebookContents.php new file mode 100644 index 00000000..bd53ec48 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/SaveNotebookContents.php @@ -0,0 +1,31 @@ +pquery($sql, array($contents, $current_user->id, $notebookid)); + return true; +} +?> diff --git a/oss/vtiger/trunk/modules/Home/UnifiedSearch.php b/oss/vtiger/trunk/modules/Home/UnifiedSearch.php new file mode 100644 index 00000000..30113183 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/UnifiedSearch.php @@ -0,0 +1,316 @@ + $object_name){ + if ($curModule == 'Home' || ($curModule == $module && !empty($_REQUEST['ajax']))) { + $focus = CRMEntity::getInstance($module); + if(isPermitted($module,"index") == "yes"){ + $smarty = new vtigerCRM_Smarty; + + require_once("modules/$module/language/".$current_language.".lang.php"); + global $mod_strings; + global $app_strings; + + $smarty->assign("MOD", $mod_strings); + $smarty->assign("APP", $app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE",$module); + $smarty->assign("SEARCH_MODULE",vtlib_purify($_REQUEST['search_module'])); + $smarty->assign("SINGLE_MOD",$module); + $smarty->assign("SEARCH_STRING",vtlib_purify($search_val)); + + $listquery = getListQuery($module); + $oCustomView = ''; + + $oCustomView = new CustomView($module); + //Instead of getting current customview id, use cvid of All so that all entities will be found + //$viewid = $oCustomView->getViewId($module); + $cv_res = $adb->pquery("select cvid from vtiger_customview where viewname='All' and entitytype=?", array($module)); + $viewid = $adb->query_result($cv_res,0,'cvid'); + $customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); + + $listquery = $oCustomView->getModifiedCvListQuery($viewid,$listquery,$module); + if ($module == "Calendar"){ + if (!isset($oCustomView->list_fields['Close'])){ + $oCustomView->list_fields['Close']=array ( 'activity' => 'status' ); + } + if (!isset($oCustomView->list_fields_name['Close'])){ + $oCustomView->list_fields_name['Close']='status'; + } + } + + if($search_module != ''){//This is for Tag search + $where = getTagWhere($search_val,$current_user->id); + $search_msg = $app_strings['LBL_TAG_SEARCH']; + $search_msg .= "".to_html($search_val).""; + }else{ //This is for Global search + $where = getUnifiedWhere($listquery,$module,$search_val); + $search_msg = $app_strings['LBL_SEARCH_RESULTS_FOR']; + $search_msg .= "".to_html($search_val).""; + } + + if($where != ''){ + $listquery .= ' and ('.$where.')'; + } + + if(!(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '')) { + $count_result = $adb->query($listquery); + $noofrows = $adb->num_rows($count_result); + } else { + $noofrows = vtlib_purify($_REQUEST['recordCount']); + } + $moduleRecordCount[$module]['count'] = $noofrows; + + global $list_max_entries_per_page; + if(!empty($_REQUEST['start'])){ + $start = $_REQUEST['start']; + if($start == 'last'){ + $count_result = $adb->query( mkCountQuery($listquery)); + $noofrows = $adb->query_result($count_result,0,"count"); + if($noofrows > 0){ + $start = ceil($noofrows/$list_max_entries_per_page); + } + } + if(!is_numeric($start)){ + $start = 1; + } elseif($start < 0){ + $start = 1; + } + $start = ceil($start); + }else{ + $start = 1; + } + + $navigation_array = VT_getSimpleNavigationValues($start, $list_max_entries_per_page, $noofrows); + $limitStartRecord = ($navigation_array['start'] - 1) * $list_max_entries_per_page; + + if( $adb->dbType == "pgsql"){ + $listquery = $listquery. " OFFSET $limitStartRecord LIMIT $list_max_entries_per_page"; + }else{ + $listquery = $listquery. " LIMIT $limitStartRecord, $list_max_entries_per_page"; + } + $list_result = $adb->query($listquery); + + $moduleRecordCount[$module]['recordListRangeMessage'] = getRecordRangeMessage($list_result, $limitStartRecord); + + $info_message='&recordcount='.$_REQUEST['recordcount'].'&noofrows='.$_REQUEST['noofrows'].'&message='.$_REQUEST['message'].'&skipped_record_count='.$_REQUEST['skipped_record_count']; + $url_string = '&modulename='.$_REQUEST['modulename'].'&nav_module='.$module_name.$info_message; + $viewid = ''; + + $navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,$module,"UnifiedSearch",$viewid); + $listview_header = getListViewHeader($focus,$module,"","","","global",$oCustomView); + $listview_entries = getListViewEntries($focus,$module,$list_result,$navigation_array,"","","","",$oCustomView); + + //Do not display the Header if there are no entires in listview_entries + if(count($listview_entries) > 0){ + $display_header = 1; + }else{ + $display_header = 0; + } + $smarty->assign("NAVIGATION", $navigationOutput); + $smarty->assign("LISTHEADER", $listview_header); + $smarty->assign("LISTENTITY", $listview_entries); + $smarty->assign("DISPLAYHEADER", $display_header); + $smarty->assign("HEADERCOUNT", count($listview_header)); + $smarty->assign("ModuleRecordCount", $moduleRecordCount); + + $total_record_count = $total_record_count + $noofrows; + + $smarty->assign("SEARCH_CRITERIA","( $noofrows )".$search_msg); + $smarty->assign("MODULES_LIST", $object_array); + $smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); + + if(($i != 0 && empty($_REQUEST['ajax'])) || !(empty($_REQUEST['ajax']))) + $smarty->display("UnifiedSearchAjax.tpl"); + else + $smarty->display('UnifiedSearchDisplay.tpl'); + unset($_SESSION['lvs'][$module]); + $i++; + } + } + } + //Added to display the Total record count + if(empty($_REQUEST['ajax'])) { +?> + +
        ".$mod_strings['ERR_ONE_CHAR'].""; +} + +/** + * Function to get the Tags where condition + * @param string $search_val -- entered search string value + * @param string $current_user_id -- current user id + * @return string $where -- where condition with the list of crmids, will like vtiger_crmentity.crmid in (1,3,4,etc.,) + */ +function getTagWhere($search_val,$current_user_id){ + require_once('include/freetag/freetag.class.php'); + + $freetag_obj = new freetag(); + $crmid_array = $freetag_obj->get_objects_with_tag_all($search_val,$current_user_id); + + $where = " vtiger_crmentity.crmid IN ("; + if(count($crmid_array) > 0){ + foreach($crmid_array as $index => $crmid){ + $where .= $crmid.','; + } + $where = trim($where,',').')'; + } + //If there are no records has the search tag we need to add the condition like crmid is none. If dont add condition at all search will return all the values. + // Fix for #5571 + else { + $where .= '0)'; + } + return $where; +} + + +/** + * Function to get the the List of Searchable Modules as a combo list which will be displayed in right corner under the Header + * @param string $search_module -- search module, this module result will be shown defaultly + */ +function getSearchModulesComboList($search_module){ + global $object_array; + global $app_strings; + global $mod_strings; + + ?> + + + + + + +
   + +
+ $object_name1,$module_name2=>$object_name2,$module_name3=>$object_name3,$module_name4=>$object_name4,-----); + */ +function getSearchModules($filter = array()){ + global $adb; + // vtlib customization: Ignore disabled modules. + //$sql = 'select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid=vtiger_field.tabid where vtiger_tab.tabid not in (16,29)'; + $sql = 'select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_tab.tabid=vtiger_field.tabid where vtiger_tab.tabid not in (16,29) and vtiger_tab.presence != 1 and vtiger_field.presence in (0,2)'; + // END + $result = $adb->pquery($sql, array()); + while($module_result = $adb->fetch_array($result)){ + $modulename = $module_result['name']; + // Do we need to filter the module selection? + if(!empty($filter) && is_array($filter) && !in_array($modulename, $filter)) { + continue; + } + // END + if($modulename != 'Calendar'){ + $return_arr[$modulename] = $modulename; + }else{ + $return_arr[$modulename] = 'Activity'; + } + } + return $return_arr; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Home/UnifiedSearchModules.php b/oss/vtiger/trunk/modules/Home/UnifiedSearchModules.php new file mode 100644 index 00000000..277ed321 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/UnifiedSearchModules.php @@ -0,0 +1,43 @@ +query($sql); +while($modulerow = $adb->fetch_array($moduleres)) { + if(is_admin($current_user) || isPermitted($modulerow['name'], 'DetailView')) { + $modulename = $modulerow['name']; + $allowed_modules[$modulename] = array( + 'label' => getTranslatedString($modulename, $modulename), + 'selected' => in_array($modulename, $selected_modules) + ); + } +} +ksort($allowed_modules); + +require_once('Smarty_setup.php'); + +$smarty = new vtigerCRM_Smarty(); +$smarty->assign('MOD', $mod_strings); +$smarty->assign('APP', $app_strings); +$smarty->assign('THEME', $theme); +$smarty->assign('IMAGE_PATH', "themes/$theme/images/"); +$smarty->assign('ALLOWED_MODULES', $allowed_modules); + +$smarty->display('UnifiedSearchModules.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Home/chat.css b/oss/vtiger/trunk/modules/Home/chat.css new file mode 100644 index 00000000..3c0017ca --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/chat.css @@ -0,0 +1,232 @@ +/* + Copyright 2005 Rolando Gonzalez (rolosworld@gmail.com) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + table.chat // don't set width or height + thead.chat + tfoot.chat + tbody.chat + tr.chathea + tr.chatfoot + tr.chatbody + td.chathead + td.chathead1 + td.chathead2 + td.chatfoot + td.chatfoot1 + td.chatfoot2 + td.chatbody + td.chatbody1 // don't set width or height + td.chatbody2 + + td.chatbox // don't set width or height or overflow + td.chaticon + td.chattopic + td.chathide + td.chatclose + + div.cumsg + div.csmsg + span.cunick +*/ +*{ + font-family: Verdana, Arial, Helvetica, sans-serif; + font-size: 8pt; +} + +table.chat,table.pchat{ + empty-cells:show; +} +table.chat{ + position:absolute; +} +thead.chat{ + cursor:move; +} +td.chathead,td.chathead2,td.pchathead,td.pchathead2{ + width:5px; + height:38px; + padding:0px 5px 0px 0px; +} +td.chathead1,td.pchathead1{ + background-image:url(imgs/box_T.gif); + width:100%; +} +td.chathead,td.pchathead{ + background-image:url(imgs/box_TL.gif); +} +td.chathead2,td.pchathead2{ + background-image:url(imgs/box_TR.gif); +} + +td.chaticon{ + background-image:url(imgs/2tbarPrivateChat.gif); +} +td.chattopic{ + background-image:url(imgs/2tbarPublicChat.gif); + background-repeat:no-repeat; + background-position:center left; + padding:0px 10px 0px 30px; + width:100%; +} + +td.chattopic1{ + padding:0px 10px 0px 5px; + width:100%; + text-align:left; +} +span.chatTopicNick{ font-weight:900; } +td.chathide,td.chatclose{ + cursor:pointer; +} +td.chathide{ + background-image:url(imgs/btn_hide.gif); +} +td.chatclose{ + background-image:url(imgs/btn_close.gif); +} +td.chaticon,td.chathide,td.chatclose{ + height:36px; + width:36px; + padding:31px 31px 5px 0px; + background-repeat:no-repeat; + background-position:center center; +} + +td.chatbody,td.chatbody2,td.pchatbody,td.pchatbody2{ + width:5px; + padding:0px 5px 0px 0px; +} +td.chatbody,td.pchatbody{ + background-image:url(imgs/box_ML.gif); +} +td.chatbody1,td.pchatbody1{ + background-image:url(imgs/box_M.gif); + padding:5px 5px 5px 5px; + vertical-align:top; +} +td.chatbody2,td.pchatbody2{ + background-image:url(imgs/box_MR.gif); +} + +td.chatfoot,td.chatfoot2,td.pchatfoot,td.pchatfoot2{ + width:5px; + height:60px; + padding:60px 5px 0px 0px; +} +td.chatfoot1,td.pchatfoot1{ + background-image:url(imgs/bx_B.gif); +} +td.chatfoot,td.pchatfoot{ + background-image:url(imgs/box_BL.gif); +} +td.chatfoot2,td.pchatfoot2{ + background-image:url(imgs/box_BR.gif); +} + + + +div.chatbox{ + background-color: #FFFFFF; + border: 1px solid #938F86; + color:#000000; + vertical-align:top; +} + +/* UList */ +span.cunick{ + color:green; +} +div.cumsg,div.csmsg{ + color:#0000ff; + margin:2px 2px 4px 2px; +} +div.csmsg{ + color:#FF0000; +} + +a.chat{ + background-image:url(themes/images/user_icon.gif); + background-position:center left; + background-repeat:no-repeat; + color:#000000; + text-decoration:none; + display:block; + width:100px; + height:20px; + background-color:#FFFFFF; + padding:10px 5px 5px 30px; + vertical-align:middle; +} +a.chat:hover{ + background-color:#DFD9CD; +} + +span{ + padding:0px; + margin:0px; +} + +/* input */ +form.cinput{ + display:inline; +} +input.cinput{ + background-color: #FFFFFF; + border: 1px solid #938F86; + width: 100%; + height:20px; + font-size:12px; + padding:2px 2px 2px 2px; + font-weight:bold; + color:#333333; +} +table.cinput{ + width:100%; +} +tr.cinput{ + +} +td.cinput{ + width:100%; +} +td.ckeyb{ + width:32px; + height:29px; + padding:29px 32px 5px 5px; + background-repeat:no-repeat; + background-position:center center; +} +td.csubmit{ + cursor:pointer; + background-image:url(imgs/btn_send.gif); + width:63px; + height:32px; + padding:32px 63px 5px 5px; + background-repeat:no-repeat; + background-position:center center; +} + + +span.sysb{font-weight:900;} +.chatuserlist{ + font-size:14px; + text-align:left; + color:white; + background-color:#898475; +} diff --git a/oss/vtiger/trunk/modules/Home/chat.php b/oss/vtiger/trunk/modules/Home/chat.php new file mode 100644 index 00000000..45331220 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/chat.php @@ -0,0 +1,382 @@ +\n".mysql_error()."
\n".$query); + } + return $result; +} + +/**** handler *****/ +/** + * Chat object + */ +class Chat +{ + // stores the string to be returned + var $json; + + function Chat() + { + global $adb; + $this->json = ''; + + // las message id received by user + if(!isset($_SESSION["mlid"])) + { + $res = $adb->pquery("show table status like 'vtiger_chat_msg'", array()); + $line = $adb->fetch_array($res); + if(intval($line['Auto_increment']) == 0) + $_SESSION["mlid"] = 0; + else + $_SESSION["mlid"] = intval($line['Auto_increment']) - 1; + } + + // when the las user list was sended. + if(!isset($_SESSION["lul"])) + { + $_SESSION["lul"] = 0; + } + + // check if user is active. + if(!isset($_SESSION['chat_user'])) + { + $this->setUserNick(); + } + else + { + $res = $adb->pquery("update vtiger_chat_users set ping=now() where session=?", array(session_id())); + if($adb->getAffectedRowCount($res) == 0) + { + $this->setUserNick(); + } + } + + switch($_POST['submode']) + { + // request all the json data at once. + case 'get_all': + global $chat_conf; + $this->lastMsgId(); + + $this->json = '[%s]'; + $this->getAllPVChat(); + $pvchat = $this->json; + + $this->json = '[%s]'; + $this->getPubChat(); + $pchat = $this->json; + + $this->json = ''; + if(time() - $_SESSION["lul"] > $chat_conf['alive_time']) + { + $_SESSION["lul"] = time(); + $this->json = '[%s]'; + $this->getUserList(); + } + $ulist = $this->json; + + $tmp = array(); + $this->json = '{%s}'; + if(strlen($ulist) > 0) + $tmp[] = '"ulist":'.$ulist; + + if(strlen($pvchat) > 0) + $tmp[] = '"pvchat":'.$pvchat; + + if(strlen($pchat) > 0) + $tmp[] = '"pchat":'.$pchat; + + $this->json = sprintf($this->json, implode(',',$tmp)); + break; + + // user is submiting a msg + case 'submit': + $this->submit($_POST['msg'],intval($_POST['to'])); + break; + + // user closed a private chat + case 'pvclose': + $this->pvClose(intval($_POST['to'])); + break; + + default: + break; + } + } + + /** + * returns the JSON created + */ + function getAJAX() + { + return $this->json; + } + + /** + * Sets the user initial nickname. + */ + function setUserNick() + { + global $current_user, $adb; + $res = $adb->pquery("select id from vtiger_chat_users where session=?", array(session_id())); + if($adb->num_rows($res) > 0) + { + $line = $adb->fetch_array($res); + $_SESSION['chat_user'] = $line['id']; + return; + } + + $res = $adb->pquery("show table status like 'vtiger_chat_users'", array()); + $line = $adb->fetch_array($res); + if(intval($line['Auto_increment']) == 0) + $line['Auto_increment'] = 1; + + $_SESSION['chat_user'] = $line['Auto_increment']; + + + $sql = "insert into vtiger_chat_users(nick,session,ping,ip) values (?,?, now(), ?)"; + $params = array($current_user->user_name, session_id(), $_SERVER['REMOTE_ADDR']); + $res = $adb->pquery($sql, $params); + } + + /** + * generate the available users list + */ + function getUserList() + { + global $chat_conf, $adb; + $tmp = ''; + $sql = "delete from vtiger_chat_users where ((unix_timestamp(now())-unix_timestamp(ping))>?)"; + $params = array($chat_conf['alive_time']); + $res = $adb->pquery($sql, $params); + + $res = $adb->pquery("select id,nick from vtiger_chat_users", array()); + if($adb->num_rows($res)==0) + { + $this->json = ''; + return; + } + + while($line = $adb->fetch_array($res)) + { + if($line['id'] != $_SESSION['chat_user']) + $tmp .= '{"uid":'.$line['id'].',"nick":"'.$line['nick'].'"},'; + } + $tmp = trim($tmp,','); + $this->json = sprintf($this->json,$tmp); + } + + /** + * Sets user last post received. + */ + function lastMsgId() + { + if(isset($_POST['mlid']) && intval($_POST['mlid']) > $_SESSION["mlid"]) + $_SESSION["mlid"] = intval($_POST['mlid']); + } + + /** + * generates the private chat data + */ + function getAllPVChat() + { + global $chat_conf, $adb; + $format = '{"mlid":%s,"chat":%s,"from":"%s","msg":"%s"},'; + $sql ="select ms.id mid,ms.chat_from mfrom,ms.chat_to mto,pv.id id,us.nick `chat_from`,ms.msg msg from vtiger_chat_users us,vtiger_chat_pvchat pv,vtiger_chat_msg ms where pv.msg=ms.id and us.id=ms.chat_from and ms.id>? and ((ms.chat_from=? and ms.chat_to>0) or (ms.chat_to=? and ms.chat_from>0)) order by ms.born limit 0, " . $chat_conf['msg_limit']; + $params = array($_SESSION['mlid'], $_SESSION['chat_user'], $_SESSION['chat_user']); + $res = $adb->pquery($sql, $params); + + if($adb->num_rows($res)==0) + { + $this->json = ''; + return; + } + + $tmp = ''; + while($line = $adb->fetch_array($res)) + { + if($line['mfrom'] == $_SESSION['chat_user']) + $cid = $line['mto']; + else + $cid = $line['mfrom']; + + $tmp .= sprintf($format,$line['mid'],$cid,$line['chat_from'],addslashes($line['msg'])); + } + $tmp = trim($tmp,','); + $this->json = sprintf($this->json,$tmp); + } + + + /** + * generates the public chat data + * NOTE: this is alpha + */ + function getPubChat() + { + global $chat_conf, $adb; + $format = '{"mlid":%s,"from":"%s","msg":"%s"},'; + $sql = "select ms.id mid,ms.chat_from mfrom,ms.chat_to mto,p.id id,us.nick `chat_from`,ms.msg msg from vtiger_chat_users us,vtiger_chat_pchat p,vtiger_chat_msg ms where p.msg=ms.id and us.id=ms.chat_from and ms.id>? and ms.chat_to=0 order by ms.born limit 0," . $chat_conf['msg_limit']; + $params = array($_SESSION['mlid']); + $res = $adb->pquery($sql, $params); + + if($adb->num_rows($res)==0) + { + $this->json = ''; + return; + } + + $tmp = ''; + while($line = $adb->fetch_array($res)) + { + $tmp .= sprintf($format,$line['mid'],$line['chat_from'],addslashes($line['msg'])); + } + $tmp = trim($tmp,','); + $this->json = sprintf($this->json,$tmp); + } + + /** + * Check for special commands on message. + */ + function msgParse($msg) + { + global $adb; + if(strlen($msg) == 0) return ''; + $msg = stripslashes($msg); + + + if($msg[0] == '\\') + { + $today_date = getdate(); + + $words = explode(" ",$msg); + switch($words[0]) + { + case '\nick': + if(isset($words[1]) && strlen($words[1]) > 3) + { + $res = $adb->pquery("select nick from vtiger_chat_users where id=?", array($_SESSION['chat_user'])); + $line = $adb->fetch_array($res); + $res = $adb->pquery("update vtiger_chat_users set nick=? where id=?", array($words[1], $_SESSION['chat_user'])); + $msg = '\sys '.$line['nick'].' changed nick to '.$words[1].''; + } + break; + + case '\help': + $msg = '\sys
\\\\nick "nickname" - change nick
\\\\date - date
\\\\time - time
\\\\month - month
\\\\day - weekday'; + break; + case '\date': + $msg = '\sys Today is '.date('d-m-Y').''; + break; + case '\time': + $msg = '\sys The Current time is '.$today_date["hours"].':'.$today_date["minutes"].':'.$today_date["hours"].''; break; + case '\month': + $msg = '\sys '.$today_date["month"].''; + break; + case '\day': + $msg = '\sys '.$today_date["weekday"].''; + break; + default: + + $msg = '\sys Bad command: '.$words[0]; + break; + } + } + return $msg; + } + + /** + * process a submited msg + */ + function submit($msg, $to=0) + { + global $adb; + //UTF-8 support added - ding + $msg = utf8RawUrlDecode($msg); + $msg = $this->msgParse($msg); +// $msg = htmlentities($msg); + $msg = htmlentities($msg,ENT_QUOTES, 'UTF-8'); + if(strlen($msg) == 0) return; + + //$sql = "insert into vtiger_chat_msg set chat_from=?, chat_to=?, born=now(), msg=?"; + $sql = "insert into vtiger_chat_msg(chat_from, chat_to, born, msg) values (?,?, now(), ?)"; + $params = array($_SESSION['chat_user'], $to, $msg); + $res = $adb->pquery($sql, $params); + + $chat = "p"; + if($to != 0) + $chat .= "v"; + + $res = $adb->pquery("insert into vtiger_chat_".$chat."chat set msg=LAST_INSERT_ID()", array()); + } + + /** + * removes the private conversation msg's because someone closed it + */ + function pvClose($to) + { + global $adb; + $sql = "delete from vtiger_chat_msg where (`chat_from`=? and `chat_to`=?) or (`chat_from`=? and `chat_to`=?)"; + $params = array($to, $_SESSION['chat_user'], $_SESSION['chat_user'], $to); + $res = $adb->pquery($sql, $params); + } +} + +/**** caller ****/ +$chat = new Chat(); +echo $chat->getAJAX(); +?> diff --git a/oss/vtiger/trunk/modules/Home/home_rss.php b/oss/vtiger/trunk/modules/Home/home_rss.php new file mode 100644 index 00000000..9690e16d --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/home_rss.php @@ -0,0 +1,128 @@ +\n"); +echo (" \n"); +echo (" \n"); +echo (" vtigerCRM Tickets\n"); +echo (" ".$site_URL."/index.php?module=Home&action=home_rss\n"); +echo (" test\n"); +echo (" \n"); +echo (" ".$current_user->user_name."\n"); +echo (" " . gmdate('D, d M Y H:i:s', time()) . " GMT\n"); +echo (" vtigerCRM\n"); + +//retrieving notifications****************************** +//<<<<<<<<<<<<<<<< start of owner notify>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> +$query = "select vtiger_crmentity.setype,vtiger_crmentity.crmid,vtiger_crmentity.smcreatorid,vtiger_crmentity.modifiedtime from vtiger_crmentity inner join vtiger_ownernotify on vtiger_crmentity.crmid=vtiger_ownernotify.crmid"; + +$result = $adb->pquery($query, array()); +for($i=0;$i<$adb->num_rows($result);$i++){ + $mod_notify[$i] = $adb->fetch_array($result); + if($mod_notify[$i]['setype']=='Accounts'){ + $tempquery='select vtiger_accountname from vtiger_account where vtiger_accountid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $account_name=$adb->fetch_array($tempresult); + $notify_values[$i]=$account_name['accountname']; + }else if($mod_notify[$i]['setype']=='Potentials'){ + $tempquery='select vtiger_potentialname from vtiger_potential where vtiger_potentialid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $potential_name=$adb->fetch_array($tempresult); + $notify_values[$i]=$potential_name['potentialname']; + }else if($mod_notify[$i]['setype']=='Contacts'){ + $tempquery='select lastname from vtiger_contactdetails where contactid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $contact_name=$adb->fetch_array($tempresult); + $notify_values[$i]=$contact_name['lastname']; + }else if($mod_notify[$i]['setype']=='Leads'){ + $tempquery='select lastname from vtiger_leaddetails where leadid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $lead_name=$adb->fetch_array($tempresult); + $notify_values[$i]=$lead_name['lastname']; + }else if($mod_notify[$i]['setype']=='SalesOrder'){ + $tempquery='select subject from vtiger_salesorder where vtiger_salesorderid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $sales_subject=$adb->fetch_array($tempresult); + $notify_values[$i]=$sales_subject['subject']; + }else if($mod_notify[$i]['setype']=='Orders'){ + $tempquery='select subject from vtiger_purchaseorder where vtiger_purchaseorderid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $purchase_subject=$adb->fetch_array($tempresult); + $notify_values[$i]=$purchase_subject['subject']; + }else if($mod_notify[$i]['setype']=='Products'){ + $tempquery='select productname from vtiger_products where productid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $product_name=$adb->fetch_array($tempresult); + $notify_values[$i]=$product_name['productname']; + }else if($mod_notify[$i]['setype']=='Emails'){ + $tempquery='select subject from vtiger_activity where vtiger_activityid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $email_subject=$adb->fetch_array($tempresult); + $notify_values[$i]=$email_subject['subject']; + }else if($mod_notify[$i]['setype']=='HelpDesk'){ + $tempquery='select title from vtiger_troubletickets where ticketid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $HelpDesk_title=$adb->fetch_array($tempresult); + $notify_values[$i]=$HelpDesk_title['title']; + }else if($mod_notify[$i]['setype']=='Calendar'){ + $tempquery='select subject from vtiger_activity where vtiger_activityid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $Activity_subject=$adb->fetch_array($tempresult); + $notify_values[$i]=$Activity_subject['subject']; + }else if($mod_notify[$i]['setype']=='Quotes'){ + $tempquery='select subject from vtiger_quotes where quoteid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $quote_subject=$adb->fetch_array($tempresult); + $notify_values[$i]=$quote_subject['subject']; + }else if($mod_notify[$i]['setype']=='Invoice'){ + $tempquery='select subject from vtiger_invoice where vtiger_invoiceid=?'; + $tempresult=$adb->pquery($tempquery, array($mod_notify[$i]['crmid'])); + $invoice_subject=$adb->fetch_array($tempresult); + $notify_values[$i]=$invoice_subject['subject']; + } + //<<<<<<<<<<<<<<<< end of owner notify>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + + + // Variable reassignment and reformatting for author + $author_id = $db->query_result($result,$i,'smcreatorid'); + $entry_author = getUserName($author_id); + $entry_author = htmlspecialchars ($entry_author); + + $entry_link = $site_URL."/index.php?modules=".$mod_notify[$i]['setype']."&action=DetailView&record=".$mod_notify[$i]['crmid']; + $entry_link = htmlspecialchars($entry_link); + $entry_time = $db->query_result($result,$i,'modifiedtime'); + + echo (" \n"); + echo (" ".$mod_notify[$i]['setype']."\n"); + echo (" ".$entry_link."\n"); + echo (" ".$notify_values[$i]."\n"); + echo (" ".$entry_author."\n"); + echo (" ".$entry_time."\n"); + echo (" \n"); +} +echo (" \n"); +echo (" \n"); +?> diff --git a/oss/vtiger/trunk/modules/Home/index.php b/oss/vtiger/trunk/modules/Home/index.php new file mode 100644 index 00000000..89e747bc --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/index.php @@ -0,0 +1,104 @@ + 29 and tabid <> 16 and tabid <>10) order by name"; + +// Performance Optimization: Re-written to ignore extension and inactive modules +$modulenamearr = Array(); +foreach($tabrows as $resultrow) { + if($resultrow['isentitytype'] != '0') { + // Eliminate: Events, Emails + if($resultrow['tabid'] == '16' || $resultrow['tabid'] == '10') { + continue; + } + $modName=$resultrow['name']; + if(isPermitted($modName,'DetailView') == 'yes' && vtlib_isModuleActive($modName)){ + $modulenamearr[$modName]=array($resultrow['tabid'],$modName); + } + } +} +ksort($modulenamearr); // We avoided ORDER BY in Query (vtlib_prefetchModuleActiveInfo)! +// END + + +//Security Check done for RSS and Dashboards +$allow_rss='no'; +$allow_dashbd='no'; +if(isPermitted('Rss','DetailView') == 'yes' && vtlib_isModuleActive('Rss')){ + $allow_rss='yes'; +} +if(isPermitted('Dashboard','DetailView') == 'yes' && vtlib_isModuleActive('Dashboard')){ + $allow_dashbd='yes'; +} + +$homedetails = $homeObj->getHomePageFrame(); +$maxdiv = sizeof($homedetails)-1; +$user_name = $current_user->column_fields['user_name']; +$buttoncheck['Calendar'] = isPermitted('Calendar','index'); +$freetag = new freetag(); +$numberofcols = getNumberOfColumns(); + +$smarty->assign("CHECK",$buttoncheck); +if(vtlib_isModuleActive('Calendar')){ + $smarty->assign("CALENDAR_ACTIVE","yes"); +} +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",'Home'); +$smarty->assign("CATEGORY",getParenttab('Home')); +$smarty->assign("CURRENTUSER",$user_name); +$smarty->assign("ALL_TAG",$freetag->get_tag_cloud_html("",$current_user->id)); +$smarty->assign("MAXLEN",$maxdiv); +$smarty->assign("ALLOW_RSS",$allow_rss); +$smarty->assign("ALLOW_DASH",$allow_dashbd); +$smarty->assign("HOMEFRAME",$homedetails); +$smarty->assign("MODULE_NAME",$modulenamearr); +$smarty->assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("LAYOUT", $numberofcols); + +$smarty->display("Home/Homestuff.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Home/js/ajax.js b/oss/vtiger/trunk/modules/Home/js/ajax.js new file mode 100644 index 00000000..10e2220c --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/js/ajax.js @@ -0,0 +1,104 @@ +/* + Copyright 2005 Rolando Gonzalez (rolosworld@gmail.com) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +function debug(dib,msg) +{ + if(document.getElementById(dib)) + document.getElementById(dib).innerHTML = msg; + else + alert(msg); +}; + + +function getRequester() +{ + try + { + if(window.XMLHttpRequest) + { + return new XMLHttpRequest(); + } + else if(window.ActiveXObject) + { + return new ActiveXObject("Microsoft.XMLHTTP"); + } + } + catch (e) + { + alert("You need a browser which supports an XMLHttpRequest Object.\nMozilla build 0.9.5 has this Object and IE5 and above."); + } +}; + +/* +onreadystatechange Event handler for an event that fires at every state change +readyState Object status integer: +0 = uninitialized +1 = loading +2 = loaded +3 = interactive +4 = complete +responseText String version of data returned from server process +responseXML DOM-compatible document object of data returned from server process +status Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK" +statusText String message accompanying the status code +*/ +function Ajax(cb) +{ + var me = this; + this.requester = getRequester(); + + if(cb) + this.callback = cb; + else + this.callback = function(req) + { + return eval(req.responseText); + }; + + this.requester.onreadystatechange = function(){ + switch(me.requester.readyState) + { + case 1: + case 2: + case 3: + break; + case 4: + var response = me.callback(me.requester); + break; + default: + alert("Error"); + break; + } + }; + + this.state = function() + { + return me.requester.readyState; + }; + + this.process = function(url, parameters){ + + me.requester.open("POST", url, true); + me.requester.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); + me.requester.setRequestHeader("Content-length", parameters.length); + //me.requester.setRequestHeader("Connection", "close"); + debug("debug",parameters); + me.requester.send(parameters); + + }; +}; diff --git a/oss/vtiger/trunk/modules/Home/js/chat.js b/oss/vtiger/trunk/modules/Home/js/chat.js new file mode 100644 index 00000000..ffa5bb66 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/js/chat.js @@ -0,0 +1,477 @@ +/* + Copyright 2005 Rolando Gonzalez (rolosworld@gmail.com) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +var chats = new Array(); // private chats opened +var users = new Array(); // users list +var chat_data = null; +var mlid = 0; //msg last id +var DEBUG = false; +var PRIVATES = true; +var PUBLIC = true; + +function getNick(uid) +{ + for(var i in users) + { + if(users[i].uid == uid) + return users[i].nick; + } + return null; +}; + +function resetChatsZ() +{ + for(var i = 0; i < chats.length; i++) + if(chats[i]) + chats[i].win.table.style.zIndex = chats[i].win.z; +}; + +function debug(dib,msg) +{ + if(!DEBUG) return; + if(document.getElementById(dib)) + document.getElementById(dib).innerHTML = msg; + else + alert(msg); +}; + +// initialize chat connection. +function Chat(conf) +{ + var me = this; + this.pcid = conf["pchatid"]?conf["pchatid"]:null; + this.dt = conf["dt"]?conf["dt"]:1000; + this.ulid = conf["ulid"]?conf["ulid"]:null; + this.w = conf["width"]?conf["width"]:"400px"; + this.h = conf["height"]?conf["height"]:"300px"; + this.ulist = null; + + if(this.pcid) + { + chats[0] = new PubChat(this.dt,this.w,this.h); + document.getElementById(this.pcid).appendChild(chats[0].get()); + } + + // evaluate the returned json + this.callback = function(response) + { + me.ajax = null; + try{ + me.doRefresh(decodeURI(response.responseText)); + + }catch(e){ + debug("debug","Chat Error: "+response.responseText); + clearInterval(me.interv); + debug("debug",e.toString()); + debug("debug",e.filename+":"+e.lineNumber); + return; + } + me.ajax = new Ajax(me.callback); + debug("debug",decodeURI(response.responseText)); + window.status=Date(); + }; + + this.doRefresh = function(response) + { + if(!me.ulist) + me.ulist = new UList(me.dt,me.ulid,me.w,me.h); + chat_data = eval("("+response+")"); + me.ulist.refresh(); + me.refreshChats(); + }; + + this.ajax = new Ajax(me.callback); + + // start the ajax request for the chat data + this.refresh = function() + { + if(me.ajax.state() == 0) + me.ajax.process("index.php?mode=chat&module=Home&action=chat","submode=get_all&mlid="+mlid); + }; + this.interv = setInterval(me.refresh,me.dt); + + this.refreshChats = function() + { + if(chat_data.pvchat) + { + cnum = 0; + for(var i in chat_data.pvchat) + { + cnum = chat_data.pvchat[i].chat; + if(!chats[cnum]) + chats[cnum] = new PrivChat(me.dt,cnum,me.w,me.h); + + if(mlid < chat_data.pvchat[i].mlid) + mlid = chat_data.pvchat[i].mlid; + + if(chat_data.pvchat[i].msg.substr(0,5) == "\\sys ") + { + chats[cnum].appendSysMsg(chat_data.pvchat[i].msg.substr(5)); + } + else + chats[cnum].appendMsg(chat_data.pvchat[i].from,chat_data.pvchat[i].msg); + } + chat_data.pvchat = null; + } + + if(PUBLIC && chat_data.pchat) + { + for(var i in chat_data.pchat) + { + if(mlid < chat_data.pchat[i].mlid) + mlid = chat_data.pchat[i].mlid; + + if(!chats[0]) + continue; + + if(chat_data.pchat[i].msg.substr(0,5) == "\\sys ") + { + chats[0].appendSysMsg(chat_data.pchat[i].msg.substr(5)); + } + else + chats[0].appendMsg(chat_data.pchat[i].from,chat_data.pchat[i].msg); + } + chat_data.pchat = null; + } + }; +}; + +// User list handler +function UList(dt,ulid,w,h) +{ + var me = this; + this.w = w; + this.h = h; + this.dt = dt; // delta time to sleep the requests. + this.ulid = ulid; // user list ul tag id. + this.interv = null; + + // updates the users list on the html + this.refreshList = function() + { + if(!document.getElementById(me.ulid)) + { + clearInterval(me.interv); + return; + } + + while(document.getElementById(me.ulid).firstChild) + document.getElementById(me.ulid).removeChild(document.getElementById(me.ulid).firstChild); + + if(users) + { + var li; + var a; + var user; + for(var i in users) + { + user = users[i]; + li = document.createElement("span"); + a = document.createElement("a"); + a.appendChild(document.createTextNode(user.nick)); + a.setAttribute("href","#"); + a.className = "chat"; + if(PRIVATES) + a.onclick = me.newPriv(me.dt,user.uid); + + li.appendChild(a); + document.getElementById(me.ulid).appendChild(li); + } + //var date = new Date(); + //window.status=date.toString(); + } + }; + + // higher order stuff + this.newPriv = function(dt,uid) + { + return function() + { + if(!chats[uid]) + { + resetChatsZ(); + chats[uid] = new PrivChat(dt,uid,me.w,me.h); + } + return false; + }; + }; + + // check if theres a new user list + this.refresh = function() + { + //users = null; + if(chat_data.ulist) + { + users = chat_data.ulist; + me.refreshList(); + } + chat_data.ulist = null; + }; +}; + +////////////////////////////////////////////////////////// +// Input handler +function chatInput(to) +{ + var me = this; + this.to = to?to:null; + this.input = document.createElement("input"); + this.input.className = "cinput"; + this.input.setAttribute("type","text"); + this.input.setAttribute("name","input"); + + var table = document.createElement("table"); + //table.border = "1"; + var tbody = table.appendChild(document.createElement("tbody")); + var tr = tbody.appendChild(document.createElement("tr")); + var td = tr.appendChild(document.createElement("td")); + var td1 = tr.appendChild(document.createElement("td")); + var td2 = tr.appendChild(document.createElement("td")); + + table.className = "cinput"; + tbody.className = "cinput"; + tr.className = "cinput"; + td.className = "ckeyb"; + td1.className = "cinput"; + td2.className = "csubmit"; + + this.input = td1.appendChild(this.input); + td2.onclick = function() + { + var ajax = new Ajax(me.callback); + ajax.process("index.php?mode=chat&module=Home&action=chat","submode=submit&msg="+escapeAll(me.input.value)+(me.to?"&to="+me.to:"")); + + me.input.value = ""; + me.input.focus(); + return false; + }; + + this.form = document.createElement("form"); + this.form.className = "cinput"; + + this.form.appendChild(table); + this.form.onsubmit = function() + { + var ajax = new Ajax(me.callback); + ajax.process("index.php?mode=chat&module=Home&action=chat","submode=submit&msg="+escapeAll(me.input.value)+(me.to?"&to="+me.to:"")); + me.input.value = ""; + me.input.focus(); + return false; + }; + + this.setFocus = function() + { + me.input.focus(); + }; + + // evaluate the returned json + this.callback = function(response) + { + response = response.responseText; + try{ + if(response) + debug("debug",response); + }catch(e){ + debug("debug","chatInput Error: "+response); + } + }; + + this.get = function() + { + return me.form; + }; +}; + +////////////////////////////////////////////////////////// +// Private chat handler / abre ventana de usurio + usuario +function PrivChat(dt,to,w,h) +{ + var me = this; + this.dt = dt; // delta time to sleep the requests. + this.to = to; // private chat the other user id + this.input = new chatInput(to); + this.toNick = getNick(to); + + var conf = new Array(); + conf["topic"] = "Private chat with "+me.toNick+""; + conf["class"] = "chat"; + conf["width"] = w; + conf["height"] = h; + conf["drag"] = true; + + this.win = new cssWindow(conf); + + // move z+1..crappy way to send above others + this.win.table.onDragStart = function() + { + resetChatsZ(); + chats[me.to].win.table.style.zIndex++; + }; + + this.win.cb = function() + { + me.ajax = new Ajax(me.callback); + me.ajax.process("index.php?mode=chat&module=Home&action=chat","submode=pvclose&to="+me.to); + chats[me.to]=null; + }; + + this.cbox = this.win.setBody(document.createElement("div")); + this.cbox.style.width = "100%"; + this.cbox.style.height = "100%"; + this.cbox.style.overflow = "auto"; + this.cbox.className = "chatbox"; + + // Draws the top of the window + this.getHead = function() + { + var t = document.createElement("table"); + t.style.width="100%";t.cellSpacing="0";t.cellPadding="0"; + var tb = t.appendChild(document.createElement("tbody")); + var tr = tb.appendChild(document.createElement("tr")); + var td = tr.appendChild(document.createElement("td")); + td.className = "chaticon"; + td = tr.appendChild(document.createElement("td")); + td.className = "chattopic1"; + td.innerHTML = me.win.topic; + var hide = tr.appendChild(document.createElement("td")); + hide.className = "chathide"; + hide.onclick = me.win.doHide; + var close = tr.appendChild(document.createElement("td")); + close.className = "chatclose"; + close.onclick = me.win.doClose; + return t; + }; + + this.win.setHead(this.getHead()); + this.win.setFoot(this.input.get()); + + + // updates the chat on the html + this.appendMsg = function(from,msg) + { + var div; + var span; + + span = document.createElement("span"); + span.appendChild(document.createTextNode(from+": ")); + span.className = "cunick"; + + div = document.createElement("div"); + div.className = "cumsg"; + + div.appendChild(span); + div.innerHTML+=msg; + me.cbox.appendChild(div); + me.cbox.scrollTop=me.cbox.scrollHeight; + }; + + // updates the chat on the html + this.appendSysMsg = function(msg) + { + var div; + div = document.createElement("div"); + div.className = "csmsg"; + div.innerHTML+=msg; + me.cbox.appendChild(div); + me.cbox.scrollTop=me.cbox.scrollHeight; + }; + + this.win.show(); + this.input.setFocus(); +}; + +////////////////////////////////////////////////////////// +// Public chat handler / abre ventana de usurio + usuario +function PubChat(dt,w,h) +{ + var me = this; + this.dt = dt; // delta time to sleep the requests. + this.to = 0; // public chat the other user id + this.input = new chatInput(this.to); + + var conf = new Array(); + conf["topic"] = "Public Chat"; + conf["class"] = "pchat"; + conf["width"] = w; + conf["height"] = h; + conf["drag"] = false; + + this.win = new cssWindow(conf); + + this.cbox = this.win.setBody(document.createElement("div")); + this.cbox.style.width = "100%"; + this.cbox.style.height = "100%"; + this.cbox.style.overflow = "auto"; + this.cbox.className = "chatbox"; + + // Draws the top of the window + this.getHead = function() + { + var t = document.createElement("table"); + t.style.width="100%";t.cellSpacing="0";t.cellPadding="0"; + var tb = t.appendChild(document.createElement("tbody")); + var tr = tb.appendChild(document.createElement("tr")); + var td = tr.appendChild(document.createElement("td")); + td.className = "chattopic"; + td.appendChild(document.createTextNode(me.win.topic)); + var hide = tr.appendChild(document.createElement("td")); + hide.className = "chathide"; + hide.onclick = me.win.doHide; + + return t; + }; + + this.win.setHead(this.getHead()); + this.win.setFoot(this.input.get()); + + // updates the chat on the html + this.appendMsg = function(from,msg) + { + var div; + var span; + + span = document.createElement("span"); + span.appendChild(document.createTextNode(from+": ")); + span.className = "cunick"; + + div = document.createElement("div"); + div.className = "cumsg"; + + div.appendChild(span); + div.innerHTML+=msg; + me.cbox.appendChild(div); + me.cbox.scrollTop=me.cbox.scrollHeight; + }; + + // updates the chat on the html + this.appendSysMsg = function(msg) + { + var div; + div = document.createElement("div"); + div.className = "csmsg"; + div.innerHTML+=msg; + me.cbox.appendChild(div); + me.cbox.scrollTop=me.cbox.scrollHeight; + }; + + this.get = function() + { + me.input.setFocus(); + return me.win.get(); + }; +}; diff --git a/oss/vtiger/trunk/modules/Home/js/css-window_p.js b/oss/vtiger/trunk/modules/Home/js/css-window_p.js new file mode 100644 index 00000000..15fe51ae --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/js/css-window_p.js @@ -0,0 +1 @@ +eval(function(p,a,c,k,e,d){e=function(c){return(c'New Contact', +'LBL_FIRST_NAME'=>'First Name:', +'LBL_LAST_NAME'=>'Last Name:', +'LBL_LIST_LAST_NAME'=>'Last Name', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_PHONE'=>'Phone:', +'LBL_EMAIL_ADDRESS'=>'Email:', +'LBL_TOTAL'=>'Total : ', + +'LBL_MY_HOME'=>'My Home', +'LBL_MODIFIED_TIME'=>'Modified Time', +'LBL_LOGIN_ID'=>'ID', +'LBL_MODIFIED_BY'=>'Modified By', +'LBL_TYPE'=>'Type', + +'LBL_PIPELINE_FORM_TITLE'=>'My Pipeline', + +'ERR_ONE_CHAR'=>'Please enter at least one letter or number for your search ...', + +'LBL_OPEN_TASKS'=>'My Open Tasks', + +'LBL_LEADS_BY_SOURCE'=>'Leads By Source', +'LBL_LEADS_BY_STATUS'=>'Leads By Status', + +'LBL_UPCOMING_EVENTS'=>'Upcoming Activities', +'LBL_PENDING_EVENTS'=>'Pending Activities', +'LBL_SINGLE_PENDING_EVENT'=>'Event for Last Ten Days', +'LBL_MULTIPLE_PENDING_EVENTS'=>'Events for Last Ten Days', + +'recordsforuser'=>'Records for', + +'Today'=>'Today', +'This Week'=>'This Week', +'This Month'=>'This Month', +'This Year'=>'This Year', +'Last Week'=>'Last Week', +'Last 2 Days'=>'Last 2 Days', +'Last Ten Days'=>'Last Ten Days', + +// Added/Updated for vtiger CRM 5.0.4 +'TITLE_AJAX_CSS_POPUP_CHAT'=>'Ajax Css-Popup chat', +'User List'=>'User List', + +// Added after 5.0.4 GA + +//ADDED for Home Page Customization +'LBL_HOME_MODULE' => 'Module', +'LBL_HOME_RSS' => 'RSS', +'LBL_HOME_DASHBOARD' => 'Dashboard', +'LBL_HOME_STUFFTITLE'=>'Window Title', +'LBL_HOME_SHOW'=>'Show', +'LBL_HOME_FILTERBY'=>'Filter By', +'LBL_HOME_Fields'=>'Fields To Show
(select any two)', +'LBL_HOME_PRESSCTRL'=>'(Press "Ctrl"
for multiple selection)', +'LBL_HOME_RSSURL'=>'RSS URL', +'LBL_HOME_DASHBOARD_NAME'=>'DashBoard Name', +'LBL_HOME_DASHBOARD_TYPE'=>'DashBoard Type', +'LBL_HOME_HORIZONTAL_BARCHART'=>'Horizontal Bar Chart', +'LBL_HOME_VERTICAL_BARCHART'=>'Vertical Bar Chart', +'LBL_HOME_PIE_CHART'=>'Pie Chart', +'LBL_HOME_ITEMS'=>'item(s)', +'LBL_MORE'=>'More', +'LBL_SCROLL'=>'Scroll', + +// vtiger CRM News +'LBL_NEWS_NO'=>'No news', + +//added for home page changes +'LBL_NOTEBOOK'=>'Notebook', +'LBL_NOTEBOOK_TITLE'=>'Double-click to edit.', +'LBL_NOTEBOOK_SAVE_TITLE'=>'Click anywhere else on the page to save.', + +'LBL_URL'=>'Website', +'LBL_HOME_LAYOUT'=>'Change layout', +'LBL_NUMBER_OF_COLUMNS'=>'Number of columns', +'LBL_TWO_COLUMN'=>'Two Columns', +'LBL_THREE_COLUMN'=>'Three Columns', +'LBL_FOUR_COLUMN'=>'Four Columns', +// END + +// Default home page widget's title +'Top Accounts'=>'Top Accounts', +'Top Potentials'=>'Top Potentials', +'Top Quotes'=>'Top Quotes', +'Top Trouble Tickets'=>'Top Trouble Tickets', +'Top Invoices'=>'Top Invoices', +'Top Sales Orders'=>'Top Sales Orders', +'Top Purchase Orders'=>'Top Purchase Orders', +'My New Leads'=>'My New Leads', +'Key Metrics'=>'Key Metrics', +'My Group Allocation'=>'My Group Allocation', +'My Recent FAQs'=>'My Recent FAQs', +'Upcoming Activities'=>'Upcoming Activities', +'Pending Activities'=>'Pending Activities', +'Home Page Dashboard'=>'Home Page Dashboard', +'Tag Cloud'=>'Tag Cloud', + +'MSG_NO_FILTERS' => 'No Filters Available', +'MSG_NO_FIELDS' => 'No Fields Available', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Home/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Home/language/zh_cn.lang.php new file mode 100644 index 00000000..ab95d297 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/language/zh_cn.lang.php @@ -0,0 +1,121 @@ + '新增联系人', + 'LBL_FIRST_NAME' => '姓名:', + 'LBL_LAST_NAME' => '姓氏:', + 'LBL_LIST_LAST_NAME' => '姓氏:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_PHONE' => '电话:', + 'LBL_EMAIL_ADDRESS' => '电子邮件:', + 'LBL_TOTAL' => '总计:', + + 'LBL_MY_HOME' => '我的首页', + 'LBL_MODIFIED_TIME' => '异动时间', + 'LBL_LOGIN_ID' => '代号', + 'LBL_MODIFIED_BY' => '修改者', + 'LBL_TYPE' => '类型', + + 'LBL_PIPELINE_FORM_TITLE' => '我的统计图表', + + 'ERR_ONE_CHAR' => '请至少输入1个字符以上的号码,以供搜寻 ...', + +'LBL_OPEN_TASKS' => '我的进行中任务', + + 'LBL_LEADS_BY_SOURCE' => '准客户来源', + 'LBL_LEADS_BY_STATUS' => '准客户状态', + + 'LBL_UPCOMING_EVENTS' => '未来事件', + 'LBL_PENDING_EVENTS' => '暂停事件', + 'LBL_SINGLE_PENDING_EVENT' => '最近十天事件', + 'LBL_MULTIPLE_PENDING_EVENTS' => '最近十天事件', + + 'recordsforuser' => '资料于', + + 'Today' => '今天', + 'This Week' => '这个星期', + 'This Month' => '这个月', + 'This Year' => '今年', + 'Last Week' => '上星期', + 'Last 2 Days' => '过去两天', + 'Last Ten Days' => '过去十天', + +'TITLE_AJAX_CSS_POPUP_CHAT'=>'员工聊天室', +'User List'=>'使用者列表', + +//ADDED for Home Page Customization +'LBL_HOME_MODULE' => '模块', +'LBL_HOME_RSS' => 'RSS', +'LBL_HOME_DASHBOARD' => '图表', +'LBL_HOME_STUFFTITLE'=>'窗口标题', +'LBL_HOME_SHOW'=>'显示', +'LBL_HOME_FILTERBY'=>'过滤', +'LBL_HOME_Fields'=>'要显示的字段
(选择任何两个)', +'LBL_HOME_PRESSCTRL'=>'(如需多个选择请按“ Ctrl ” 键)', +'LBL_HOME_RSSURL'=>'RSS URL', +'LBL_HOME_DASHBOARD_NAME'=>'图表名称', +'LBL_HOME_DASHBOARD_TYPE'=>'图表类型', +'LBL_HOME_HORIZONTAL_BARCHART'=>'横向柱状图', +'LBL_HOME_VERTICAL_BARCHART'=>'垂直柱状图', +'LBL_HOME_PIE_CHART'=>'饼图', +'LBL_HOME_ITEMS'=>'项目', +'LBL_MORE'=>'更多', +'LBL_SCROLL'=>'滚动', + +// vtiger CRM News +'LBL_NEWS_NO'=>'没有新闻', + +//added for home page changes +'LBL_NOTEBOOK'=>'笔记本', +'LBL_NOTEBOOK_TITLE'=>'双击进入编加状态.', +'LBL_NOTEBOOK_SAVE_TITLE'=>'点击页面其他部分进行保存.', + +'LBL_URL'=>'网站', +'LBL_HOME_LAYOUT'=>'变更版面', +'LBL_NUMBER_OF_COLUMNS'=>'列数', +'LBL_TWO_COLUMN'=>'两列', +'LBL_THREE_COLUMN'=>'三列', +'LBL_FOUR_COLUMN'=>'四列', +// END + +// Default home page widget's title +'Top Accounts'=>'最新客户', +'Top Potentials'=>'最新潜在机会', +'Top Quotes'=>'Top Quotes', +'Top Trouble Tickets'=>'最新报修记录', +'Top Invoices'=>'最新发票', +'Top Sales Orders'=>'最新订单', +'Top Purchase Orders'=>'最新采购订单', +'My New Leads'=>'最新潜在客户', +'Key Metrics'=>'关键指标', +'My Group Allocation'=>'我的群组分配', +'My Recent FAQs'=>'最新常见问题', +'Upcoming Activities'=>'近期活动', +'Pending Activities'=>'即将进行的活动', +'Home Page Dashboard'=>'首页图表', +'Tag Cloud'=>'常用标签', + +'MSG_NO_FILTERS' => '无过滤器可用', +'MSG_NO_FIELDS' => '无可用字段', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Home/vtchat.html b/oss/vtiger/trunk/modules/Home/vtchat.html new file mode 100644 index 00000000..a072ffd3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/vtchat.html @@ -0,0 +1,124 @@ + + + + + + + + + + +<?php echo $mod_strings['TITLE_AJAX_CSS_POPUP_CHAT'];?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
 
+
+ +
+
 
 
+
+
+
+ + + +
+ + + diff --git a/oss/vtiger/trunk/modules/Home/vtchat.php b/oss/vtiger/trunk/modules/Home/vtchat.php new file mode 100644 index 00000000..a2ca9469 --- /dev/null +++ b/oss/vtiger/trunk/modules/Home/vtchat.php @@ -0,0 +1,124 @@ + + + + + + + + + + + +<?php echo $mod_strings['TITLE_AJAX_CSS_POPUP_CHAT'];?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + +
 
+
+ +
+
 
 
+
+
+
+ + + +
+ + + diff --git a/oss/vtiger/trunk/modules/Import/Forms.php b/oss/vtiger/trunk/modules/Import/Forms.php new file mode 100644 index 00000000..1bcda405 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/Forms.php @@ -0,0 +1,259 @@ +$unused) + { + $print_required_array .= "required['$required'] = '". $all_fields[$required] . "';\n"; + + } + + $the_script = << + + + +EOQ; + + return $the_script; +} + + + + +function get_validate_upload_js () +{ + global $mod_strings; + + $err_missing_required_fields = $mod_strings['ERR_MISSING_REQUIRED_FIELDS']; + $lbl_select_file = $mod_strings['ERR_SELECT_FILE']; + $lbl_custom = $mod_strings['LBL_CUSTOM']; + + $the_script = << + + + +EOQ; + + return $the_script; +} + +/** function used to form the combo values with the available importable fields + * @param array reference &$column_fields - reference of the column fields which will be like lastname=>1, etc where as the key is the field name based on the import module and value is 1 + * @param int $colnum - column number + * @param array reference &$required_fields - required fields of the import module + * @param string $suggest_field - field to show as selected in the combo box + * @param array $translated_fields - list of fields which are available to map + * @param string $module - tablename for the import module + * @return picklist $output - return the combo box ie., picklist with the fields which are available to map + */ +function getFieldSelect(&$column_fields,$colnum,&$required_fields,$suggest_field,$translated_fields,$module) +{ + global $mod_strings; + global $app_strings; + global $outlook_contacts_field_map; + require_once('include/database/PearDatabase.php'); + global $adb; + + $output = "\n"; + return $output; +} + + +function get_readonly_js () +{ +?> + + + diff --git a/oss/vtiger/trunk/modules/Import/ImportAccount.php b/oss/vtiger/trunk/modules/Import/ImportAccount.php new file mode 100644 index 00000000..f9d8e8aa --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportAccount.php @@ -0,0 +1,217 @@ +'account_type_dom' + // ,'industry'=>'industry_dom'); + //$comboFieldArray = getComboArray($comboFieldNames); + + + // This is the list of vtiger_fields that are required. + var $required_fields = array("accountname"=>1); + + // This is the list of the functions to run when importing + var $special_functions = array( + "map_member_of","modseq_number", + //"add_billing_address_streets" + //,"add_shipping_address_streets" + //,"fix_website" + ); + + /* + function fix_website() + { + if ( isset($this->website) && + preg_match("/^http:\/\//",$this->website) ) + { + $this->website = substr($this->website,7); + } + } + + + function add_industry() + { + if ( isset($this->industry) && + ! isset( $comboFieldArray['industry_dom'][$this->industry])) + { + unset($this->industry); + } + } + + function add_type() + { + if ( isset($this->type) && + ! isset($comboFieldArray['account_type_dom'][$this->type])) + { + unset($this->type); + } + } + + function add_billing_address_streets() + { + if ( isset($this->billing_address_street_2)) + { + $this->billing_address_street .= + " ". $this->billing_address_street_2; + } + + if ( isset($this->billing_address_street_3)) + { + $this->billing_address_street .= + " ". $this->billing_address_street_3; + } + if ( isset($this->billing_address_street_4)) + { + $this->billing_address_street .= + " ". $this->billing_address_street_4; + } + } + + function add_shipping_address_streets() + { + if ( isset($this->shipping_address_street_2)) + { + $this->shipping_address_street .= + " ". $this->shipping_address_street_2; + } + + if ( isset($this->shipping_address_street_3)) + { + $this->shipping_address_street .= + " ". $this->shipping_address_street_3; + } + + if ( isset($this->shipping_address_street_4)) + { + $this->shipping_address_street .= + " ". $this->shipping_address_street_4; + } + } + */ + + // This is the list of vtiger_fields that are importable. + // some if these do not map directly to database columns + /*var $importable_fields = Array( + "id"=>1 + ,"name"=>1 + ,"website"=>1 + ,"industry"=>1 + ,"account_type"=>1 + ,"ticker_symbol"=>1 + ,"parent_name"=>1 + ,"employees"=>1 + ,"ownership"=>1 + ,"phone_office"=>1 + ,"phone_fax"=>1 + ,"phone_alternate"=>1 + ,"email1"=>1 + ,"email2"=>1 + ,"rating"=>1 + ,"sic_code"=>1 + ,"annual_revenue"=>1 + ,"billing_address_street"=>1 + ,"billing_address_street_2"=>1 + ,"billing_address_street_3"=>1 + ,"billing_address_street_4"=>1 + ,"billing_address_city"=>1 + ,"billing_address_state"=>1 + ,"billing_address_postalcode"=>1 + ,"billing_address_country"=>1 + ,"shipping_address_street"=>1 + ,"shipping_address_street_2"=>1 + ,"shipping_address_street_3"=>1 + ,"shipping_address_street_4"=>1 + ,"shipping_address_city"=>1 + ,"shipping_address_state"=>1 + ,"shipping_address_postalcode"=>1 + ,"shipping_address_country"=>1 + ,"description"=>1 + ); + */ + + var $importable_fields = Array(); + + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportAccount() { + parent::Accounts(); + $this->log = LoggerManager::getLogger('import_account'); + $this->db = PearDatabase::getInstance(); + $this->db->println("IMP ImportAccount"); + $this->initImportableFields("Accounts"); + + $this->db->println($this->importable_fields); + } + + /** function used to map with existing Mamber Of(Account) if the account is map with an member of during import + */ + function map_member_of() + { + global $adb; + + $account_name = $this->column_fields['account_id']; + $adb->println("Entering map_member_of account_id=".$account_name); + + if ((! isset($account_name) || $account_name == '') ) + { + $adb->println("Exit map_member_of. Account Name(Member Of) not set for this entity."); + return; + } + + $account_name = trim($account_name); + + //Query to get the available Account which is not deleted + $query = "select accountid from vtiger_account inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid WHERE vtiger_account.accountname=? and vtiger_crmentity.deleted=0"; + $account_id = $adb->query_result($adb->pquery($query, array($account_name)),0,'accountid'); + + if($account_id == '' || !isset($account_id)) + $account_id = 0; + + $this->column_fields['account_id'] = $account_id; + + $adb->println("Exit map_member_of. Fetched Account for '".$account_name."' and the account_id = $account_id"); + } + + // Module Sequence Numbering + function modseq_number() { + $this->column_fields['account_no'] = ''; + } + // END + +} + + + +?> diff --git a/oss/vtiger/trunk/modules/Import/ImportAjax.php b/oss/vtiger/trunk/modules/Import/ImportAjax.php new file mode 100644 index 00000000..45b8c905 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportAjax.php @@ -0,0 +1,82 @@ +pquery($query, array($map_name)); + $noofrows = $adb->num_rows($Result); + if($noofrows > 0) + echo "false"; //Map name already exists + else + echo "true"; +} +else +{ + + if($_REQUEST['delete_map'] != '') + { + $query = "update vtiger_import_maps set deleted=1 where id = ?"; + $adb->pquery($query, array($_REQUEST['mapping'])); + } + + $mapping_file = new ImportMap(); + $mapping_arr = $mapping_file->getSavedMappingContent($_REQUEST['mapping']); + + $importable_fields = $_SESSION['import_module_object_column_fields']; + $field_count = $_SESSION['import_module_field_count']; + $required_fields = $_SESSION['import_module_object_required_fields']; + $translated_column_fields = $_SESSION['import_module_translated_column_fields']; + + $tablename = ''; + $has_header = $_SESSION['import_has_header']; + $firstrow = $_SESSION['import_firstrow']; + $field_map = &$mapping_arr;//$_SESSION['import_field_map']; + $smarty_array1 = array(); + + for($i=0;$i<$field_count;$i++) + { + $suggest = ''; + if ($has_header && isset( $field_map[$firstrow[$i]] ) ) + { + $suggest = $field_map[$firstrow[$i]]; + } + else if (isset($field_map[$i])) + { + $suggest = $field_map[$i]; + } + + $smarty_array1[$i+1] = getFieldSelect( $importable_fields, + $i, + $required_fields, + $suggest, + $translated_column_fields, + $tablename + ); + } + + $smarty = new vtigerCRM_Smarty; + $smarty->assign("FIRSTROW",$firstrow); + $smarty->assign("SELECTFIELD",$smarty_array1); + + $smarty->display('ImportMap.tpl'); + +} + +?> diff --git a/oss/vtiger/trunk/modules/Import/ImportButton.php b/oss/vtiger/trunk/modules/Import/ImportButton.php new file mode 100644 index 00000000..93b15edc --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportButton.php @@ -0,0 +1,51 @@ + +
  • + +
  • + +
  • + +
  • + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportContact.php b/oss/vtiger/trunk/modules/Import/ImportContact.php new file mode 100644 index 00000000..94da2cc1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportContact.php @@ -0,0 +1,305 @@ +salutation) && + ! isset( $comboFieldArray['salutation_dom'][ $this->salutation ]) ) + { + $this->salutation = ''; + } + } + + function add_lead_source() + { + if ( isset($this->lead_source) && + ! isset( $comboFieldArray['lead_source_dom'][ $this->lead_source ]) ) + { + $this->lead_source = ''; + } + + } + + function add_birthdate() + { + if ( isset($this->birthdate)) + { + if (! preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/',$this->birthdate)) + { + $this->birthdate = ''; + } + } + + } + + function add_do_not_call() + { + if ( isset($this->do_not_call) && $this->do_not_call != 'on') + { + $this->do_not_call = ''; + } + + } + + function add_email_opt_out() + { + if ( isset($this->email_opt_out) && $this->email_opt_out != 'on') + { + $this->email_opt_out = ''; + } + } + + function add_primary_address_streets() + { + if ( isset($this->primary_address_street_2)) + { + $this->primary_address_street .= " ". $this->primary_address_street_2; + } + + if ( isset($this->primary_address_street_3)) + { + $this->primary_address_street .= " ". $this->primary_address_street_3; + } + } + + function add_alt_address_streets() + { + if ( isset($this->alt_address_street_2)) + { + $this->alt_address_street .= " ". $this->alt_address_street_2; + } + + if ( isset($this->alt_address_street_3)) + { + $this->alt_address_street .= " ". $this->alt_address_street_3; + } + + } + + function get_names_from_full_name() + { + if ( ! isset($this->full_name)) + { + return; + } + $arr = array(); + + $name_arr = preg_split('/\s+/',$this->full_name); + + if ( count($name_arr) == 1) + { + $this->last_name = $this->full_name; + } + + $this->first_name = array_shift($name_arr); + + $this->last_name = join(' ',$name_arr); + + } + */ + + // Module Sequence Numbering + function modseq_number() { + $this->column_fields['contact_no'] = ''; + } + // END + + /** function used to create or map with existing account if the contact has mapped with an account during import + */ + function add_create_account() + { + global $adb; + // global is defined in UsersLastImport.php + global $imported_ids; + global $current_user; + + $acc_name = $this->column_fields['account_id']; + $adb->println("contact add_create acc=".$acc_name); + + if ((! isset($acc_name) || $acc_name == '') ) + { + return; + } + + $arr = array(); + + // check if it already exists + $focus = new Accounts(); + + $query = ''; + + // if user is defining the vtiger_account id to be associated with this contact.. + + //Modified to remove the spaces at first and last in vtiger_account name -- after 4.2 patch 2 + $acc_name = trim($acc_name); + + //Modified the query to get the available account only ie., which is not deleted + $query = "select vtiger_crmentity.deleted, vtiger_account.* from vtiger_account, vtiger_crmentity WHERE accountname=? and vtiger_crmentity.crmid =vtiger_account.accountid and vtiger_crmentity.deleted=0"; + $result = $adb->pquery($query, array($acc_name)); + + $row = $this->db->fetchByAssoc($result, -1, false); + + $adb->println("fetched account"); + $adb->println($row); + + // we found a row with that id + if (isset($row['accountid']) && $row['accountid'] != -1) + { + $focus->id = $row['accountid']; + $adb->println("Account row exists - using same id=".$focus->id); + } + + // if we didnt find the vtiger_account, so create it + if (! isset($focus->id) || $focus->id == '') + { + $adb->println("Createing new vtiger_account"); + $focus->column_fields['accountname'] = $acc_name; + $focus->column_fields['assigned_user_id'] = $current_user->id; + $focus->column_fields['modified_user_id'] = $current_user->id; + + //$focus->saveentity("Accounts"); + $focus->save("Accounts"); + $acc_id = $focus->id; + + $adb->println("New Account created id=".$focus->id); + + // avoid duplicate mappings: + if (! isset( $imported_ids[$acc_id]) ) + { + $adb->println("inserting vtiger_users last import for vtiger_accounts"); + // save the new vtiger_account as a vtiger_users_last_import + $last_import = new UsersLastImport(); + $last_import->assigned_user_id = $current_user->id; + $last_import->bean_type = "Accounts"; + $last_import->bean_id = $focus->id; + $last_import->save(); + $imported_ids[$acc_id] = 1; + } + } + + $adb->println("prev contact accid=".$this->column_fields["account_id"]); + // now just link the vtiger_account + $this->column_fields["account_id"] = $focus->id; + $adb->println("curr contact accid=".$this->column_fields["account_id"]); + + } + + /** function used to map with existing Reports To(Contact) if the contact is map with reports to during import + */ + function map_reports_to() + { + global $adb; + + $contact_name = $this->column_fields['contact_id']; + $adb->println("Entering map_reports_to contact_id=".$contact_name); + + if ((! isset($contact_name) || $contact_name == '') ) + { + $adb->println("Exit map_reports_to. Contact Name(Reports To) not set for this entity."); + return; + } + + $contact_name = trim($contact_name); + + //Query to get the available Contact (Reports To) which is not deleted + $query = "select contactid from vtiger_contactdetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid WHERE concat(vtiger_contactdetails.lastname,' ',vtiger_contactdetails.firstname) = ? and vtiger_crmentity.deleted=0"; + $contact_id = $adb->query_result($adb->pquery($query, array($contact_name)),0,'contactid'); + + if($contact_id == '' || !isset($contact_id)) + $contact_id = 0; + + $this->column_fields['contact_id'] = $contact_id; + + $adb->println("Exit map_reports_to. Fetched Contact (Reports To) for '".$contact_name."' and the contactid = $contact_id"); + } + + + // This is the list of vtiger_fields that can be imported + // some of these don't map directly to columns in the db + + //we need to add two or more arrays as the columns are distributed across the vtiger_tables now + /*var $importable_fields = array( + "contactid"=>1, + "firstname"=>1, + "lastname"=>1, + "salutation"=>1, + "donotcall"=>1, + "emailoptout"=>1, + "accountid"=>1, + "title"=>1, + "department"=>1, + "phone"=>1, + "mobile"=>1, + "fax"=>1, + "email"=>1, + "otheremail"=>1, + "yahooid"=>1, + );*/ + + var $importable_fields = Array(); + + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportContact() { + parent::Contacts(); + $this->log = LoggerManager::getLogger('import_contact'); + $this->db = PearDatabase::getInstance(); + $this->db->println("IMP ImportContact"); + $this->initImportableFields("Contacts"); + $this->db->println($this->importable_fields); + } + +} + + + +?> diff --git a/oss/vtiger/trunk/modules/Import/ImportLead.php b/oss/vtiger/trunk/modules/Import/ImportLead.php new file mode 100644 index 00000000..1c381e6c --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportLead.php @@ -0,0 +1,100 @@ +column_fields["assigned_user_id"]; + $this->db->println("assign_user ".$ass_user." cur_user=".$current_user->id); + + if( $ass_user != $current_user->id) + { + $this->db->println("searching and assigning ".$ass_user); + + $result = $this->db->pquery("select id from vtiger_users where id = ? union select groupid as id from vtiger_groups where groupid = ?", array($ass_user, $ass_user)); + if($this->db->num_rows($result)!=1) + { + $this->db->println("not exact records setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + else + { + + $row = $this->db->fetchByAssoc($result, -1, false); + if (isset($row['id']) && $row['id'] != -1) + { + $this->db->println("setting id as ".$row['id']); + $this->column_fields["assigned_user_id"] = $row['id']; + } + else + { + $this->db->println("setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + } + } + } + + // Module Sequence Numbering + function modseq_number() { + $this->column_fields['lead_no'] = ''; + } + // END + + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportLead() { + parent::Leads(); + $this->log = LoggerManager::getLogger('import_lead'); + $this->db = PearDatabase::getInstance(); + $this->db->println("IMP ImportLead"); + $this->initImportableFields("Leads"); + $this->db->println($this->importable_fields); + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportMap.php b/oss/vtiger/trunk/modules/Import/ImportMap.php new file mode 100644 index 00000000..4aa1d40e --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportMap.php @@ -0,0 +1,226 @@ +"id"); + var $new_schema = true; + + var $column_fields = Array("id" + ,"name" + ,"module" + ,"content" + ,"has_header" + ,"deleted" + ,"date_entered" + ,"date_modified" + ,"assigned_user_id" + ,"is_published" + ); + + /** Constructor + */ + function ImportMap() + { + $this->log = LoggerManager::getLogger('file'); + $this->db = PearDatabase::getInstance(); + } + + /** function used to get the id, name, module and content as string + * @return string Object:ImportMap id=$this->id name=$this->name module=$this->module content=$this->content + */ + function toString() + { + return "Object:ImportMap id=$this->id name=$this->name module=$this->module content=$this->content"; + } + + /** function used to save the mapping + * @param int $owner_id - user id who is the owner for this mapping + * @param string $name - name of the mapping + * @param string $module - module name in which we have saved the mapping + * @param string $has_header - has_header value + * @param string $content - all fields which are concatenated with & symbol + * @return int $result - return 1 if the mapping contents updated + */ + function save_map( $owner_id, $name, $module, $has_header,$content ) + { + $query_arr = array('assigned_user_id'=>$owner_id,'name'=>$name); + + //$this->retrieve_by_string_fields($query_arr, false); + + $result = 1; + $this->assigned_user_id = $owner_id; + + $this->name = $name; + $this->module = $module; + + $this->content = "".$this->db->getEmptyBlob().""; + $this->has_header = $has_header; + $this->deleted = 0; + + //check whether this map name is already exist, if yes then overwrite the existing one, else create new + $res = $this->db->pquery("select id from vtiger_import_maps where name=?", array(trim($name))); + if($this->db->num_rows($res) > 0) + { + $this->id = $this->db->query_result($res,0,'id'); + } + + $returnid = $this->save(); + + $this->db->updateBlob($this->table_name,"content","name='". $this->db->sql_escape_string($name)."' and module='".$module."'",$content); + + return $result; + } + + /** function used to publish or unpublish the mapping + * @param int $user_id - user id who is publishing the map + * @param string $flag - yes or no + * @return value - if flag is yes then update the db and return 1 otherwise return -1 + */ + function mark_published($user_id,$flag) + { + $other_map = new ImportMap(); + + if ($flag == 'yes') + { + // if you are trying to publish your map + // but there's another published map + // by the same name + + $query_arr = array('name'=>$this->name, + 'is_published'=>'yes'); + } + else + { + // if you are trying to unpublish a map + // but you own an unpublished map by the same name + $query_arr = array('name'=>$this->name, + 'assigned_user_id'=>$user_id, + 'is_published'=>'no'); + } + $other_map->retrieve_by_string_fields($query_arr, false); + + if ( isset($other_map->id) ) + { + //.. don't do it! + return -1; + } + + $query = "UPDATE $this->table_name set is_published=?, assigned_user_id=? where id=?"; + $params = array($flag, $user_id, $this->id); + $this->db->pquery($query,$params,true,"Error marking import map published: "); + return 1; + } + + + /** function to retrieve all the column fields and set as properties + * @param array $fields_array - fields array of the corresponding module + * @return array $obj_arr - return an array which contains the retrieved column_field values as properties + */ + function retrieve_all_by_string_fields($fields_array) + { + $where_clause = $this->get_where($fields_array); + $query = "SELECT * FROM $this->table_name $where_clause"; + $this->log->debug("Retrieve $this->object_name: ".$query); + $result = & $this->db->query($query,true," Error: "); + $obj_arr = array(); + + while ($row = $this->db->fetchByAssoc($result,-1,FALSE) ) + { + $focus = new ImportMap(); + + foreach($this->column_fields as $field) + { + if(isset($row[$field])) + { + $focus->$field = $row[$field]; + } + } + array_push($obj_arr,$focus); + } + return $obj_arr; + } + + /** function used to get the list of saved mappings + * @param string $module - module name which we currently importing + * @return array $map_lists - return the list of mappings in the format of [id]=>name + */ + function getSavedMappingsList($module) + { + $query = "SELECT * FROM $this->table_name where module=? and deleted=0"; + $result = $this->db->pquery($query,array($module),true," Error: "); + $map_lists = array(); + + while ($row = $this->db->fetchByAssoc($result,-1,FALSE) ) + { + $map_lists[$row['id']] = $row['name']; + } + return $map_lists; + } + + /** function used to retrieve the mapping content for the passed mapid + * @param int $mapid - mapid for the selected map + * @return array $mapping_arr - return the array which contains the mapping_arr[name]=value from the content of the map + */ + function getSavedMappingContent($mapid) + { + $query = "SELECT * FROM $this->table_name where id=? and deleted=0"; + $result = $this->db->pquery($query,array($mapid),true," Error: "); + $mapping_arr = array(); + + $pairs = split("&",$this->db->query_result($result,0,'content')); + foreach ($pairs as $pair) + { + list($name,$value) = split("=",$pair); + $mapping_arr["$name"] = $value; + } + + return $mapping_arr; + } + +} + + +?> diff --git a/oss/vtiger/trunk/modules/Import/ImportOpportunity.php b/oss/vtiger/trunk/modules/Import/ImportOpportunity.php new file mode 100644 index 00000000..3ae55bfc --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportOpportunity.php @@ -0,0 +1,125 @@ +column_fields["assigned_user_id"]; + $this->db->println("assign_user ".$ass_user." cur_user=".$current_user->id); + + if( $ass_user != $current_user->id) + { + $this->db->println("searching and assigning ".$ass_user); + + $result = $this->db->pquery("select id from vtiger_users where id = ? union select groupid as id from vtiger_groups where groupid = ?", array($ass_user, $ass_user)); + if($this->db->num_rows($result)!=1) + { + $this->db->println("not exact records setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + else + { + + $row = $this->db->fetchByAssoc($result, -1, false); + if (isset($row['id']) && $row['id'] != -1) + { + $this->db->println("setting id as ".$row['id']); + $this->column_fields["assigned_user_id"] = $row['id']; + } + else + { + $this->db->println("setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + } + } +} + /** function used to map with existing Campaign Source if the potential is map with an campaign during import + */ + function map_campaign_source(){ + global $adb; + + $campaign_name = $this->column_fields['campaignid']; + $adb->println("Entering map_campaign_source campaignid=".$campaign_name); + + if ((! isset($campaign_name) || $campaign_name == '') ){ + $adb->println("Exit map_campaign_source. Campaign Name not set for this entity."); + return; + } + + $campaign_name = trim($campaign_name); + + //Query to get the available campaign which is not deleted + $query = "select campaignid from vtiger_campaign inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_campaign.campaignid WHERE vtiger_campaign.campaignname=? and vtiger_crmentity.deleted=0"; + + $campaignid = $adb->query_result($adb->pquery($query, array($campaign_name)),0,'campaignid'); + + if($campaignid == '' || !isset($campaignid)){ + $campaignid = 0; + } + + $this->column_fields['campaignid'] = $campaignid; + $adb->println("Exit map_campaign_source. Fetched Campaign for '".$campaign_name."' and the campaignid = $campaignid"); + } + + var $importable_fields = Array(); + + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportOpportunity() { + parent::Potentials(); + $this->log = LoggerManager::getLogger('import_opportunity'); + $this->db = PearDatabase::getInstance(); + + $this->db->println("IMP ImportOpportunity"); + $this->initImportableFields("Potentials"); + $this->db->println($this->importable_fields); + } + + // Module Sequence Numbering + function modseq_number() { + $this->column_fields['potential_no'] = ''; + } + // END +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportProduct.php b/oss/vtiger/trunk/modules/Import/ImportProduct.php new file mode 100644 index 00000000..f1d80f96 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportProduct.php @@ -0,0 +1,163 @@ +column_fields["assigned_user_id"]; + $this->db->println("assign_user ".$ass_user." cur_user=".$current_user->id); + + if( $ass_user != $current_user->id) + { + $this->db->println("searching and assigning ".$ass_user); + + $result = $this->db->pquery("select id from vtiger_users where id = ?", array($ass_user)); + if($this->db->num_rows($result)!=1) + { + $this->db->println("not exact records setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + else + { + + $row = $this->db->fetchByAssoc($result, -1, false); + if (isset($row['id']) && $row['id'] != -1) + { + $this->db->println("setting id as ".$row['id']); + $this->column_fields["assigned_user_id"] = $row['id']; + } + else + { + $this->db->println("setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + } + } + } + + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportProduct() { + parent::Products(); + $this->log = LoggerManager::getLogger('import_product'); + $this->db = PearDatabase::getInstance(); + $this->db->println("IMP ImportProduct"); + $this->initImportableFields("Products"); + $this->db->println($this->importable_fields); + } + + /** function used to map with existing Vendor if the product is map with an vendor during import + */ + function map_vendor_name() + { + global $adb; + + $vendor_name = $this->column_fields['vendor_id']; + $adb->println("Entering map_vendor_name vendor_id=".$vendor_name); + + if ((! isset($vendor_name) || $vendor_name == '') ) + { + $adb->println("Exit map_vendor_name. Vendor Name not set for this entity."); + return; + } + + $vendor_name = trim($vendor_name); + + //Query to get the available Vendor which is not deleted + $query = "select vendorid from vtiger_vendor inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_vendor.vendorid WHERE vtiger_vendor.vendorname=? and vtiger_crmentity.deleted=0"; + $vendor_id = $adb->query_result($adb->pquery($query, array($vendor_name)),0,'vendorid'); + + if($vendor_id == '' || !isset($vendor_id)) + $vendor_id = 0; + + $this->column_fields['vendor_id'] = $vendor_id; + + $adb->println("Exit map_vendor_name. Fetched Vendor for '".$vendor_name."' and the vendorid = $vendor_id"); + } + + /** Function used to map with existing Member Of(Product) if the product is map with an member of during import + */ + function map_member_of() + { + global $adb; + + $product_name = $this->column_fields['product_id']; + $adb->println("Entering map_member_of product_id=".$product_name); + + if ((! isset($product_name) || $product_name == '') ) + { + $adb->println("Exit map_member_of. Product Name(Member Of) not set for this entity."); + return; + } + + $product_name = trim($product_name); + + //Query to get the available Product which is not deleted + $query = "select productid from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid WHERE vtiger_products.productname=? and vtiger_crmentity.deleted=0"; + $product_id = $adb->query_result($adb->pquery($query, array($product_name)),0,'productid'); + + if($product_id == '' || !isset($product_id)) + $product_id = 0; + + $this->column_fields['product_id'] = $product_id; + + $adb->println("Exit map_member_of. Fetched Account for '".$product_name."' and the account_id = $product_id"); + } + + //Module Sequence Numbering + function modseq_number() { + $this->column_fields['product_no'] = ''; + } + // END +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportSave.php b/oss/vtiger/trunk/modules/Import/ImportSave.php new file mode 100644 index 00000000..489fcf0c --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportSave.php @@ -0,0 +1,572 @@ +$data) + $users_groups_list[$data] = $key; + + $temp = get_group_array(FALSE); + foreach ( $temp as $key=>$data) + $users_groups_list[$data] = $key; + + p(print_r(users_groups_list,1)); + $adb->println("Users List : "); + $adb->println($users_groups_list); + $dup_count = 0; + $count = 0; + $dup_ow_count = 0; + $process_fields='false'; + if($start == 0) + { + $_SESSION['totalrows'] = $rows; + $_SESSION['return_field_count'] = $ret_field_count; + $_SESSION['column_position_to_field'] = $col_pos_to_field; + } + $ii = $start; + // go thru each row, process and save() + foreach ($rows1 as $row) + { + $adb->println("Going to Save the row ".$ii." =====> "); + $adb->println($row); + global $mod_strings; + + $do_save = 1; + //MWC + $my_userid = $current_user->id; + + //If we want to set default values for some fields for each entity then we have to set here + if($module == 'Products' || $module == 'Services')//discontinued is not null. if we unmap active, NULL will be inserted and query will fail + $focus->column_fields['discontinued'] = 'on'; + + for($field_count = 0; $field_count < $ret_field_count; $field_count++) + { + p("col_pos[".$field_count."]=".$col_pos_to_field[$field_count]); + + if ( isset( $col_pos_to_field[$field_count]) ) + { + p("set =".$field_count); + if (! isset( $row[$field_count]) ) + { + continue; + } + + p("setting"); + + // TODO: add check for user input + // addslashes, striptags, etc.. + $field = $col_pos_to_field[$field_count]; + + //picklist function is added to avoid duplicate picklist entries + $pick_orginal_val = getPicklist($field,$row[$field_count]); + + if($pick_orginal_val != null) + { + $focus->column_fields[$field]=$pick_orginal_val; + } + elseif (substr(trim($field), 0, 3) == "CF_") + { + p("setting custfld".$field."=".$row[$field_count]); + $resCustFldArray[$field] = $row[$field_count]; + } + //MWC + elseif ( $field == "assignedto" || $field == "assigned_user_id" ) + { + //Here we are assigning the user id in column fields, so in function assign_user (ImportLead.php and ImportProduct.php files) we should use the id instead of user name when query the user + //or we can use $focus->column_fields['smownerid'] = $users_groups_list[$row[$field_count]]; + $focus->column_fields[$field] = $users_groups_list[trim($row[$field_count])]; + p("setting my_userid=$my_userid for user=".$row[$field_count]); + } + else + { + //$focus->$field = $row[$field_count]; + $focus->column_fields[$field] = $row[$field_count]; + p("Setting ".$field."=".$row[$field_count]); + } + + } + + } + if($focus->column_fields['notify_owner'] == '') + { + $focus->column_fields['notify_owner'] = '0'; + } + if($focus->column_fields['reference'] == '') + { + $focus->column_fields['reference'] = '0'; + } + if($focus->column_fields['emailoptout'] == '') + { + $focus->column_fields['emailoptout'] = '0'; + } + if($focus->column_fields['donotcall'] == '') + { + $focus->column_fields['donotcall'] = '0'; + } + if($focus->column_fields['discontinued'] == '') + { + $focus->column_fields['discontinued'] = '0'; + } + if($focus->column_fields['active'] == '') + { + $focus->column_fields['active'] = '0'; + } + p("setting done"); + + p("do save before req vtiger_fields=".$do_save); + + $adb->println($focus->required_fields); + foreach ($focus->required_fields as $field=>$notused) + { + $fv = trim($focus->column_fields[$field]); + if (! isset($fv) || $fv == '') + { + // Leads Import does not allow an empty lastname because the link is created on the lastname + // Without lastname the Lead could not be opened. + // But what if the import file has only company and telefone information? + // It would be stupid to skip all the companies which don't have a contact person yet! + // So we set lastname ="?????" and the user can later enter a name. + // So the lastname is still mandatory but may be empty. + if ($field == 'lastname' && $module == 'Leads') + { + $focus->column_fields[$field] = '?????'; + } + else + { + p("fv ".$field." not set"); + $do_save = 0; + $skip_required_count++; + break; + } + } + } + + if ( ! isset($focus->column_fields["assigned_user_id"]) || $focus->column_fields["assigned_user_id"]==='' || $focus->column_fields["assigned_user_id"]===NULL) { + $focus->column_fields["assigned_user_id"] = $my_userid; + } + + //added for duplicate handling + if(is_record_exist($module,$focus)) + { + if($do_save != 0) + { + $do_save = 0; + $dup_count++; + } + } + p("do save=".$do_save); + + if ($do_save) + { + p("saving.."); + + if ( ! isset($focus->column_fields["assigned_user_id"]) || $focus->column_fields["assigned_user_id"]=='') + { + //$focus->column_fields["assigned_user_id"] = $current_user->id; + //MWC + $focus->column_fields["assigned_user_id"] = $my_userid; + } + + //handle uitype 10 + foreach($focus->importable_fields as $fieldname=>$uitype){ + $uitype = $focus->importable_fields[$fieldname]; + if($uitype == 10){ + //added to handle security permissions for related modules :: for e.g. Accounts/Contacts in Potentials + if(method_exists($focus, "add_related_to")){ + if(!$focus->add_related_to($module, $fieldname)){ + if(array_key_exists($fieldname, $focus->required_fields)){ + $do_save = 0; + $skip_required_count++; + continue 2; + } + } + } + } + } + + // now do any special processing for ex., map account with contact and potential + if($process_fields == 'false'){ + $focus->process_special_fields(); + } + + $focus->save($module); + //$focus->saveentity($module); + $return_id = $focus->id; + + if(count($resCustFldArray)>0){ + if($_REQUEST['module'] == 'Contacts'){ + $_REQUEST['module']='contactdetails'; + } + $dbquery="select * from vtiger_field where vtiger_tablename=? and vtiger_field.presence in (0,2)"; + $custresult = $adb->pquery($dbquery, array($_REQUEST['module'])); + if($adb->num_rows($custresult) != 0) + { + if (! isset( $_REQUEST['module'] ) || $_REQUEST['module'] == 'Contacts') + { + $columns = 'contactid'; + $custTabName = 'contactscf'; + } + else if ( $_REQUEST['module'] == 'Accounts') + { + $columns = 'accountid'; + $custTabName = 'accountscf'; + } + else if ( $_REQUEST['module'] == 'Potentials') + { + $columns = 'potentialid'; + $custTabName = 'potentialscf'; + } + else if ( $_REQUEST['module'] == 'Leads') + { + $columns = 'leadidid'; + $custTabName = 'leadscf'; + } + else if ( $_REQUEST['module'] == 'Products') + { + $columns = 'productid'; + $custTabName = 'productcf'; + } + else if ( $_REQUEST['module'] == 'Helpdesk') + { + $columns = 'ticketid'; + $custTabName = 'ticketcf'; + } + else if ( $_REQUEST['module'] == 'Vendors') + { + $columns = 'vendorid'; + $custTabName = 'vendorcf'; + } + $noofrows = $adb->num_rows($custresult); + $params = array($focus->id); + + for($j=0; $j<$noofrows; $j++) + { + $colName=$adb->query_result($custresult,$j,"columnname"); + if(array_key_exists($colName, $resCustFldArray)) + { + $value_colName = $resCustFldArray[$colName]; + + $columns .= ', '.$colName; + array_push($params, $value_colName); + } + } + + $insert_custfld_query = 'insert into '.$custTabName.' ('.$columns.') values('. generateQuestionMarks($params) .')'; + $adb->pquery($insert_custfld_query, $params); + + } + } + + $last_import = new UsersLastImport(); + $last_import->assigned_user_id = $current_user->id; + $last_import->bean_type = $_REQUEST['module']; + $last_import->bean_id = $focus->id; + $last_import->save(); + array_push($saved_ids,$focus->id); + $count++; + } + $ii++; + } + + $_REQUEST['count'] = $ii; + if(isset($_REQUEST['module'])) + $modulename = vtlib_purify($_REQUEST['module']); + + $end = $start+$recordcount; + $START = $start + $recordcount; + $RECORDCOUNT = $recordcount; + $dup_check_type = $_REQUEST['dup_type']; + + if($end >= $totalnoofrows) { + $module = 'Import';//$_REQUEST['module']; + $action = 'ImportSteplast'; + //exit; + $imported_records = $totalnoofrows - $skip_required_count; + if($imported_records == $totalnoofrows) { + $skip_required_count = 0; + } + if($dup_check_type == "auto") { + $auto_dup_type = $_REQUEST['auto_type']; + if($auto_dup_type == "ignore") { + $dup_info = $mod_strings['Duplicate_Records_Skipped_Info'].$dup_count; + $imported_records -= $dup_count; + } + else if($auto_dup_type == "overwrite") { + $dup_info = $mod_strings['Duplicate_Records_Overwrite_Info'].$dup_ow_count; + $imported_records -= $dup_ow_count; + } + } + else + $dup_info = ""; + + if($imported_records < 0) $imported_records = 0; + + $message= urlencode("".$mod_strings['LBL_SUCCESS'].""."

    " .$mod_strings['LBL_SUCCESS_1']." $imported_records" ."

    " .$mod_strings['LBL_SKIPPED_1']." $skip_required_count

    ".$dup_info ); + } else { + $module = 'Import'; + $action = 'ImportStep3'; + } +?> + + + +'.$start.' '.$mod_strings['to'].' '.$end.' '.$mod_strings['of'].' '.$totalnoofrows.' '.$mod_strings['are_imported_succesfully']; + //return $_SESSION['import_display_message']; +} + +function is_record_exist($module,$focus) +{ + global $adb; + global $dup_ow_count; + $dup_check_type = $_REQUEST['dup_type']; + $auto_dup_type = ""; + $sec_parameter = ""; + if($dup_check_type == 'auto') + { + $auto_dup_type = $_REQUEST['auto_type']; + } + if($auto_dup_type == "ignore") + { + $sec_parameter = getSecParameterforMerge($module); + if($module == "Leads") + { + $sel_qry = "select count(*) as count from vtiger_leaddetails + inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_leaddetails.leadid + inner join vtiger_leadsubdetails on vtiger_leaddetails.leadid = vtiger_leadsubdetails.leadsubscriptionid + inner join vtiger_leadaddress on vtiger_leadaddress.leadaddressid = vtiger_leaddetails.leadid + left join vtiger_leadscf on vtiger_leadscf.leadid = vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + where vtiger_crmentity.deleted = 0 AND vtiger_leaddetails.converted = 0 $sec_parameter"; + } + else if($module == "Accounts") + { + $sel_qry = "SELECT count(*) as count FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid = vtiger_accountscf.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted = 0 $sec_parameter"; + } + else if($module == "Contacts") + { + $sel_qry = "SELECT count(*) as count FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactaddress.contactaddressid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactsubdetails.contactsubscriptionid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted = 0 $sec_parameter"; + } + else if($module == "Products") + { + $sel_qry = "SELECT count(*) as count FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + WHERE vtiger_crmentity.deleted = 0 "; + } + else if($module == "Vendors") + { + $sel_qry = "select count(*) as count from vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid = vtiger_vendor.vendorid + WHERE vtiger_crmentity.deleted = 0"; + } else { + $sel_qry = "select count(*) as count from $focus->table_name + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $focus->table_name.$focus->table_index"; + // Consider custom table join as well. + if(isset($focus->customFieldTable)) { + $sel_qry .= " INNER JOIN ".$focus->customFieldTable[0]." ON ".$focus->customFieldTable[0].'.'.$focus->customFieldTable[1] . + " = $focus->table_name.$focus->table_index"; + } + $sel_qry .= " LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id + WHERE vtiger_crmentity.deleted = 0 $sec_parameter"; + } + $sel_qry .= get_where_clause($module,$focus->column_fields); + $result = $adb->query($sel_qry); + $cnt = $adb->query_result($result,0,"count"); + if($cnt > 0) + return true; + else + return false; + } + else if($auto_dup_type == "overwrite") + { + return overwrite_duplicate_records($module,$focus); + } + else + return false; +} +//function to get the where clause for the duplicate - select query +function get_where_clause($module,$column_fields) { + global $current_user, $dup_ow_count, $adb; + $where_clause = ""; + $field_values_array=getFieldValues($module); + $field_values=$field_values_array['fieldnames_list']; + $tblname_field_arr = explode(",",$field_values); + $uitype_arr = $field_values_array['fieldname_uitype']; + + $focus = CRMEntity::getInstance($module); + + foreach($tblname_field_arr as $val) { + list($tbl,$col,$fld) = explode(".",$val); + $col_name = $tbl ."." . $col; + $field_value=$column_fields[$fld]; + + if($fld == $focus->table_index && $column_fields[$focus->table_index] !='' && !is_integer($column_fields[$focus->table_index])) { + $field_value = getEntityId($module, $column_fields[$focus->table_index]); + } + + if(is_uitype($uitype_arr[$fld],'_users_list_') && $field_value == '') { + $field_value = $current_user->id; + } + $where_clause .= " AND ifnull(". $adb->sql_escape_string($col_name) .",'') = ifnull('". $adb->sql_escape_string($field_value) ."','') "; + } + return $where_clause; +} +//function to overwrite the existing duplicate records with the importing record's values +function overwrite_duplicate_records($module,$focus) +{ + global $adb; + global $dup_ow_count; + global $process_fields; + + $where_clause = ""; + $where = get_where_clause($module,$focus->column_fields); + $sec_parameter = getSecParameterforMerge($module); + if($module == "Leads") + { + $sel_qry = "select vtiger_leaddetails.leadid from vtiger_leaddetails + inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_leaddetails.leadid + inner join vtiger_leadsubdetails on vtiger_leaddetails.leadid = vtiger_leadsubdetails.leadsubscriptionid + inner join vtiger_leadaddress on vtiger_leadaddress.leadaddressid = vtiger_leaddetails.leadid + left join vtiger_leadscf on vtiger_leadscf.leadid = vtiger_leaddetails.leadid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + where vtiger_crmentity.deleted = 0 AND vtiger_leaddetails.converted = 0 $where $sec_parameter order by vtiger_leaddetails.leadid ASC"; + } + else if($module == "Accounts") + { + $sel_qry = "SELECT vtiger_account.accountid FROM vtiger_account + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_account.accountid + INNER JOIN vtiger_accountbillads ON vtiger_account.accountid = vtiger_accountbillads.accountaddressid + INNER JOIN vtiger_accountshipads ON vtiger_account.accountid = vtiger_accountshipads.accountaddressid + LEFT JOIN vtiger_accountscf ON vtiger_account.accountid = vtiger_accountscf.accountid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted = 0 $where $sec_parameter order by vtiger_account.accountid ASC"; + } + else if($module == "Contacts") + { + $sel_qry = "SELECT vtiger_contactdetails.contactid FROM vtiger_contactdetails + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactaddress ON vtiger_contactaddress.contactaddressid = vtiger_contactdetails.contactid + INNER JOIN vtiger_contactsubdetails ON vtiger_contactsubdetails.contactsubscriptionid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_contactscf ON vtiger_contactscf.contactid = vtiger_contactdetails.contactid + LEFT JOIN vtiger_customerdetails ON vtiger_customerdetails.customerid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid + WHERE vtiger_crmentity.deleted = 0 $where $sec_parameter order by vtiger_contactdetails.contactid ASC"; + } + else if($module == "Products") + { + $sel_qry = "SELECT vtiger_products.productid FROM vtiger_products + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid + LEFT JOIN vtiger_productcf ON vtiger_productcf.productid = vtiger_products.productid + WHERE vtiger_crmentity.deleted = 0 $where order by vtiger_products.productid ASC"; + } + else if($module == "Vendors") + { + $sel_qry = "SELECT vtiger_vendor.vendorid FROM vtiger_vendor + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_vendor.vendorid + LEFT JOIN vtiger_vendorcf ON vtiger_vendorcf.vendorid = vtiger_vendor.vendorid + WHERE vtiger_crmentity.deleted = 0 $where order by vtiger_vendor.vendorid ASC"; + } + else { + $sel_qry = "SELECT $focus->table_name.$focus->table_index FROM $focus->table_name + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = $focus->table_name.$focus->table_index"; + // Consider custom table join as well. + if(isset($focus->customFieldTable)) { + $sel_qry .= " INNER JOIN ".$focus->customFieldTable[0]." ON ".$focus->customFieldTable[0].'.'.$focus->customFieldTable[1] . + " = $focus->table_name.$focus->table_index"; + } + $sel_qry .= " LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid = vtiger_users.id + WHERE vtiger_crmentity.deleted = 0 $where $sec_parameter order by $focus->table_name.$focus->table_index ASC"; + } + $result = $adb->query($sel_qry); + $no_rows = $adb->num_rows($result); + // now do any special processing for ex., map account with contact and potential + $focus->process_special_fields(); + $process_fields='true'; + $moduleObj = new $module(); + if($no_rows > 0) + { + for($i=0;$i<$no_rows;$i++) + { + $id_field = $moduleObj->table_index; + $id_value = $adb->query_result($result,$i,$id_field); + if($i == 0) + { + $moduleObj->mode = "edit"; + $moduleObj->id = $id_value; + $moduleObj->column_fields = $focus->column_fields; + $moduleObj->save($module); + } + else{ + DeleteEntity($module,$module,$moduleObj,$id_value,""); + } + } + $dup_ow_count = $dup_ow_count+$no_rows; + return true; + } + else + return false; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportStep1.php b/oss/vtiger/trunk/modules/Import/ImportStep1.php new file mode 100644 index 00000000..f88ea776 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportStep1.php @@ -0,0 +1,104 @@ +info($mod_strings['LBL_MODULE_NAME'] . " Upload Step 1"); + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("IMP", $import_mod_strings); + +$smarty->assign("CATEGORY", htmlspecialchars($_REQUEST['parenttab'],ENT_QUOTES,$default_charset)); + +$import_object_array = Array( + "Leads"=>"ImportLead", + "Accounts"=>"ImportAccount", + "Contacts"=>"ImportContact", + "Potentials"=>"ImportOpportunity", + "Products"=>"ImportProduct", + "HelpDesk"=>"ImportTicket", + "Vendors"=>"ImportVendors" + ); + +if(isset($_REQUEST['module']) && $_REQUEST['module'] != '') +{ + $object_name = $import_object_array[$_REQUEST['module']]; + // vtlib customization: Hook added to enable import for un-mapped modules + $module = $_REQUEST['module']; + if($object_name == null) { + checkFileAccess("modules/$module/$module.php"); + require_once("modules/$module/$module.php"); + $object_name = $module; + $callInitImport = true; + } + // END + $focus = new $object_name(); + // vtlib customization: Call the import initializer + if($callInitImport) $focus->initImport($module); + // END +} +else +{ + echo "Sorry! Import Option is not provided for this module."; + exit; +} + +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'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +$smarty->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']); +$smarty->assign("HAS_HEADER_CHECKED"," CHECKED"); + +$smarty->assign("MODULE", $_REQUEST['module']); +$smarty->assign("MODULELABEL", getTranslatedString($_REQUEST['module'],$_REQUEST['module'])); +$smarty->assign("SOURCE", $_REQUEST['source']); + +//we have set this as default. upto 4.2.3 we have Outlook, Act, SF formats. but now CUSTOM is enough to import +$lang_key = "CUSTOM"; +$smarty->assign("INSTRUCTIONS_TITLE",$mod_strings["LBL_IMPORT_{$lang_key}_TITLE"]); + +for($i = 1; isset($mod_strings["LBL_{$lang_key}_NUM_$i"]);$i++) +{ + $smarty->assign("STEP_NUM",$mod_strings["LBL_NUM_$i"]); + $smarty->assign("INSTRUCTION_STEP",$mod_strings["LBL_{$lang_key}_NUM_$i"]); +} + +$smarty->display("ImportStep1.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportStep2.php b/oss/vtiger/trunk/modules/Import/ImportStep2.php new file mode 100644 index 00000000..60f71dbf --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportStep2.php @@ -0,0 +1,459 @@ + $upload_maxsize) +{ + show_error_import( $mod_strings['LBL_IMPORT_MODULE_ERROR_LARGE_FILE'] . " ". $upload_maxsize. " ". $mod_strings['LBL_IMPORT_MODULE_ERROR_LARGE_FILE_END']); + exit; +} +if( !is_writable( $import_dir )) +{ + show_error_import($mod_strings['LBL_IMPORT_MODULE_NO_DIRECTORY'].$import_dir.$mod_strings['LBL_IMPORT_MODULE_NO_DIRECTORY_END']); + exit; +} + +$tmp_file_name = $import_dir. "IMPORT_".$current_user->id; + +move_uploaded_file($_FILES['userfile']['tmp_name'], $tmp_file_name); + +// Convert ISO-8859 file (as saved by MS Excel) into UTF-8 to preserve umlauts and accents +if ($_REQUEST["format"] != "UTF-8") +{ + $fh = fopen($tmp_file_name,"r"); + $content = fread($fh, filesize($tmp_file_name)); + fclose($fh); + + if (function_exists("mb_convert_encoding")) + { + $content = mb_convert_encoding($content, 'UTF-8', $_REQUEST["format"]); + } else { + $content = iconv('UTF-8', $_REQUEST["format"], $content); + } + + $fh = fopen($tmp_file_name,"w"); + fwrite($fh, $content); + fclose($fh); +} + +// Now parse the file and look for errors +$ret_value = 0; + +if ($_REQUEST['source'] == 'act') +{ + $ret_value = parse_import_act($tmp_file_name,$delimiter,$max_lines,$has_header); +} +else +{ + $ret_value = parse_import($tmp_file_name,$delimiter,$max_lines,$has_header); +} + +if ($ret_value == -1) +{ + show_error_import( $mod_strings['LBL_CANNOT_OPEN'] ); + exit; +} +else if ($ret_value == -2) +{ + show_error_import( $mod_strings['LBL_NOT_SAME_NUMBER'] ); + exit; +} +else if ( $ret_value == -3 ) +{ + show_error_import( $mod_strings['LBL_NO_LINES'] ); + exit; +} + +$rows = $ret_value['rows']; +$ret_field_count = $ret_value['field_count']; + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("TMP_FILE", $tmp_file_name ); +$smarty->assign("SOURCE", vtlib_purify($_REQUEST['source'])); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +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'])); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +$smarty->assign("HEADER", $app_strings['LBL_IMPORT']." ". $mod_strings['LBL_MODULE_NAME']); +$smarty->assign("HASHEADER", $has_header); + +$import_object_array = Array( + "Leads"=>"ImportLead", + "Accounts"=>"ImportAccount", + "Contacts"=>"ImportContact", + "Potentials"=>"ImportOpportunity", + "Products"=>"ImportProduct", + "HelpDesk"=>"ImportTicket", + "Vendors"=>"ImportVendors" + ); + +if(isset($_REQUEST['module']) && $_REQUEST['module'] != '') +{ + $object_name = $import_object_array[$_REQUEST['module']]; + // vtlib customization: Hook added to enable import for un-mapped modules + $module = $_REQUEST['module']; + if($object_name == null) { + checkFileAccess("modules/$module/$module.php"); + require_once("modules/$module/$module.php"); + $object_name = $module; + $callInitImport = true; + } + // END + $focus = new $object_name(); + // vtlib customization: Call the import initializer + if($callInitImport) $focus->initImport($module); + //initialized the required fields,used to check for mandatory fields while importing + $focus->initRequiredFields($module); + // END +} +else +{ + $focus = new ImportContact(); +} + + +$total_num_rows=sizeof($rows); +$firstrow = $rows[0]; +if($total_num_rows >1 ) +{ + $secondrow = $rows[1]; +} +if($total_num_rows >2) +{ + $thirdrow = $rows[2]; +} + +//If the cell value is very large then UI mapping will be collpased. So we will display partial text +foreach($firstrow as $ind => $val) +{ + if(strlen($val) > 30) + $firstrow[$ind] = substr(to_html($val),0,30)." .........."; + else + $firstrow[$ind] = to_html($val); +} +if (isset($secondrow)) { //Asha: Fix for ticket #4432 + foreach($secondrow as $ind => $val) + { + if(strlen($val) > 30) + $secondrow[$ind] = substr(to_html($val),0,30)." .........."; + else + $secondrow[$ind] = to_html($val); + + } + if (isset($thirdrow)) { //Asha: Fix for ticket #4432 + foreach($thirdrow as $ind => $val) + { + if(strlen($val) > 30) + $thirdrow[$ind] = substr(to_html($val),0,30)." .........."; + else + $thirdrow[$ind] = to_html($val); + } + } +} + +$field_map = $outlook_contacts_field_map; + +$mapping_file = new ImportMap(); +$saved_map_lists = $mapping_file->getSavedMappingsList($_REQUEST['return_module']); +$map_list_combo = ''; +//This link is Delete link for the selected mapping +$map_list_combo .= "   "; +$smarty->assign("SAVED_MAP_LISTS",$map_list_combo); + + +if ( count($mapping_arr) > 0){ + $field_map = &$mapping_arr; +}else if ($_REQUEST['source'] == 'other'){ + if ($_REQUEST['module'] == 'Contacts'){ + $field_map = $outlook_contacts_field_map; + }else if ($_REQUEST['module'] == 'Accounts'){ + $field_map = $outlook_accounts_field_map; + }else if ($_REQUEST['module'] == 'Potentials'){ + $field_map = $salesforce_opportunities_field_map; + } +} + +$add_one = 1; +$start_at = 0; + +if($has_header){ + $add_one = 0; + $start_at = 1; +} + +for($row_count = $start_at; $row_count < count($rows); $row_count++){ + $smarty->assign("ROWCOUNT", $row_count + $add_one); +} + +$list_string_key = strtolower($_REQUEST['module']); +$list_string_key .= "_import_fields"; + +//Now we are getting the import fields from DB instead of hard coded array $mod_list_strings +$translated_column_fields = getImportFieldsList($_REQUEST['module']);//$mod_list_strings[$list_string_key]; + +$cnt=1; +for($field_count = 0; $field_count < $ret_field_count; $field_count++){ + + $smarty->assign("COLCOUNT", $field_count + 1); + $suggest = ""; + + if($_REQUEST['module']=='Accounts'){ + $tablename='account'; + $focus1=new Accounts(); + } + if($_REQUEST['module']=='Contacts'){ + $tablename='contactdetails'; + $focus1=new Contacts(); + } + if($_REQUEST['module']=='Leads'){ + $tablename='leaddetails'; + $focus1=new Leads(); + } + if($_REQUEST['module']=='Potentials'){ + $tablename='potential'; + $focus1=new Potentials(); + } + if($_REQUEST['module']=='Products'){ + $tablename='products'; + $focus1=new Products(); + } + if($_REQUEST['module']=='HelpDesk'){ + $tablename='troubletickets'; + $focus1=new HelpDesk(); + } + if($_REQUEST['module']=='Vendors'){ + $tablename='Vendors'; + $focus1=new Vendors(); + } + + // vtlib customization: Hook to provide generic import for other modules + if($_REQUEST['module']) { + $focus1 = CRMEntity::getInstance($_REQUEST['module']); + $tablename = $focus->table_name; + } + // END + + $smarty->assign("FIRSTROW",$firstrow); + $smarty->assign("SECONDROW",$secondrow); + $smarty->assign("THIRDROW",$thirdrow); + $smarty_array[$field_count + 1] = getFieldSelect( $focus->importable_fields, + $field_count, + $focus->required_fields, + $suggest, + $translated_column_fields, + $tablename + ); + + $pos = 0; + foreach($rows as $row ){ + if( isset($row[$field_count]) && $row[$field_count] != ''){ + $smarty->assign("CELL",htmlspecialchars($row[$field_count])); + } + $cnt++; + } +} +@session_unregister('import_delimiter'); +@session_unregister('import_has_header'); +@session_unregister('import_firstrow'); +@session_unregister('import_field_map'); +@session_unregister('import_module_object_column_fields'); +@session_unregister('import_module_field_count'); +@session_unregister('import_module_object_required_fields'); +@session_unregister('import_module_translated_column_fields'); +$_SESSION['import_delimiter'] = $delimiter; +$_SESSION['import_has_header'] = $has_header; +$_SESSION['import_firstrow'] = $firstrow; +$_SESSION['import_field_map'] = $field_map; +$_SESSION['import_module_object_column_fields'] = $focus->importable_fields; +$_SESSION['import_module_field_count'] = $field_count; +$_SESSION['import_module_object_required_fields'] = $focus1->required_fields; +$_SESSION['import_module_translated_column_fields'] = $translated_column_fields; + +$smarty->assign("SELECTFIELD",$smarty_array); +$smarty->assign("ROW", $row); + +$module_key = "LBL_".strtoupper($_REQUEST['module'])."_NOTE_"; + +for ($i = 1;isset($mod_strings[$module_key.$i]);$i++){ + $smarty->assign("NOTETEXT", $mod_strings[$module_key.$i]); +} + +if($has_header){ + $smarty->assign("HAS_HEADER", 'on'); +}else{ + $smarty->assign("HAS_HEADER", 'off'); +} + +$smarty->assign("AVALABLE_FIELDS", getMergeFields($module,"available_fields")); +$smarty->assign("FIELDS_TO_MERGE", getMergeFields($module,"fileds_to_merge")); +if(isPermitted($module,'DuplicatesHandling','') == 'yes'){ + $smarty->assign("DUPLICATESHANDLING", 'DuplicatesHandling'); +} + +$smarty->assign("MODULE", vtlib_purify($_REQUEST['module'])); +$smarty->assign("MODULELABEL", getTranslatedString($_REQUEST['module'],$_REQUEST['module'])); +$parenttab = getParentTab(); +$smarty->assign('CATEGORY' , $parenttab); +$_SESSION['import_parenttab'] = $parenttab; +$smarty->assign("JAVASCRIPT2", get_readonly_js() ); + +$smarty->display('ImportStep2.tpl'); + +?> + diff --git a/oss/vtiger/trunk/modules/Import/ImportStep3.php b/oss/vtiger/trunk/modules/Import/ImportStep3.php new file mode 100644 index 00000000..702d4ba1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportStep3.php @@ -0,0 +1,317 @@ +println("IMP :".$str); +} + +function implode_assoc($inner_delim, $outer_delim, $array){ + $output = array(); + foreach( $array as $key => $item ){ + $output[] = $key . $inner_delim . $item; + } + return implode($outer_delim, $output); +} + +global $mod_strings; +global $app_list_strings; +global $app_strings; +global $current_user; +global $import_file_name; +global $theme; +global $upload_maxsize; +global $site_URL; + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Upload Step 3"); + +include("include/saveMergeCriteria.php"); + +$delimiter = ','; +// file handle +$count = 0; +$error = ""; +$col_pos_to_field = array(); +$header_to_field = array(); +$field_to_pos = array(); +$focus = 0; +$current_bean_type = ""; +$id_exists_count = 0; +$broken_ids = 0; + +$delimiter = $_SESSION['import_delimiter']; + +$has_header = 0; + +if(isset( $_REQUEST['has_header']) && $_REQUEST['has_header'] == 'on'){ + $has_header = 1; +} + +if($_REQUEST['modulename'] != ''){ + $_REQUEST['module'] = vtlib_purify($_REQUEST['modulename']); +} + +$import_object_array = Array( + "Leads"=>"ImportLead", + "Accounts"=>"ImportAccount", + "Contacts"=>"ImportContact", + "Potentials"=>"ImportOpportunity", + "Products"=>"ImportProduct", + "HelpDesk"=>"ImportTicket", + "Vendors"=>"ImportVendors" + ); + +if(isset($_REQUEST['module']) && $_REQUEST['module'] != ''){ + $current_bean_type = $import_object_array[$_REQUEST['module']]; + // vtlib customization: Hook added to enable import for un-mapped modules + $module = $_REQUEST['module']; + if($current_bean_type == null) { + checkFileAccess("modules/$module/$module.php"); + require_once("modules/$module/$module.php"); + $current_bean_type = $module; + $callInitImport = true; + } + // END +}else{ + $current_bean_type = "ImportContact"; +} + +$focus = new $current_bean_type(); +// vtlib customization: Call the import initializer +if($callInitImport) $focus->initImport($module); +// END + +//Constructing the custom vtiger_field Array +require_once('include/CustomFieldUtil.php'); +$custFldArray = getCustomFieldArray($_REQUEST['module']); +p("IMP 3: custFldArray"); +p($custFldArray); + +//Initializing an empty Array to store the custom vtiger_field Column Name and Value +$resCustFldArray = Array(); + +p("Getting from request"); +// loop through all request variables +foreach ($_REQUEST as $name=>$value){ + p("name=".$name." value=".$value); + // only look for var names that start with "colnum" + if ( strncasecmp( $name, "colnum", 6) != 0 ){ + continue; + } + if ($value == "-1"){ + continue; + } + + $user_field = $value; + $pos = substr($name,6); + + if ( isset( $field_to_pos[$user_field]) ){ + show_error_import($mod_strings['LBL_ERROR_MULTIPLE']); + exit; + } + + p("user_field=".$user_field." if=".$focus->importable_fields[$user_field]); + + if ( isset( $focus->importable_fields[$user_field] ) || isset( $custFldArray[$user_field] )){ + p("user_field SET=".$user_field); + $field_to_pos[$user_field] = $pos; + $col_pos_to_field[$pos] = $user_field; + } +} + +p("field_to_pos"); +$adb->println($field_to_pos); +p("col_pos_to_field"); +$adb->println($col_pos_to_field); + +$max_lines = -1; +$ret_value = 0; + +if(isset($_REQUEST['tmp_file'])) { + $_SESSION['tmp_file'] = vtlib_purify($_REQUEST['tmp_file']); +} else { + $_REQUEST['tmp_file'] = vtlib_purify($_SESSION['tmp_file']); +} +// End + +if ($_REQUEST['source'] == 'act'){ + $ret_value = parse_import_act($_REQUEST['tmp_file'],$delimiter,$max_lines,$has_header); +}else{ + $ret_value = parse_import($_REQUEST['tmp_file'],$delimiter,$max_lines,$has_header); +} + +$datarows = $ret_value['rows']; + +$ret_field_count = $ret_value['field_count']; + +//we have to get all picklist entries and add with the corresponding picklist table +if(isset($datarows) && is_array($datarows)){ + //This file will be included only once at the first time. Will not be included when we redirect from ImportSave + include("modules/Import/picklist_addition.php"); +} + +$saved_ids = array(); + +$firstrow = 0; + +if (! isset($datarows)){ + $error = $mod_strings['LBL_FILE_ALREADY_BEEN_OR']; + $datarows = array(); +} + +if ($has_header == 1){ + $firstrow = array_shift($datarows); +} + +//Mark the last imported records as deleted which are imported by the current user in vtiger_users_last_import vtiger_table +if(!isset($_REQUEST['startval'])){ + $seedUsersLastImport = new UsersLastImport(); + $seedUsersLastImport->mark_deleted_by_user_id($current_user->id); +} +$skip_required_count = 0; + +p("processing started ret_field_count=".$ret_field_count); +$adb->println($datarows); + +$error = ''; +$focus = new $current_bean_type(); +$focus->initRequiredFields($module); + +// SAVE MAPPING IF REQUESTED +if(isset($_REQUEST['save_map']) && $_REQUEST['save_map'] == 'on' && isset($_REQUEST['save_map_as']) && $_REQUEST['save_map_as'] != ''){ + p("save map"); + $serialized_mapping = ''; + + if( $has_header){ + foreach($col_pos_to_field as $pos=>$field_name){ + if ( isset($firstrow[$pos]) && isset( $field_name)){ + $header_to_field[ $firstrow[$pos] ] = $field_name; + } + } + $serialized_mapping = implode_assoc("=","&",$header_to_field); + }else{ + $serialized_mapping = implode_assoc("=","&",$col_pos_to_field); + } + + $mapping_file_name = $_REQUEST['save_map_as']; + $mapping_file = new ImportMap(); + + $result = $mapping_file->save_map( $current_user->id, + $mapping_file_name, + $_REQUEST['module'], + $has_header, + $serialized_mapping ); + + $adb->println("Save map done"); + $adb->println($result); +} +//save map - ends + +if(isset($_SESSION['totalrows']) && $_SESSION['totalrows'] != ''){ + $xrows = $_SESSION['totalrows']; +}else{ + $xrows = $datarows; +} +if(isset($_SESSION['return_field_count'])){ + $ret_field_count = $_SESSION['return_field_count']; +} +if(isset($_SESSION['column_position_to_field'])){ + $col_pos_to_field = $_SESSION['column_position_to_field']; +} +if($xrows != ''){ + $datarows = $xrows; +} +if($_REQUEST['skipped_record_count'] != ''){ + $skipped_record_count = vtlib_purify($_REQUEST['skipped_record_count']); +}else{ + $_REQUEST['skipped_record_count'] = 0; +} + +if($_REQUEST['noofrows'] != ''){ + $totalnoofrows = vtlib_purify($_REQUEST['noofrows']); +}else{ + $totalnoofrows = count($datarows); +} + +$loopcount = ($totalnoofrows/$RECORDCOUNT)+1; + +if($_REQUEST['startval'] != ''){ + $START = vtlib_purify($_REQUEST['startval']); +}else{ + $START = vtlib_purify($_SESSION['startval']); +} + +if($_REQUEST['recordcount'] != ''){ + $RECORDCOUNT = vtlib_purify($_REQUEST['recordcount']); +}else{ + $RECORDCOUNT = vtlib_purify($_SESSION['recordcount']); +} + +if(($START+$RECORDCOUNT) > $totalnoofrows){ + $RECORDCOUNT = $totalnoofrows - $START; +} + +$focus->initImportableFields($module); +if($totalnoofrows > $RECORDCOUNT && $START < $totalnoofrows){ + $rows1 = Array(); + for($j=$START;$j<$START+$RECORDCOUNT;$j++){ + $rows1[] = $datarows[$j]; + } + + $res = InsertImportRecords($datarows,$rows1,$focus,$ret_field_count,$col_pos_to_field,$START,$RECORDCOUNT,vtlib_purify($_REQUEST['module']),$totalnoofrows,$skipped_record_count); + if($START != 0){ + echo ''.$res.''; + } + + $count = vtlib_purify($_REQUEST['count']); +}else{ + if($START == 0){ + $res = InsertImportRecords($datarows,$datarows,$focus,$ret_field_count,$col_pos_to_field,$START,$totalnoofrows,vtlib_purify($_REQUEST['module']),$totalnoofrows,$skipped_record_count); + } +} + +//Display the imported records message +echo "
    ".$_SESSION['import_display_message']."
    "; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportSteplast.php b/oss/vtiger/trunk/modules/Import/ImportSteplast.php new file mode 100644 index 00000000..578e8032 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportSteplast.php @@ -0,0 +1,305 @@ +info("Import Step last"); + +$parenttab = getParenttab(); +//This Buttons_List1.tpl is is called to display the add, search, import and export buttons ie., second level tabs +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("IMP", $import_mod_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +$smarty->assign("MODULE", vtlib_purify($_REQUEST['modulename'])); +$smarty->assign("SINGLE_MOD", vtlib_purify($_REQUEST['modulename'])); +$smarty->assign("CATEGORY", vtlib_purify($_SESSION['import_parenttab'])); +//@session_unregister("import_parenttab"); +if($req_module != 'Accounts' || $req_module != 'Contacts' || $req_module != 'Products' || $req_module != 'Leads' || $req_module != 'HelpDesk' || $req_module != 'Potentials' || $req_module != 'Vendors' ) +{ + $smarty->display("Buttons_List1.tpl"); +} + +if ( isset($_REQUEST['message'])) +{ + ?> +
    + + + + + + + + + + + + + + + +
    + +
     
    + +   + +   + + +
    + +


    + + + + +
    + + + + + + + + + + + + +
    + + + + +
    +
    + + + + + + + + +
    + "; + $return_module=vtlib_purify($_REQUEST['modulename']); + + $ret_arr=getDuplicateRecordsArr($req_module); + $fld_values=$ret_arr[0]; + $total_num_group=count($fld_values); + $fld_name=$ret_arr[1]; + + $smarty->assign("MODULE",$req_module); + $smarty->assign("MODULELABEL",getTranslatedString($req_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); + $smarty->assign("MOD", return_module_language($current_language,'Contacts')); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("APP", $app_strings); + $smarty->assign("CMOD", $mod_strings); + $smarty->assign("MODE",'view'); + $smarty->assign("NAVIGATION",$ret_arr["navigation"]);//Added for page navigation + if(isPermitted($req_module,'Delete','') == 'yes') + $button_del = $app_strings[LBL_MASS_DELETE]; + $smarty->assign("DELETE",$button_del); + if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("FindDuplicateAjax.tpl"); + else + $smarty->display('FindDuplicateDisplay.tpl'); +} +else +{ + echo "

    "; + $currentModule = "Import"; + global $limit; + global $list_max_entries_per_page; + $implict_account = false; + $import_modules_array = Array( + "Leads"=>"Leads", + "Accounts"=>"Accounts", + "Contacts"=>"Contacts", + "Potentials"=>"Potentials", + "Products"=>"Products", + "HelpDesk"=>"ImportTicket", + "Vendors"=>"ImportVendors" + ); + + // vtlib customization: Hook provide to include custom modules + $module = $_REQUEST['modulename']; + checkFileAccess("modules/$module/$module.php"); + require_once("modules/$module/$module.php"); + $import_modules_array[$module] = $module; + // END + + foreach($import_modules_array as $module_name => $object_name) + { + $seedUsersLastImport = new UsersLastImport(); + $seedUsersLastImport->bean_type = $module_name; + $list_query = $seedUsersLastImport->create_list_query($o,$w); + $current_module_strings = return_module_language($current_language, $module_name); + + $object = new $object_name(); + $seedUsersLastImport->list_fields = $object->list_fields; + + $list_result = $adb->query($list_query); + //Retreiving the no of rows + $noofrows = $adb->num_rows($list_result); + + if($noofrows>=1) + { + if($module_name != 'Accounts') + { + $implict_account=true; + } + + if($module_name == 'Accounts' && $implict_account==true) + $display_header_msg = "Newly created Accounts"; + else + $display_header_msg = "".$mod_strings['LBL_LAST_IMPORTED']." ".$app_strings[$module_name].""; + + //Display the Header Message + echo " + + + + +
    + ".$mod_strings['LBL_LAST_IMPORTED']." ".$app_strings[$module_name]." +
    + "; + + $smarty = new vtigerCRM_Smarty; + + $smarty->assign("MOD", $mod_strings); + $smarty->assign("APP", $app_strings); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE",$module_name); + $smarty->assign("MODULELABEL",getTranslatedString($module_name,$module_name)); + $smarty->assign("SINGLE_MOD",$module_name); + $smarty->assign("SHOW_MASS_SELECT",'false'); + + //Retreiving the start value from request + if($module_name == $_REQUEST['nav_module'] && isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); + } else { + $start = 1; + } + + $info_message='&recordcount='.vtlib_purify($_REQUEST['recordcount']).'&noofrows='.vtlib_purify($_REQUEST['noofrows']).'&message='.vtlib_purify($_REQUEST['message']).'&skipped_record_count='.vtlib_purify($_REQUEST['skipped_record_count']); + $url_string = '&modulename='.vtlib_purify($_REQUEST['modulename']).'&nav_module='.$module_name.$info_message; + $viewid = ''; + + //Retreive the Navigation array + $navigation_array = getNavigationValues($start, $noofrows, $list_max_entries_per_page); + $navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Import","ImportSteplast",$viewid); + + //Retreive the List View Header and Entries + $listview_header = getListViewHeader($object,$module_name); + $listview_entries = getListViewEntries($object,$module_name,$list_result,$navigation_array,"","","EditView","Delete",""); + //commented to remove navigation buttons from import list view + //$smarty->assign("NAVIGATION", $navigationOutput); + $smarty->assign("HIDE_CUSTOM_LINKS", 1);//Added to hide the CustomView links in imported records ListView + + // Remove all the links for the list view header as they do not work in this page. + for($i=0;$iassign("LISTHEADER", $listview_header); + $smarty->assign("LISTENTITY", $listview_entries); + + $smarty->display("ListViewEntries.tpl"); + echo "
    "; + } + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportStepundo.php b/oss/vtiger/trunk/modules/Import/ImportStepundo.php new file mode 100644 index 00000000..fce7afe8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportStepundo.php @@ -0,0 +1,129 @@ +info("Import Undo"); +$last_import = new UsersLastImport(); +$ret_value = $last_import->undo($current_user->id); + +// vtlib customization: Invoke undo import function of the module. +$module = $_REQUEST['module']; +$undo_focus = CRMEntity::getInstance($module); +if(method_exists($undo_focus, 'undo_import')) { + $ret_value += $undo_focus->undo_import($module, $current_user->id); +} +// END + +?> + +
    + + + + + + + + + + + + + + + + +
     
    + +   + +   + + +
    +
    + + " . $mod_strings['LBL_SUCCESS']."" ?>

    + + +
    + + +
    +
    +
    +
    + + + + + + + + +
    +
    + diff --git a/oss/vtiger/trunk/modules/Import/ImportTicket.php b/oss/vtiger/trunk/modules/Import/ImportTicket.php new file mode 100644 index 00000000..dfc0353c --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportTicket.php @@ -0,0 +1,136 @@ +column_fields["assigned_user_id"]; + $this->db->println("assign_user ".$ass_user." cur_user=".$current_user->id); + + if( $ass_user != $current_user->id) + { + $this->db->println("searching and assigning ".$ass_user); + + $result = $this->db->pquery("select id from vtiger_users where id = ? union select groupid as id from vtiger_groups where groupid = ?",array($ass_user, $ass_user)); + if($this->db->num_rows($result)!=1) + { + $this->db->println("not exact records setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + else + { + + $row = $this->db->fetchByAssoc($result, -1, false); + if (isset($row['id']) && $row['id'] != -1) + { + $this->db->println("setting id as ".$row['id']); + $this->column_fields["assigned_user_id"] = $row['id']; + } + else + { + $this->db->println("setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + } + } + } + function add_product() + { + global $adb,$imported_ids,$current_user; + + $pro_name = $this->column_fields['product_id']; + if((! isset($pro_name) || $pro_name == '') ) + return; + + //check if it already exists + $focus = new Products(); + $query = ''; + + //Modified to remove the spaces at first and last in vtiger_product name + $pro_name = trim($pro_name); + + //Modified the query to get the available product only ie., which is not deleted + $query = "select vtiger_products.* ,vtiger_crmentity.deleted from vtiger_products,vtiger_crmentity WHERE productname=? and vtiger_crmentity.crmid = vtiger_products.productid and vtiger_crmentity.deleted=0"; + $result = $adb->pquery($query, array($pro_name)); + $row = $this->db->fetchByAssoc($result, -1, false); + $adb->println($row); + + // we found a row with that id + if (isset($row['productid']) && $row['productid'] != -1) + $focus->id = $row['productid']; + + $this->column_fields["product_id"] = $focus->id; + } + function empty_relatedto() + { + global $adb; + $parent_name = $this->column_fields["parent_id"]; + if($parent_name == '' || $parent_name == NULL) + $parent_id = 0; + else + { //get the account + $relatedTo = explode(':',$parent_name); + $parent_module = $relatedTo[0]; $parent_module = trim($parent_module," "); + $parent_name = $relatedTo[3]; $parent_name = trim($parent_name," "); + $num_rows = 0; + if($parent_module == 'Contacts') + { + $query ="select crmid from vtiger_contactdetails, vtiger_crmentity WHERE concat(lastname,' ',firstname)=? and vtiger_crmentity.crmid =vtiger_contactdetails.contactid and vtiger_crmentity.deleted=0"; + $result = $adb->pquery($query, array($parent_name)); + $num_rows=$adb->num_rows($result); + } + else if($parent_module == 'Accounts') + { + $query = "select crmid from vtiger_account, vtiger_crmentity WHERE accountname=? and vtiger_crmentity.crmid =vtiger_account.accountid and vtiger_crmentity.deleted=0"; + $result = $adb->pquery($query, array($parent_name)); + $num_rows = $adb->num_rows($result); + } + else $num_rows=0; + if($num_rows == 0) $parent_id = 0; + else $parent_id = $adb->query_result($result,0,"crmid"); + } + $this->column_fields['parent_id'] = $parent_id; + } + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportTicket() { + parent::HelpDesk(); + $this->log = LoggerManager::getLogger('import_ticket'); + $this->db = PearDatabase::getInstance(); + $this->db->println("IMP ImportTicket"); + $this->initImportableFields("HelpDesk"); + $this->db->println($this->importable_fields); + } + + // Module Sequence Numbering + function modseq_number() { + $this->column_fields['ticket_no'] = ''; + } + // END + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/ImportVendors.php b/oss/vtiger/trunk/modules/Import/ImportVendors.php new file mode 100644 index 00000000..b3f9d1a8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/ImportVendors.php @@ -0,0 +1,80 @@ +column_fields["assigned_user_id"]; + $this->db->println("assign_user ".$ass_user." cur_user=".$current_user->id); + + if( $ass_user != $current_user->id) + { + $this->db->println("searching and assigning ".$ass_user); + + $result = $this->db->query("select id from vtiger_users where id = '".$ass_user."'"); + if($this->db->num_rows($result)!=1) + { + $this->db->println("not exact records setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + else + { + + $row = $this->db->fetchByAssoc($result, -1, false); + if (isset($row['id']) && $row['id'] != -1) + { + $this->db->println("setting id as ".$row['id']); + $this->column_fields["assigned_user_id"] = $row['id']; + } + else + { + $this->db->println("setting current userid"); + $this->column_fields["assigned_user_id"] = $current_user->id; + } + } + } + } + + /** Constructor which will set the importable_fields as $this->importable_fields[$key]=1 in this object where key is the fieldname in the field table + */ + function ImportVendors() { + parent::Vendors(); + $this->log = LoggerManager::getLogger('import_vendors'); + $this->db = PearDatabase::getInstance(); + $this->db->println("IMP ImportVendors"); + $this->initImportableFields("Vendors"); + $this->db->println($this->importable_fields); + } + + //Module Sequence Numbering + function modseq_number() { + $this->column_fields['vendor_no'] = ''; + } + // END + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/UsersLastImport.php b/oss/vtiger/trunk/modules/Import/UsersLastImport.php new file mode 100644 index 00000000..d2cc33b4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/UsersLastImport.php @@ -0,0 +1,453 @@ +log = LoggerManager::getLogger('UsersLastImport'); + $this->db = PearDatabase::getInstance(); + } + + /** function used to delete the old entries for this user + * @param int $user_id - user id to whom's last imported records to delete + * @return void + */ + function mark_deleted_by_user_id($user_id) + { + $query = "DELETE FROM $this->table_name where assigned_user_id=?"; + $this->db->pquery($query,array($user_id),true,"Error deleting last imported records: "); + } + + /** function used to get the list query of the imported records + * @param reference &$order_by - reference of the variable order_by to add with the query + * @param reference &$where - where condition to add with the query + * @return string $query - return the list query to get the imported records list + */ + function create_list_query(&$order_by, &$where) + { + global $current_user; + $query = ''; + + $this->db->println("create list bean_type = ".$this->bean_type." where = ".$where); + + if ($this->bean_type == 'Contacts') + { + $query = "SELECT distinct crmid, + vtiger_account.accountname as accountname, + vtiger_contactdetails.contactid, + vtiger_contactdetails.accountid, + vtiger_contactdetails.yahooid, + vtiger_contactdetails.firstname, + vtiger_contactdetails.lastname, + vtiger_contactdetails.phone, + vtiger_contactdetails.title, + vtiger_contactdetails.email, + vtiger_users.id as assigned_user_id, + smownerid, + case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name + FROM vtiger_contactdetails + left join vtiger_users_last_import on vtiger_users_last_import.bean_id=vtiger_contactdetails.contactid + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_contactdetails.contactid + LEFT JOIN vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id + LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid + LEFT JOIN vtiger_account ON vtiger_account.accountid=vtiger_contactdetails.accountid + WHERE vtiger_users_last_import.assigned_user_id= '{$current_user->id}' + AND vtiger_users_last_import.bean_type='Contacts' + AND vtiger_users_last_import.deleted=0 AND vtiger_crmentity.deleted=0"; + + } + else if ($this->bean_type == 'Accounts') + { + $query = "SELECT distinct vtiger_account.*, vtiger_accountbillads.bill_city, + case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + crmid, smownerid + FROM vtiger_account + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid + inner join vtiger_accountbillads on vtiger_crmentity.crmid=vtiger_accountbillads.accountaddressid + left join vtiger_users_last_import on vtiger_users_last_import.bean_id=vtiger_crmentity.crmid + left join vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id + 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='Accounts' + AND vtiger_users_last_import.deleted=0 + AND vtiger_crmentity.deleted=0"; + }else if ($this->bean_type == 'Potentials'){ + $query = "SELECT distinct vtiger_account.accountid accountid, vtiger_account.accountname accountname, + case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, vtiger_crmentity.crmid, smownerid, + vtiger_potential.* + FROM vtiger_potential + inner join vtiger_crmentity + on vtiger_crmentity.crmid=vtiger_potential.potentialid + left join vtiger_account + on vtiger_account.accountid=vtiger_potential.related_to + left join vtiger_users + ON vtiger_crmentity.smownerid=vtiger_users.id + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users_last_import + on vtiger_users_last_import.bean_id=vtiger_crmentity.crmid + where vtiger_users_last_import.assigned_user_id='{$current_user->id}' + AND vtiger_users_last_import.bean_type='Potentials' + AND vtiger_users_last_import.bean_id=vtiger_crmentity.crmid + AND vtiger_users_last_import.deleted=0 + AND vtiger_crmentity.deleted=0"; + }else if($this->bean_type == 'Leads'){ + $query = "SELECT distinct vtiger_leaddetails.*, vtiger_crmentity.crmid, vtiger_leadaddress.phone,vtiger_leadsubdetails.website, + case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + smownerid + FROM vtiger_leaddetails + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid + inner join vtiger_leadaddress on vtiger_crmentity.crmid=vtiger_leadaddress.leadaddressid + inner join vtiger_leadsubdetails on vtiger_crmentity.crmid=vtiger_leadsubdetails.leadsubscriptionid + left join vtiger_users_last_import on vtiger_users_last_import.bean_id=vtiger_crmentity.crmid + left join vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id + 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='Leads' + AND vtiger_users_last_import.deleted=0 + AND vtiger_crmentity.deleted=0"; + } + + //Pavani: Query to retrieve trouble tickets, vendors data from database + else if($this->bean_type == 'HelpDesk') + { + $query = "SELECT distinct vtiger_troubletickets.*, vtiger_crmentity.crmid, + case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + smownerid + FROM vtiger_troubletickets + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid + left join vtiger_users_last_import on vtiger_users_last_import.bean_id=vtiger_crmentity.crmid + left join vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id + 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='HelpDesk' + AND vtiger_users_last_import.deleted=0 + AND vtiger_crmentity.deleted=0"; + } + + else if($this->bean_type == 'Vendors') + { + $query = "SELECT distinct vtiger_vendor.*, vtiger_crmentity.crmid, + case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end as user_name, + smownerid + FROM vtiger_vendor + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_vendor.vendorid + left join vtiger_users_last_import on vtiger_users_last_import.bean_id=vtiger_crmentity.crmid + left join vtiger_users ON vtiger_crmentity.smownerid=vtiger_users.id + 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='Vendors' + AND vtiger_users_last_import.deleted=0 + AND vtiger_crmentity.deleted=0"; + } + //pavani...end + + else if($this->bean_type == 'Products') + { + $query = "SELECT vtiger_crmentity.crmid, vtiger_products.*, vtiger_productcf.* + FROM vtiger_products + INNER JOIN vtiger_crmentity + ON vtiger_crmentity.crmid = vtiger_products.productid + INNER JOIN vtiger_productcf + ON vtiger_products.productid = vtiger_productcf.productid + LEFT JOIN vtiger_vendor + ON vtiger_vendor.vendorid = vtiger_products.vendor_id + 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_products.handler + WHERE + vtiger_users_last_import.assigned_user_id= '{$current_user->id}' + AND vtiger_users_last_import.bean_type='Products' + AND vtiger_users_last_import.deleted=0 + AND vtiger_crmentity.deleted = 0"; + + } + // vtlib customization: Hook for getting the query from the module class itself. + else { + require_once("modules/$this->bean_type/$this->bean_type.php"); + $bean_focus = new $this->bean_type(); + $query = $bean_focus->create_import_query($this->bean_type); + } + // END + + return $query; + + } + + /* + function list_view_parse_additional_sections(&$list_form) + { + if ($this->bean_type == "Contacts") + { + if( isset($this->yahoo_id) && $this->yahoo_id != '') + { + $list_form->parse("main.row.yahoo_id"); + } + else + { + $list_form->parse("main.row.no_yahoo_id"); + } + } + return $list_form; + + } + */ + + /** function used to delete (update deleted=1 in crmentity table) the last imported records of the current user + * @param int $user_id - user id, whose last imported records want to be deleted + * @return int $count - return the number of total deleted records (contacts, accounts, opportunities, leads and products) + */ + function undo($user_id) + { + $count = 0; + + $count += $this->undo_contacts($user_id); + $count += $this->undo_accounts($user_id); + $count += $this->undo_opportunities($user_id); + $count += $this->undo_leads($user_id); + $count += $this->undo_products($user_id); + $count += $this->undo_HelpDesk($user_id); + $count += $this->undo_Vendors($user_id); + return $count; + } + + /** function used to delete (update deleted=1 in crmentity table) the last imported contacts of the current user + * @param int $user_id - user id, whose last imported contacts want to be deleted + * @return int $count - return the number of deleted contacts + */ + function undo_contacts($user_id) + { + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='Contacts' AND deleted=0"; + $this->log->info($query1); + $result1 = $this->db->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid=?"; + $this->log->info($query2); + $result2 = $this->db->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error()); + + $count++; + + } + return $count; + } + + /** function used to delete (update deleted=1 in crmentity table) the last imported leads of the current user + * @param int $user_id - user id, whose last imported leads want to be deleted + * @return int $count - return the number of deleted leads + */ + function undo_leads($user_id) + { + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='Leads' AND deleted=0"; + $this->log->info($query1); + $result1 = $this->db->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid=?"; + $this->log->info($query2); + $result2 = $this->db->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error()); + + $count++; + + } + return $count; + } + //Pavani: Function to cancel latest import of trouble tickets and vendors of the particular user + /** function used to delete (update deleted=1 in crmentity table) the last imported tickets of the current user + * @param int $user_id - user id, whose last imported tickets want to be deleted + * @return int $count - return the number of deleted tickets + */ + function undo_HelpDesk($user_id) + { + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id='$user_id' AND bean_type='HelpDesk' AND deleted=0"; + + $this->log->info($query1); + + $result1 = $this->db->query($query1) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid='{$row1['bean_id']}'"; + + $this->log->info($query2); + + $result2 = $this->db->query($query2) or die("Error undoing last import: ".mysql_error()); + + $count++; + + } + return $count; + } + + /** function used to delete (update deleted=1 in crmentity table) the last imported vendors of the current user + * @param int $user_id - user id, whose last imported vendors want to be deleted + * @return int $count - return the number of deleted vendors + */ + function undo_Vendors($user_id) + { + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id='$user_id' AND bean_type='Vendors' AND deleted=0"; + + $this->log->info($query1); + + $result1 = $this->db->query($query1) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid='{$row1['bean_id']}'"; + + $this->log->info($query2); + + $result2 = $this->db->query($query2) or die("Error undoing last import: ".mysql_error()); + + $count++; + + } + return $count; + } + + /** function used to delete (update deleted=1 in crmentity table) the last imported accounts of the current user + * @param int $user_id - user id, whose last imported accounts want to be deleted + * @return int $count - return the number of deleted accounts + */ + function undo_accounts($user_id) + { + // this should just be a loop foreach module type + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='Accounts' AND deleted=0"; + $this->log->info($query1); + $result1 = $this->db->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid=?"; + $this->log->info($query2); + $result2 = $this->db->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error()); + + $count++; + + } + return $count; + } + + /** function used to delete (update deleted=1 in crmentity table) the last imported potentials of the current user + * @param int $user_id - user id, whose last imported potentials want to be deleted + * @return int $count - return the number of deleted potentials + */ + function undo_opportunities($user_id) + { + // this should just be a loop foreach module type + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='Potentials' AND deleted=0"; + + $this->log->info($query1); + + $result1 = $this->db->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid=?"; + $this->log->info($query2); + $result2 = $this->db->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error()); + + $count++; + + } + return $count; + } + + /** function used to delete (update deleted=1 in crmentity table) the last imported products of the current user + * @param int $user_id - user id, whose last imported products want to be deleted + * @return int $count - return the number of deleted products + */ + function undo_products($user_id) + { + $count = 0; + $query1 = "select bean_id from vtiger_users_last_import where assigned_user_id=? AND bean_type='Products' AND deleted=0"; + $this->log->info($query1); + $result1 = $this->db->pquery($query1, array($user_id)) or die("Error getting last import for undo: ".mysql_error()); + + while ( $row1 = $this->db->fetchByAssoc($result1)) + { + $query2 = "update vtiger_crmentity set deleted=1 where crmid=?"; + $this->log->info($query2); + $result2 = $this->db->pquery($query2, array($row1['bean_id'])) or die("Error undoing last import: ".mysql_error()); + + $count++; + } + return $count; + } + +} + + +?> diff --git a/oss/vtiger/trunk/modules/Import/error.php b/oss/vtiger/trunk/modules/Import/error.php new file mode 100644 index 00000000..e480fabb --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/error.php @@ -0,0 +1,68 @@ +info("Upload Error"); + + $smarty = new vtigerCRM_Smarty; + $smarty->assign("MOD", $mod_strings); + $smarty->assign("APP", $app_strings); + + + 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'])); + + $smarty->assign("THEME", $theme); + + $category = getParenttab(); + $smarty->assign("CATEGORY", $category); + + $smarty->assign("IMAGE_PATH", $image_path); + $smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + + $smarty->assign("MODULE", vtlib_purify($_REQUEST['module'])); + $smarty->assign("MESSAGE", $message); + + $smarty->display('Importerror.tpl'); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/index.php b/oss/vtiger/trunk/modules/Import/index.php new file mode 100644 index 00000000..42faee04 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/index.php @@ -0,0 +1,252 @@ +"salutation", +// SPECIAL FIELD: +"Full Name"=>"full_name", +"Company"=>"company", +// END +"First Name"=>"first_name", +"Last Name"=>"last_name", +"Job Title"=>"title", +"Department"=>"department", +"Birthday"=>"birthdate", +"Home Phone"=>"phone_home", +"Mobile Phone"=>"phone_mobile", +"Business Phone"=>"phone_work", +"Other Phone"=>"phone_other", +"Business Fax"=>"phone_fax", +"E-mail Address"=>"email1", +"E-mail 2"=>"email2", +"Assistant's Name"=>"assistant", +"Assistant's Phone"=>"assistant_phone", +"Business Street"=>"primary_address_street", +"Business City"=>"primary_address_city", +"Business State"=>"primary_address_state", +"Business Postal Code"=>"primary_address_postalcode", +"Business Country/Region"=>"primary_address_country", +"Home Street"=>"alt_address_street", +"Home City"=>"alt_address_city", +"Home State"=>"alt_address_state", +"Home Postal Code"=>"alt_address_postalcode", +"Home Country/Region"=>"alt_address_country", +); + + +$outlook_accounts_field_map = array( +"Company"=>"name", +"Business Street"=>"billing_address_street", +"Business City"=>"billing_address_city", +"Business State"=>"billing_address_state", +"Business Country"=>"billing_address_country", +"Business Postal Code"=>"billing_address_postalcode", +"Business Fax"=>"phone_fax", +"Company Main Phone"=>"phone_office", +"Web Page"=>"website", +//Government ID Number, +//Organizational ID Number, +); + +$act_contacts_field_map = array( +"Web Site"=>"website", +"Company"=>"account_name", +"Name Suffix"=>"salutation", +"Title"=>"title", +"First Name"=>"first_name", +"Last Name"=>"last_name", +"Address 1"=>"primary_address_street", +"Address 2"=>"primary_address_street_2", +"Address 3"=>"primary_address_street_3", +"City"=>"primary_address_city", +"State"=>"primary_address_state", +"Zip"=>"primary_address_postalcode", +"Country"=>"primary_address_country", +"Phone"=>"phone_work", +"Phone Ext-"=>"phone_work_ext", +"Mobile Phone"=>"phone_mobile", +"Alt Phone"=>"phone_other", +"Fax"=>"phone_fax", +"E-mail Login"=>"email1", +"E-mail"=>"email1", +"E-Mail 2"=>"email2", +"Assistant"=>"assistant", +"Asst. Phone"=>"assistant_phone", +"Home Address 1"=>"alt_address_street", +"Home Address 2"=>"alt_address_street_2", +"Home Address 3"=>"alt_address_street_3", +"Home City"=>"alt_address_city", +"Home State"=>"alt_address_state", +"Home Zip"=>"alt_address_postalcode", +"Home Country"=>"alt_address_country", +"Home Phone"=>"phone_home", +); + + +$act_accounts_field_map = array( +"Revenue"=>"annual_revenue", +"Number of Employees"=>"employees", +"Company"=>"name", +"Address 1"=>"billing_address_street", +"City"=>"billing_address_city", +"State"=>"billing_address_state", +"Zip Code"=>"billing_address_postalcode", +"Country"=>"billing_address_country", +"Phone"=>"phone_office", +"Fax Phone"=>"phone_fax", +"Ticker Symbol"=>"ticker_symbol", +"Web Site"=>"website", +); + +/* +"Last Activity"=>"", +"Last Modified Date"=>"", +"Created Date"=>"", +"Reports To"=>"", +"Last Stay-in-Touch Request Date"=>"", +"Last Stay-in-Touch Save Date"=>"", +*/ +$salesforce_contacts_field_map = array( +"Salutation"=>"salutation", +"Description"=>"description", +"First Name"=>"first_name", +"Last Name"=>"last_name", +"Title"=>"title", +"Department"=>"department", +"Birthdate"=>"birthdate", +"Lead Source"=>"lead_source", +"Assistant"=>"assistant", +"Asst. Phone"=>"assistant_phone", +"Contact ID"=>"id", +"Mailing Street"=>"primary_address_street", +"Mailing Address Line1"=>"primary_address_street_2", +"Mailing Address Line2"=>"primary_address_street_3", +"Mailing Address Line3"=>"primary_address_street_4", +"Mailing City"=>"primary_address_city", +"Mailing State"=>"primary_address_state", +"Mailing Zip/Postal Code"=>"primary_address_postalcod3", +"Mailing Country"=>"primary_address_country", +"Other Street"=>"alt_address_street", +"Other Address Line 1"=>"alt_address_street_2", +"Other Address Line 2"=>"alt_address_street_3", +"Other Address Line 3"=>"alt_address_street_4", +"Other City"=>"alt_address_city", +"Other State"=>"alt_address_state", +"Other Zip/Postal Code"=>"alt_address_postalcode", +"Other Country"=>"alt_address_country", +"Phone"=>"phone_work", +"Mobile"=>"phone_mobile", +"Home Phone"=>"phone_home", +"Other Phone"=>"phone_other", +"Fax"=>"phone_fax", +"Email"=>"email1", +"Email Opt Out"=>"email_opt_out", +"Do Not Call"=>"do_not_call", +"Account Name"=>"account_name", +"Account ID"=>"account_id", +); + + + + +/* +ommited vtiger_fields to map: +"Account Number"=>"", +"Account Site"=>"", +"Last Activity"=>"", +"Parent Account"=>"", +"Parent Account ID"=>"", +"Parent Account Site"=>"", +"Created Date"=>"", +"Last Modified Date"=>"", +"Billing Address Line3"=>"", +"Shipping Address Line3"=>"", +*/ +$salesforce_accounts_field_map = array( +"Account Name"=>"name", +"Annual Revenue"=>"annual_revenue", +"Type"=>"type", +"Ticker Symbol"=>"ticker_symbol", +"Rating"=>"rating", +"Industry"=>"industry", +"SIC Code"=>"sic_code", +"Ownership"=>"ownership", +"Employees"=>"employees", +"Description"=>"description", +"Account ID"=>"id", +"Billing Street"=>"billing_address_street", +"Billing Address Line1"=>"billing_address_street_2", +"Billing Address Line2"=>"billing_address_street_3", +"Billing City"=>"billing_address_city", +"Billing State"=>"billing_address_state", +"Billing Zip/Postal Code"=>"billing_address_postalcode", +"Billing Country"=>"billing_address_country", +"Shipping Street"=>"shipping_address_street", +"Shipping Address Line1"=>"shipping_address_street_2", +"Shipping Address Line2"=>"shipping_address_street_3", +"Shipping City"=>"shipping_address_city", +"Shipping State"=>"shipping_address_state", +"Shipping Zip/Postal Code"=>"shipping_address_postalcode", +"Shipping Country"=>"shipping_address_country", +"Phone"=>"phone_office", +"Fax"=>"phone_fax", +"Website"=>"website" +); + +/* +"Fiscal Quarter"=>"", +"Age"=>"", +"Expected Revenue"=>"", +*/ +$salesforce_opportunities_field_map = array( + +"Opportunity Name"=>"name" , +"Type"=>"opportunity_type", +"Lead Source"=>"lead_source", +"Amount"=>"amount", +"Created Date"=>"date_entered", +"Close Date"=>"date_closed", +"Next Step"=>"next_step", +"Stage"=>"sales_stage", +"Probability (%)"=>"probability", +"Account Name"=>"account_name" +); + +if (! isset($_REQUEST['step'] ) ) +{ + $_REQUEST['step'] = 1; +} + +$mod_list_strings = return_mod_list_strings_language($current_language,"Import"); + +checkFileAccess('modules/Import/ImportStep'. $_REQUEST['step']. '.php'); +include_once('modules/Import/ImportStep'. $_REQUEST['step']. '.php'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/language/en_us.lang.php b/oss/vtiger/trunk/modules/Import/language/en_us.lang.php new file mode 100644 index 00000000..27e45c31 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/language/en_us.lang.php @@ -0,0 +1,432 @@ +'The directory ', +'LBL_IMPORT_MODULE_NO_DIRECTORY_END'=>' does not exist or is not writable', +'LBL_IMPORT_MODULE_ERROR_NO_UPLOAD'=>'File was not uploaded successfully, try again', +'LBL_IMPORT_MODULE_ERROR_LARGE_FILE'=>'File is too large. Max:', +'LBL_IMPORT_MODULE_ERROR_LARGE_FILE_END'=>'Bytes. Change $upload_maxsize in config.php', +'LBL_MODULE_NAME'=>'Import', +'LBL_TRY_AGAIN'=>'Try Again', +'LBL_ERROR'=>'Error:', +'ERR_MULTIPLE'=>'Multiple columns have been defined with the same field name.', +'ERR_MISSING_REQUIRED_FIELDS'=>'Missing required fields:', +'ERR_SELECT_FULL_NAME'=>'You cannot select Full Name when First Name and Last Name are selected.', +'ERR_SELECT_FILE'=>'Select a file to upload.', +'LBL_SELECT_FILE'=>'Select file:', +'LBL_CUSTOM'=>'Custom', +'LBL_DONT_MAP'=>'-- Do not map this field --', +'LBL_STEP_1_TITLE'=>'Step 1 of 4: Select Data Source', +'LBL_WHAT_IS'=>'Please select a data source from the following:', +'LBL_MICROSOFT_OUTLOOK'=>'Microsoft Outlook', +'LBL_ACT'=>'Act!', +'LBL_SALESFORCE'=>'Salesforce.com', +'LBL_MY_SAVED'=>'My Saved Sources:', +'LBL_PUBLISH'=>'publish', +'LBL_DELETE'=>'delete', +'LBL_PUBLISHED_SOURCES'=>'Published Sources:', +'LBL_UNPUBLISH'=>'un-publish', +'LBL_NEXT'=>'Next', +'LBL_BACK'=>'Back', +'LBL_STEP_2_TITLE'=>'Step 2 of 4: Upload Export File', +'LBL_HAS_HEADER'=>'Has Header', + +'LBL_NUM_1'=>'1.', +'LBL_NUM_2'=>'2.', +'LBL_NUM_3'=>'3.', +'LBL_NUM_4'=>'4.', +'LBL_NUM_5'=>'5.', +'LBL_NUM_6'=>'6.', +'LBL_NUM_7'=>'7.', +'LBL_NUM_8'=>'8.', +'LBL_NUM_9'=>'9.', +'LBL_NUM_10'=>'10.', +'LBL_NUM_11'=>'11.', +'LBL_NUM_12'=>'12.', +'LBL_NOW_CHOOSE'=>'Now choose that file to import:', +'LBL_IMPORT_OUTLOOK_TITLE'=>'Microsoft Outlook 98 and 2000 can export data in the Comma Separated Values format which can be used to import data into the system. To export your data from Outlook, follow the steps below:', +'LBL_OUTLOOK_NUM_1'=>'Start Outlook', +'LBL_OUTLOOK_NUM_2'=>'Select the File menu, then the Import and Export ... menu option', +'LBL_OUTLOOK_NUM_3'=>'Choose Export to a file and click Next', +'LBL_OUTLOOK_NUM_4'=>'Choose Comma Separated Values (Windows) and click Next.
    Note: You may be prompted to install the export component', +'LBL_OUTLOOK_NUM_5'=>'Select the Contacts folder and click Next. You can select different contacts folders if your contacts are stored in multiple folders', +'LBL_OUTLOOK_NUM_6'=>'Choose a filename and click Next', +'LBL_OUTLOOK_NUM_7'=>'Click Finish', +'LBL_IMPORT_ACT_TITLE'=>'Act! can export data in the Comma Separated Values format which can be used to import data into the system. To export your data from Act!, follow the steps below:', +'LBL_ACT_NUM_1'=>'Launch ACT!', +'LBL_ACT_NUM_2'=>'Select the File menu, the Data Exchange menu option, then the Export... menu option', +'LBL_ACT_NUM_3'=>'Select the file type Text-Delimited', +'LBL_ACT_NUM_4'=>'Choose a filename and location for the exported data and click Next', +'LBL_ACT_NUM_5'=>'Select Contacts records only', +'LBL_ACT_NUM_6'=>'Click the Options... button', +'LBL_ACT_NUM_7'=>'Select Comma as the field separator character', +'LBL_ACT_NUM_8'=>'Check the Yes, export field names checkbox and click OK', +'LBL_ACT_NUM_9'=>'Click Next', +'LBL_ACT_NUM_10'=>'Select All Records and then Click Finish', + +'LBL_IMPORT_SF_TITLE'=>'Salesforce.com can export data in the Comma Separated Values format which can be used to import data into the system. To export your data from Salesforce.com, follow the steps below:', +'LBL_SF_NUM_1'=>'Open your browser, go to http://www.salesforce.com, and login with your email address and password', +'LBL_SF_NUM_2'=>'Click on the Reports tab on the top menu', +'LBL_SF_NUM_3'=>'To export Accounts: Click on the Active Accounts link
    To export Contacts: Click on the Mailing List link', +'LBL_SF_NUM_4'=>'On Step 1: Select your report type, select Tabular Reportclick Next', +'LBL_SF_NUM_5'=>'On Step 2: Select the report columns, choose the columns you want to export and click Next', +'LBL_SF_NUM_6'=>'On Step 3: Select the information to summarize, just click Next', +'LBL_SF_NUM_7'=>'On Step 4: Order the report columns, just click Next', +'LBL_SF_NUM_8'=>'On Step 5: Select your report criteria, under Start Date, choose a date far enough in the past to include all your Accounts. You can also export a subset of Accounts using more advanced criteria. When you are done, click Run Report', +'LBL_SF_NUM_9'=>'A report will be generated, and the page should display Report Generation Status: Complete. Now click Export to Excel', +'LBL_SF_NUM_10'=>'On Export Report:, for Export File Format:, choose Comma Delimited .csv. Click Export.', +'LBL_SF_NUM_11'=>'A dialog will pop up for you to save the export file to your computer.', +'LBL_IMPORT_CUSTOM_TITLE'=>'Many applications will allow you to export data into a Comma Delimited text file (.csv). Generally most applications follow these general steps:', +'LBL_CUSTOM_NUM_1'=>'Launch the application and Open the data file', +'LBL_CUSTOM_NUM_2'=>'Select the Save As... or Export... menu option', +'LBL_CUSTOM_NUM_3'=>'Save the file in a CSV or Comma Separated Values format', + +'LBL_STEP_3_TITLE'=>'Step 3 of 4: Confirm Fields and Import', +'LBL_STEP_1'=>'Step 1 of 3 : ', +'LBL_STEP_1_TITLE'=>'Select the .CSV File', +'LBL_STEP_1_TEXT'=> ' vtiger CRM supports importing records from .csv ( Comma Separated Values ) files. To start import, browse to locate the .CSV file and click on the Next button to Continue.', + +'LBL_SELECT_FIELDS_TO_MAP'=>'In the list below, select the fields in your import file that should be imported into each field in the system. When you are finished, click Import Now', + +'LBL_DATABASE_FIELD'=>'Database Field', +'LBL_HEADER_ROW'=>'Header Row', +'LBL_ROW'=>'Row', +'LBL_SAVE_AS_CUSTOM'=>'Save as Custom Mapping :', +'LBL_CONTACTS_NOTE_1'=>'Either Last Name or Full Name must be mapped.', +'LBL_CONTACTS_NOTE_2'=>'If Full Name is mapped, then First Name and Last Name are ignored.', +'LBL_CONTACTS_NOTE_3'=>'If Full Name is mapped, then the data in Full Name will be split into First Name and Last Name when inserted into the database.', +'LBL_CONTACTS_NOTE_4'=>'Fields ending in Address Street 2 and Address Street 3 are concatenated together with the main Address Street Field when inserted into the database.', +'LBL_ACCOUNTS_NOTE_1'=>'Account Name must be mapped.', +'LBL_ACCOUNTS_NOTE_2'=>'Fields ending in Address Street 2 and Address Street 3 are concatenated together with the main Address Street Field when inserted into the database.', +'LBL_POTENTIALS_NOTE_1'=>'Potential Name, Account Name, Date Closed, and Sales Stage are required fields.', +'LBL_OPPORTUNITIES_NOTE_1'=>'Opportunity Name, Account Name, Date Closed, and Sales Stage are required fields.', +'LBL_LEADS_NOTE_1'=>'Last Name must be mapped.', +'LBL_LEADS_NOTE_2'=>'Company Name must be mapped.', +'LBL_IMPORT_NOW'=>'Import Now', +'LBL_'=>'', +'LBL_CANNOT_OPEN'=>'Cannot open the imported file for reading', +'LBL_NOT_SAME_NUMBER'=>'There were not the same number of fields per line in your file', +'LBL_NO_LINES'=>'There were no lines in your import file', +'LBL_FILE_ALREADY_BEEN_OR'=>'The import file has already been processed or does not exist', +'LBL_SUCCESS'=>'Success! ', +'LBL_SUCCESSFULLY'=>'Succesfully Imported', +'LBL_LAST_IMPORT_UNDONE'=>'Your Last Import Was Undone', +'LBL_NO_IMPORT_TO_UNDO'=>'There was no import to undo.', +'LBL_FAIL'=>'Fail:', +'LBL_RECORDS_SKIPPED'=>'records skipped because they were missing one or more required fields', +'LBL_IDS_EXISTED_OR_LONGER'=>'records skipped because the id\'s either existed or where longer than 36 characters', +'LBL_RESULTS'=>'Results', +'LBL_IMPORT_MORE'=>'Import More', +'LBL_FINISHED'=>'Finished', +'LBL_UNDO_LAST_IMPORT'=>'Undo Last Import', + +'LBL_SUCCESS_1' => 'No. of Records Successfully Imported : ', +'LBL_SKIPPED_1' => 'No. of Records Skipped as they were missing one or more required fields : ', + +//Added for patch2 - Products Import Notes +'LBL_PRODUCTS_NOTE_1'=>'Product Name must be mapped', +'LBL_PRODUCTS_NOTE_2'=>'Before import please check whether a single column has been mapped twice', + +//Added for version 5 +'LBL_FILE_LOCATION'=>'File Location :', +'LBL_STEP_2_3'=>'Step 2 of 3 :', +'LBL_LIST_MAPPING'=>'List & Mapping', +'LBL_STEP_2_MSG'=>'The following tables shows the imported', +'LBL_STEP_2_MSG1'=>'and other details.', +'LBL_STEP_2_TXT'=>'To map the fields, select the corresponding in combo boxes for each', +'LBL_USE_SAVED_MAPPING'=>'Use Saved Mapping :', +'LBL_MAPPING'=>'Mapping', +'LBL_HEADERS'=>'Headers :', +'LBL_ERROR_MULTIPLE'=>'Same fields may be mapped twice. Please check the mapped fields.', +'LBL_STEP_3_3'=>'Step 3 of 3 : ', +'LBL_MAPPING_RESULTS'=>'Mapping Results ', +'LBL_LAST_IMPORTED'=>'Last Imported', +//Added for sript alerts +'PLEASE_CHECK_MAPPING' => "' is mapped more than once. Please check the mapping.", +'MAP_MANDATORY_FIELD' => 'Please map the mandatory field "', +'ENTER_SAVEMAP_NAME' => 'Please Enter Save Map Name', + +//Added for 5.0.3 +'to'=>'to', +'of'=>'of', +'are_imported_succesfully'=>'are imported successfully', + +// Added after 5.0.4 GA + +//added for duplicate handling +'LBL_LAST_IMPORT'=>'Last Imported', +'Select_Criteria_For_Duplicate' => 'Select Criteria For Duplicate Records Handling', +'Manual_Merging' => 'Manual Merging', +'Auto_Merging' => 'Auto Merging', +'Ignore_Duplicate' => 'Ignore the duplicate import records', +'Overwrite_Duplicate' => 'Overwrite the duplicate records', +'Duplicate_Records_Skipped_Info' => 'No. of Records Skipped as they were duplicates : ', +'Duplicate_Records_Overwrite_Info' => 'No. of Records Overwritten as they were duplicates : ', +'LBL_STEP_4_4' => 'Step 4 of 4 : ', +'LBL_STEP_3_4'=>'Step 3 of 4 :', +'LBL_STEP_2_4'=>'Step 2 of 4 :', +'LBL_STEP_1_4'=>'Step 1 of 4 : ', + +'LBL_DELIMITER' => 'Delimiter:', +'LBL_FORMAT' => 'Format:', +); + +/*$mod_list_strings = Array( + "id"=>"Contact ID" + ,"first_name"=>"First Name" + ,"last_name"=>"Last Name" + ,"salutation"=>"Salutation" + ,"lead_source"=>"Lead Source" + ,"birthdate"=>"Lead Source" + ,"do_not_call"=>"Do Not Call" + ,"email_opt_out"=>"Email Opt Out" + ,"primary_address_street_2"=>"Primary Address Street 2" + ,"primary_address_street_3"=>"Primary Address Street 3" + ,"alt_address_street_2"=>"Other Address Street 2" + ,"alt_address_street_3"=>"Other Address Street 3" + ,"full_name"=>"Full Name" + ,"account_name"=>"Account Name" + ,"account_id"=>"Account ID" + ,"title"=>"Title" + ,"department"=>"Department" + ,"birthdate"=>"Birthdate" + ,"do_not_call"=>"Do Not Call" + ,"phone_home"=>"Phone (Home)" + ,"phone_mobile"=>"Phone (Mobile)" + ,"phone_work"=>"Phone (Work)" + ,"phone_other"=>"Phone (Other)" + ,"phone_fax"=>"Fax" + ,"email1"=>"Email" + ,"email2"=>"Email (Other)" + ,"yahoo_id"=>"Yahoo! ID" + ,"assistant"=>"Assistant" + ,"assistant_phone"=>"Assistant Phone" + ,"primary_address_street"=>"Primary Address Street" + ,"primary_address_city"=>"Primary Address City" + ,"primary_address_state"=>"Primary Address State" + ,"primary_address_postalcode"=>"Primary Address Postalcode" + ,"primary_address_country"=>"Primary Address Country" + ,"alt_address_street"=>"Other Address Street" + ,"alt_address_city"=>"Other Address City" + ,"alt_address_state"=>"Other Address State" + ,"alt_address_postalcode"=>"Other Address Postalcode" + ,"alt_address_country"=>"Other Address Country" + ,"description"=>"Description" + + ),*/ +$mod_list_strings = Array( +'contacts_import_fields' => Array( + //"id"=>"Contact ID" + "firstname"=>"First Name" + ,"lastname"=>"Last Name" + ,"salutationtype"=>"Salutation" + ,"leadsource"=>"Lead Source" + ,"birthday"=>"Birthdate" + ,"donotcall"=>"Do Not Call" + ,"emailoptout"=>"Email Opt Out" + //,"primary_address_street_2"=>"Primary Address Street 2" + //,"primary_address_street_3"=>"Primary Address Street 3" + //,"alt_address_street_2"=>"Other Address Street 2" + //,"alt_address_street_3"=>"Other Address Street 3" + //,"full_name"=>"Full Name" + //,"account_name"=>"Account Name" + ,"account_id"=>"Account Name" + ,"title"=>"Title" + ,"department"=>"Department" + //,"birthdate"=>"Birthdate" + //,"do_not_call"=>"Do Not Call" + ,"homephone"=>"Phone (Home)" + ,"mobile"=>"Phone (Mobile)" + ,"phone"=>"Phone (Work)" + ,"otherphone"=>"Phone (Other)" + ,"fax"=>"Fax" + ,"email"=>"Email" + ,"otheremail"=>"Email (Other)" + ,"yahooid"=>"Yahoo! ID" + ,"assistant"=>"Assistant" + ,"assistantphone"=>"Assistant Phone" + ,"mailingstreet"=>"Mailing Address Street" + ,"mailingpobox"=>"Mailing Address PO Box" + ,"mailingcity"=>"Mailing Address City" + ,"mailingstate"=>"Mailing Address State" + ,"mailingzip"=>"Mailing Address Postalcode" + ,"mailingcountry"=>"Mailing Address Country" + ,"otherstreet"=>"Other Address Street" + ,"otherpobox"=>"Other Address PO Box" + ,"othercity"=>"Other Address City" + ,"otherstate"=>"Other Address State" + ,"otherzip"=>"Other Address Postalcode" + ,"othercountry"=>"Other Address Country" + ,"description"=>"Description" + ,"assigned_user_id"=>"Assigned To" + ), + +'accounts_import_fields' => Array( + //"id"=>"Account ID", + "accountname"=>"Account Name", + "website"=>"Website", + "industry"=>"Industry", + "accounttype"=>"Type", + "tickersymbol"=>"Ticker Symbol", + "parent_name"=>"Member of", + "employees"=>"Employees", + "ownership"=>"Ownership", + "phone"=>"Phone", + "fax"=>"Fax", + "otherphone"=>"Other Phone", + "email1"=>"Email", + "email2"=>"Other Email", + "rating"=>"Rating", + "siccode"=>"SIC Code", + "annual_revenue"=>"Annual Revenue", + "bill_street"=>"Billing Address Street", + //"billing_address_street_2"=>"Billing Address Street 2", + //"billing_address_street_3"=>"Billing Address Street 3", + //"billing_address_street_4"=>"Billing Address Street 4", + "bill_pobox"=>"Billing Address PO Box", + "bill_city"=>"Billing Address City", + "bill_state"=>"Billing Address State", + "bill_code"=>"Billing Address Postalcode", + "bill_country"=>"Billing Address Country", + "ship_street"=>"Shipping Address Street", + //"shipping_address_street_2"=>"Shipping Address Street 2", + //"shipping_address_street_3"=>"Shipping Address Street 3", + //"shipping_address_street_4"=>"Shipping Address Street 4", + "ship_pobox"=>"Shipping Address PO Box", + "ship_city"=>"Shipping Address City", + "ship_state"=>"Shipping Address State", + "ship_code"=>"Shipping Address Postalcode", + "ship_country"=>"Shipping Address Country", + "description"=>"Description", + "assigned_user_id"=>"Assigned To" + ), + +'potentials_import_fields' => Array( + //"id"=>"Account ID" + "potentialname"=>"Potential Name" + , "account_id"=>"Account Name" + , "opportunity_type"=>"Potential Type" + , "leadsource"=>"Lead Source" + , "amount"=>"Amount" + , "closingdate"=>"Closing Date" + , "nextstep"=>"Next Step" + , "sales_stage"=>"Sales Stage" + , "probability"=>"Probability" + , "description"=>"Description" + ,"assigned_user_id"=>"Assigned To" + ), + + +'leads_import_fields' => Array( + "salutationtype"=>"Salutation", + "firstname"=>"First Name", + "phone"=>"Phone", + "lastname"=>"Last Name", + "mobile"=>"Mobile", + "company"=>"Company", + "fax"=>"Fax", + "designation"=>"Designation", + "email"=>"Email", + "leadsource"=>"Lead Source", + "website"=>"Website", + "industry"=>"Industry", + "leadstatus"=>"Lead Status", + "annualrevenue"=>"Annual Revenue", + "rating"=>"Rating", + "noofemployees"=>"No Of Employees", + "assigned_user_id"=>"Assigned To", + "yahooid"=>"Yahoo Id", + "lane"=>"Street", + "pobox"=>"PO Box", + "code"=>"Postal Code", + "city"=>"City", + "country"=>"Country", + "state"=>"State", + "description"=>"Description" + ,"assigned_user_id"=>"Assigned To" + ), + + 'products_import_fields' => Array( + 'productname'=>'Product Name', + 'productcode'=>'Product Code', + 'productcategory'=>'Product Category', + 'manufacturer'=>'Manufacturer', + 'product_description'=>'Product Description', + 'qty_per_unit'=>'Quantity Per/Unit', + 'unit_price'=>'Unit Price', + 'weight'=>'Weight', + 'pack_size'=>'Pack Size', + 'start_date'=>'Start Date', + 'expiry_date'=>'Expiration Date', + 'cost_factor'=>'Cost Factor', + 'commissionmethod'=>'Commission Method', + 'discontinued'=>'Discontinued', + 'commissionrate'=>'Commission Rate', + 'sales_start_date'=>'Sales Start Date', + 'sales_end_date'=>'Sales End Date', + 'usageunit'=>'Usage Unit', + 'serialno'=>'Serial No', + 'currency'=>'currency', + 'reorderlevel'=>'Reorder Level', + 'website'=>'Web Site', + 'taxclass'=>'Tax Class', + 'mfr_part_no'=>'Manufacture Part No', + 'vendor_part_no'=>'Vendor Part No', + 'qtyinstock'=>'Quantity in Stock', + 'productsheet'=>'Product Sheet', + 'qtyindemand'=>'Quantity in Demand', + 'glacct'=>'GL Account', + 'assigned_user_id'=>'Assigned To' + ), +//Pavani...adding list of import fields for helpdesk and vendors +'helpdesk_import_fields' => Array( + "ticketid"=>"Ticket Id", + "priority"=>"Priority", + "severity"=>"Severity", + "status"=>"Status", + "category"=>"Category", + "title"=>"Title", + "description"=>"Description", + "solution"=>"Solution" + ), + +'vendors_import_fields' => Array( + "vendorid"=>"Vender Id", + "vendorname"=>"Vendor Name", + "phone"=>"Phone", + "email"=>"Email", + "website"=>"Website", + "category"=>"Category", + "street"=>"Street", + "city"=>"City", + "state"=>"State", + "pobox"=>"Post Box", + "postalcode"=>"Postal Code", + "country"=>"Country", + "description"=>"Description" + ) +//Pavani...end list +); + +?> diff --git a/oss/vtiger/trunk/modules/Import/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Import/language/zh_cn.lang.php new file mode 100644 index 00000000..72d381de --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/language/zh_cn.lang.php @@ -0,0 +1,432 @@ + '目录 ', + 'LBL_IMPORT_MODULE_NO_DIRECTORY_END' => ' 不存在或没有记录', + 'LBL_IMPORT_MODULE_ERROR_NO_UPLOAD' => '文件无法顺利上传,请再重试', + 'LBL_IMPORT_MODULE_ERROR_LARGE_FILE' => '文件太大,大小上限:', + 'LBL_IMPORT_MODULE_ERROR_LARGE_FILE_END' => '字节,在 config.php 中调整 $upload_maxsize 设定', + 'LBL_MODULE_NAME' => '导入', + 'LBL_TRY_AGAIN' => '重试', + 'LBL_ERROR' => '错误:', + 'ERR_MULTIPLE' => '定义字段可多行输入.', + 'ERR_MISSING_REQUIRED_FIELDS' => '漏填必须字段:', + 'ERR_SELECT_FULL_NAME' => '当姓或名被选择时,您就不能再选全名.', + 'ERR_SELECT_FILE' => '选择文件以供上传.', + 'LBL_SELECT_FILE' => '选择文件:', + 'LBL_CUSTOM' => '自订', + 'LBL_DONT_MAP' => '-- 没有标记这个字段 --', + 'LBL_STEP_1_TITLE' => '步骤 1 到 4: 选择数据来源', + 'LBL_WHAT_IS' => '请选择数据来源:', + 'LBL_MICROSOFT_OUTLOOK' => 'Microsoft Outlook', + 'LBL_ACT' => 'Act!', + 'LBL_SALESFORCE' => 'Salesforce.com', + 'LBL_MY_SAVED' => '我所储存的来源:', + 'LBL_PUBLISH' => '发布', + 'LBL_DELETE' => '删除', + 'LBL_PUBLISHED_SOURCES' => '发布来源:', + 'LBL_UNPUBLISH' => '不发布', + 'LBL_NEXT' => '下一步', + 'LBL_BACK' => '上一步', + 'LBL_STEP_2_TITLE' => '步骤 2 of 4: 上传导入文件', + 'LBL_HAS_HEADER' => '标题行:', + +'LBL_NUM_1'=>'1.', +'LBL_NUM_2'=>'2.', +'LBL_NUM_3'=>'3.', +'LBL_NUM_4'=>'4.', +'LBL_NUM_5'=>'5.', +'LBL_NUM_6'=>'6.', +'LBL_NUM_7'=>'7.', +'LBL_NUM_8'=>'8.', +'LBL_NUM_9'=>'9.', +'LBL_NUM_10'=>'10.', +'LBL_NUM_11'=>'11.', +'LBL_NUM_12'=>'12.', +'LBL_NOW_CHOOSE' => '选择读入文件:', + 'LBL_IMPORT_OUTLOOK_TITLE' => 'Microsoft Outlook 98 and 2000 能依据标点符号区分各字段数据以读入或导出数据,请随后续的指示操作:', + 'LBL_OUTLOOK_NUM_1' => '开始 Outlook', + 'LBL_OUTLOOK_NUM_2' => '选择指定的 文件 清单, 以利 读入及导出 ... 清单选项', + 'LBL_OUTLOOK_NUM_3' => '选择 导出文件 和点选下一步', + 'LBL_OUTLOOK_NUM_4' => '选择 区分逗号值 (Windows) 并点选 下一步.
    备注: 您在安装导出组件时所必须作的相关提示', + 'LBL_OUTLOOK_NUM_5' => '选择 联络人 数据夹和点选 下一步. 如果您选择重了复选数据夹,您就能够选择不同的联络人数据夹', + 'LBL_OUTLOOK_NUM_6' => '选择文件名称并点选 下一步', + 'LBL_OUTLOOK_NUM_7' => '选择 完成', + 'LBL_IMPORT_ACT_TITLE' => '动作提示! 您所读入导出的数据会依据 区分标点符号 格式来执行!, 请随后续的指示操作:', + 'LBL_ACT_NUM_1' => '开始 执行!', + 'LBL_ACT_NUM_2' => '选择 文件 清单, 数据交换 清单选项, 以利 导出... 清单选项', + 'LBL_ACT_NUM_3' => '选择文件类型 Text-Delimited', + 'LBL_ACT_NUM_4' => '选择文件及其位置以利输出数据,并点选 下一步', + 'LBL_ACT_NUM_5' => '选择 仅限联络人记录', + 'LBL_ACT_NUM_6' => '点选 选项... 按钮', + 'LBL_ACT_NUM_7' => '选择 标点符号 区分字段字符', + 'LBL_ACT_NUM_8' => '检查 确定, 导出字段名称 核取并点选选 OK', + 'LBL_ACT_NUM_9' => '点选 下一步', + 'LBL_ACT_NUM_10' => '选择 全部记录 和点选 完成', + +'LBL_IMPORT_SF_TITLE' => 'Salesforce.com 能输出数据以导入数据到系统中,利用 区分标点符号 格式来执行,请随后续的指示操作:', + 'LBL_SF_NUM_1' => '开启您的浏览器, 到 http://www.salesforce.com, 和登入您的电子邮件地址及密码', + 'LBL_SF_NUM_2' => '在顶层清单中,点选 导出 ', + 'LBL_SF_NUM_3' => '输出公司: 点选 经常往来公司 连结
    输出联络人: 选择 电子邮件列表 连结', + 'LBL_SF_NUM_4' => '步骤 1: 选择您的报告类型, 选择 表格报告点选 下一步', + 'LBL_SF_NUM_5' => '步骤 2: 选择报告栏, 点选您要输出的字段 下一步', + 'LBL_SF_NUM_6' => '步骤 3: 选择总结讯息, 点选 下一步', + 'LBL_SF_NUM_7' => '步骤 4: 命令输出字段, 点选 下一步', + 'LBL_SF_NUM_8' => '步骤 5: 选择您的输出标准, 在 开始日期下方, 选择足够的日期范围值到您的公司. 您您可以输出公司相关的信息利用更多的进阶选项. 当您完成, 点选 报告', + 'LBL_SF_NUM_9' => '报告将产生, 并且该页面会显示 报告执行身份: 编译. 立即点选 输出到Excel电子电子表格', + 'LBL_SF_NUM_10' => '在 输出报告:, 从 输出文件格式:, 选择 标点符号区分.csv. 点选 输出.', + 'LBL_SF_NUM_11' => '将会弹出对话窗口让您可以储存输出文件.', + 'LBL_IMPORT_CUSTOM_TITLE' => '许多应用将会依您的输出数据所设定的 标点符号区分 (.csv). 通常将会依一般设定值来执行:', + 'LBL_CUSTOM_NUM_1' => '开始应用执行并打开数据文件', + 'LBL_CUSTOM_NUM_2' => '选择 另存...输出... 清单选项', + 'LBL_CUSTOM_NUM_3' => '储存文件的格式依据 CSV标点符号设定值', + + 'LBL_STEP_3_TITLE' => '步骤 3 / 4: 确认导入字段', + 'LBL_STEP_1' => '步骤 1 / 3:', + 'LBL_STEP_1_TITLE'=>'选择 .CSV 文件', + 'LBL_STEP_1_TEXT' => ' vtiger CRM 支持从 .csv ( 逗点分隔数据 ) 文件导入数据,请选择指定的文件后点选继续按钮。
    注意:请在执行导入前,首先修改导入文件的编码为:UTF-8或ISO-8859-1', + + 'LBL_SELECT_FIELDS_TO_MAP' => '在列表下方, 从您读入的文件中选择输入的字段. 当您完成时,点选 立即读入', + + 'LBL_DATABASE_FIELD' => '数据库字段', + 'LBL_HEADER_ROW' => '字段标题', + 'LBL_ROW' => '列', + 'LBL_SAVE_AS_CUSTOM' => '储存自订标记:', + 'LBL_CONTACTS_NOTE_1' => '不管是名或全名都必须被标记选择.', + 'LBL_CONTACTS_NOTE_2' => '如果全名被标记选择, 那姓与名字段就会取消.', + 'LBL_CONTACTS_NOTE_3' => '如果全名被标记选择,当要写入数据库时它们会被自动分割成姓与名.', + 'LBL_CONTACTS_NOTE_4' => '数据新增到数据库时,在地址2与地址3的信息会与主要地址字段合并', + 'LBL_ACCOUNTS_NOTE_1' => '公司名称必须被选择标记.', + 'LBL_ACCOUNTS_NOTE_2' => '当要写入数据库时,将地址街道巷号2和街道巷号3的数据合并在主要地址字段.', + 'LBL_POTENTIALS_NOTE_1' => '潜在机会名称,公司名称,结束日期与销售策略都是必填字段', + 'LBL_OPPORTUNITIES_NOTE_1' => '潜在案件名称, 公司名称, 结束日期, 和客服场地所需的字段.', + 'LBL_LEADS_NOTE_1' => '必须指定姓氏', + 'LBL_LEADS_NOTE_2' => '必须指定公司名称', + 'LBL_IMPORT_NOW' => '立即读入', + 'LBL_' => '', + 'LBL_CANNOT_OPEN' => '无法读取导入的文件', + 'LBL_NOT_SAME_NUMBER' => '在您指定的文件中每列的各字段的号码不一致', + 'LBL_NO_LINES' => '在您读入的文件中没有行号', + 'LBL_FILE_ALREADY_BEEN_OR' => '您所指定导入的文件已经处理过或不存在', + 'LBL_SUCCESS' => '服务系统操作:', + 'LBL_SUCCESSFULLY' => '读入系统操作', + 'LBL_LAST_IMPORT_UNDONE' => '您最后一笔读入的信息已取消', + 'LBL_NO_IMPORT_TO_UNDO' => '没有读入的信息供取消.', + 'LBL_FAIL' => '失败:', + 'LBL_RECORDS_SKIPPED' => '该笔记录略过,因为缺漏必要字段值', + 'LBL_IDS_EXISTED_OR_LONGER' => '该笔记录略过,因为记录编号已存在或长度超过36字符', + 'LBL_RESULTS' => '结果', + 'LBL_IMPORT_MORE' => '读入更多...', + 'LBL_FINISHED' => '已完成', + 'LBL_UNDO_LAST_IMPORT' => '取消最后一笔的读入', + + 'LBL_SUCCESS_1' => '成功导入数据笔数:', + 'LBL_SKIPPED_1' => '略过的数据笔数(可能缺少一或多个字段):', + + //Added for patch2 - Products Import Notes + 'LBL_PRODUCTS_NOTE_1' => '必须对应产品名称', + 'LBL_PRODUCTS_NOTE_2' => '在导入前请先确认单一字段是否被指定两次', + + //Added for version 5 + 'LBL_FILE_LOCATION' => '文件位置:', + 'LBL_STEP_2_3' => '步骤 2 / 3:', + 'LBL_LIST_MAPPING' => '列表与对应', + 'LBL_STEP_2_MSG' => '下面数据表显示导入的数据', + 'LBL_STEP_2_MSG1' => '与其它细节。', + 'LBL_STEP_2_TXT' => '对应字段的方式是在下面相对方块中调整个别项目', + 'LBL_USE_SAVED_MAPPING' => '使用预存对应:', + 'LBL_MAPPING' => '对应', + 'LBL_HEADERS' => '页首:', + 'LBL_ERROR_MULTIPLE' => '同样的字段对应两次,请检查对应字段。', + 'LBL_STEP_3_3' => '步骤 3 / 3 :', + 'LBL_MAPPING_RESULTS' => '对应结果', + 'LBL_LAST_IMPORTED' => '最新导入的', +//Added for sript alerts +'PLEASE_CHECK_MAPPING' => "' 映射一次以上。请检查映射.", +'MAP_MANDATORY_FIELD' => 'Please map the mandatory field "', +'ENTER_SAVEMAP_NAME' => '请输入要保存的地图名', + +//Added for 5.0.3 +'to'=>'to', +'of'=>'of', +'are_imported_succesfully'=>'导入成功', + +// Added after 5.0.4 GA + +//added for duplicate handling +'LBL_LAST_IMPORT'=>'Last Imported', +'Select_Criteria_For_Duplicate' => 'Select Criteria For Duplicate Records Handling', +'Manual_Merging' => 'Manual Merging', +'Auto_Merging' => 'Auto Merging', +'Ignore_Duplicate' => 'Ignore the duplicate import records', +'Overwrite_Duplicate' => 'Overwrite the duplicate records', +'Duplicate_Records_Skipped_Info' => 'No. of Records Skipped as they were duplicates : ', +'Duplicate_Records_Overwrite_Info' => 'No. of Records Overwritten as they were duplicates : ', +'LBL_STEP_4_4' => 'Step 4 of 4 : ', +'LBL_STEP_3_4'=>'Step 3 of 4 :', +'LBL_STEP_2_4'=>'Step 2 of 4 :', +'LBL_STEP_1_4'=>'Step 1 of 4 : ', + +'LBL_DELIMITER' => '定界符:', +'LBL_FORMAT' => '编码:', +); + +/*$mod_list_strings = Array( + "id"=>"Contact ID" + ,"first_name"=>"First Name" + ,"last_name"=>"Last Name" + ,"salutation"=>"Salutation" + ,"lead_source"=>"Lead Source" + ,"birthdate"=>"Lead Source" + ,"do_not_call"=>"Do Not Call" + ,"email_opt_out"=>"Email Opt Out" + ,"primary_address_street_2"=>"Primary Address Street 2" + ,"primary_address_street_3"=>"Primary Address Street 3" + ,"alt_address_street_2"=>"Other Address Street 2" + ,"alt_address_street_3"=>"Other Address Street 3" + ,"full_name"=>"Full Name" + ,"account_name"=>"Account Name" + ,"account_id"=>"Account ID" + ,"title"=>"Title" + ,"department"=>"Department" + ,"birthdate"=>"Birthdate" + ,"do_not_call"=>"Do Not Call" + ,"phone_home"=>"Phone (Home)" + ,"phone_mobile"=>"Phone (Mobile)" + ,"phone_work"=>"Phone (Work)" + ,"phone_other"=>"Phone (Other)" + ,"phone_fax"=>"Fax" + ,"email1"=>"Email" + ,"email2"=>"Email (Other)" + ,"yahoo_id"=>"Yahoo! ID" + ,"assistant"=>"Assistant" + ,"assistant_phone"=>"Assistant Phone" + ,"primary_address_street"=>"Primary Address Street" + ,"primary_address_city"=>"Primary Address City" + ,"primary_address_state"=>"Primary Address State" + ,"primary_address_postalcode"=>"Primary Address Postalcode" + ,"primary_address_country"=>"Primary Address Country" + ,"alt_address_street"=>"Other Address Street" + ,"alt_address_city"=>"Other Address City" + ,"alt_address_state"=>"Other Address State" + ,"alt_address_postalcode"=>"Other Address Postalcode" + ,"alt_address_country"=>"Other Address Country" + ,"description"=>"Description" + + ),*/ +$mod_list_strings = Array( +'contacts_import_fields' => Array( + //"id"=>"Contact ID" + "firstname"=>"名字" + ,"lastname"=>"姓氏" + ,"salutationtype"=>"称号" + ,"leadsource"=>"资料来源" + ,"birthday"=>"出生日期" + ,"donotcall"=>"请勿来电" + ,"emailoptout"=>"请勿来信" + //,"primary_address_street_2"=>"Primary Address Street 2" + //,"primary_address_street_3"=>"Primary Address Street 3" + //,"alt_address_street_2"=>"Other Address Street 2" + //,"alt_address_street_3"=>"Other Address Street 3" + //,"full_name"=>"Full Name" + //,"account_name"=>"Account Name" + ,'account_id' => '公司名称' + ,'title' => '标题' + ,'department' => '部门' + //,"birthdate"=>"Birthdate" + //,"do_not_call"=>"Do Not Call" + ,"homephone"=>"电话(家庭)" + ,"mobile"=>"电话 (手机)" + ,"phone"=>"电话 (工作)" + ,"otherphone"=>"电话 (其他)" + ,"fax"=>"传真" + ,"email"=>"Email" + ,"otheremail"=>"Email (其他)" + ,"yahooid"=>"Yahoo! ID" + ,"assistant"=>"助理" + ,"assistantphone"=>"助理电话" + ,"mailingstreet"=>"信件地址(街道巷号)" + ,"mailingpobox"=>"信件地址(邮政信箱)" + ,"mailingcity"=>"信件地址(乡镇市区)" + ,"mailingstate"=>"信件地址(县市)" + ,"mailingzip"=>"信件地址(邮政编码)" + ,"mailingcountry"=>"信件地址(国家)" + ,"otherstreet"=>"其它地址(街道巷号)" + ,"otherpobox"=>"其它地址(邮政信箱)" + ,"othercity"=>"其它地址(乡镇市区)" + ,"otherstate"=>"其它地址(县市)" + ,"otherzip"=>"其它地址(邮政编码)" + ,"othercountry"=>"其它地址(国家)" + ,"description"=>"描述" + ,"assigned_user_id"=>"担当者" + ), + +'accounts_import_fields' => Array( + //"id"=>"Account ID", + "accountname"=>"公司名称", + "website"=>"网站", + "industry"=>"企业", + "accounttype"=>"类型", + "tickersymbol"=>"传票符号", + "parent_name"=>"成员", + "employees"=>"员工", + "ownership"=>"潜在客户", + "phone"=>"电话", + "fax"=>"传真", + "otherphone"=>"其他电话", + "email1"=>"Email", + "email2"=>"其他电邮", + "rating"=>"评价", + "siccode"=>"统一编号", + "annual_revenue"=>"年营业额", + "bill_street"=>"账单地址(街道巷号)", + //"billing_address_street_2"=>"Billing Address Street 2", + //"billing_address_street_3"=>"Billing Address Street 3", + //"billing_address_street_4"=>"Billing Address Street 4", + "bill_pobox"=>"账单地址(邮政信箱)", + "bill_city"=>"账单地址(乡镇市区)", + "bill_state"=>"账单地址(县市)", + "bill_code"=>"账单地址(邮政编码)", + "bill_country"=>"账单地址(国家)", + "ship_street"=>"送货地址(街道巷号)", + //"shipping_address_street_2"=>"Shipping Address Street 2", + //"shipping_address_street_3"=>"Shipping Address Street 3", + //"shipping_address_street_4"=>"Shipping Address Street 4", + "ship_pobox"=>"收货住址(邮政信箱)", + "ship_city"=>"送货地址(乡镇市区)", + "ship_state"=>"送货地址(县市)", + "ship_code"=>"送货地址(邮政编码)", + "ship_country"=>"送货地址(国家)", + "description"=>"描述", + "assigned_user_id"=>"负责人" + ), + +'potentials_import_fields' => Array( + //"id"=>"Account ID" + "potentialname"=>"潜在案件名称" + , "account_id"=>"公司名称" + , "opportunity_type"=>"潜在案件类型" + , "leadsource"=>"资料来源" + , "amount"=>"合计" + , "closingdate"=>"关闭日期" + , "nextstep"=>"下一步设定" + , "sales_stage"=>"客服位置" + , "probability"=>"可能性" + , "description"=>"描述" + ,"assigned_user_id"=>"负责人" + ), + + +'leads_import_fields' => Array( + "salutationtype"=>"称号", + "firstname"=>"姓", + "phone"=>"电话", + "lastname"=>"名", + "mobile"=>"手机", + "company"=>"公司", + "fax"=>"传真", + "designation"=>"任命", + "email"=>"Email", + "leadsource"=>"资料来源", + "website"=>"网站", + "industry"=>"企业", + "leadstatus"=>"潜在客户职位", + "annualrevenue"=>"年营业额", + "rating"=>"评价", + "noofemployees"=>"没有雇员", + "assigned_user_id"=>"负责人", + "yahooid"=>"Yahoo Id", + "lane"=>"街道巷号", + "pobox"=>"邮政信箱", + "code"=>"邮政编码", + "city"=>"乡镇市区", + "country"=>"国家", + "state"=>"县市", + "description"=>"描述", + "assigned_user_id"=>"负责人" + ), + + 'products_import_fields' => Array( + 'productname' => '产品名称', + 'productcode' => '产品代码', + 'productcategory' => '产品类别', + 'manufacturer' => '制造商', + 'product_description' => '产品介绍', + 'qty_per_unit' => '单位数量', + 'unit_price' => '单位价格', + 'weight' => '重量', + 'pack_size' => '包装大小', + 'start_date' => '开始日期', + 'expiry_date' => '到期日', + 'cost_factor' => '成本要素', + 'commissionmethod' => '佣金计算方式', + 'discontinued' => '停售', + 'commissionrate' => '佣金率', + 'sales_start_date' => '开始销售日期', + 'sales_end_date' => '停止销售日期', + 'usageunit' => '使用单位', + 'serialno' => '序号', + 'currency' => '货币', + 'reorderlevel' => '安全库存', + 'website' => '网站', + 'taxclass' => '税别', + 'mfr_part_no' => '制造零件编号', + 'vendor_part_no' => '厂商零件编号', + 'qtyinstock' => '库存数量', + 'productsheet' => '产品表', + 'qtyindemand' => '需求数量', + 'glacct' => '会计科目', + 'assigned_user_id' => '负责人' + ), +//Pavani...adding list of import fields for helpdesk and vendors +'helpdesk_import_fields' => Array( + "ticketid"=>"Ticket Id", + "priority"=>"Priority", + "severity"=>"Severity", + "status"=>"Status", + "category"=>"Category", + "title"=>"Title", + "description"=>"Description", + "solution"=>"Solution" + ), + +'vendors_import_fields' => Array( + "vendorid"=>"Vender Id", + "vendorname"=>"Vendor Name", + "phone"=>"Phone", + "email"=>"Email", + "website"=>"Website", + "category"=>"Category", + "street"=>"Street", + "city"=>"City", + "state"=>"State", + "pobox"=>"Post Box", + "postalcode"=>"Postal Code", + "country"=>"Country", + "description"=>"Description" + ) +//Pavani...end list +); + +?> diff --git a/oss/vtiger/trunk/modules/Import/lastImport.php b/oss/vtiger/trunk/modules/Import/lastImport.php new file mode 100644 index 00000000..70e0d050 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/lastImport.php @@ -0,0 +1,207 @@ +info("Import Step last"); + +$parenttab = getParenttab(); +//This Buttons_List1.tpl is is called to display the add, search, import and export buttons ie., second level tabs +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("IMP", $import_mod_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +$smarty->assign("MODULE", vtlib_purify($_REQUEST['req_mod'])); +$smarty->assign("SINGLE_MOD", vtlib_purify($_REQUEST['modulename'])); +$smarty->assign("CATEGORY", vtlib_purify($_SESSION['import_parenttab'])); + +global $limit; +global $list_max_entries_per_page; + +$implict_account = false; + +$import_modules_array = Array( + "Leads"=>"Leads", + "Accounts"=>"Accounts", + "Contacts"=>"Contacts", + "Potentials"=>"Potentials", + "Products"=>"Products", + "HelpDesk"=>"ImportTicket", + "Vendors"=>"ImportVendors" + ); + +if(!empty($_REQUEST['req_mod'])) { + $req_mod = $_REQUEST['req_mod']; + checkFileAccess("modules/$req_mod/$req_mod.php"); + require_once("modules/$req_mod/$req_mod.php"); + if(!isset($import_modules_array[$req_mod])) { + $import_modules_array[$req_mod] = $req_mod; + } +} + +foreach($import_modules_array as $module_name => $object_name) +{ + + $seedUsersLastImport = new UsersLastImport(); + $seedUsersLastImport->bean_type = $module_name; + $list_query = $seedUsersLastImport->create_list_query($o,$w); + $current_module_strings = return_module_language($current_language, $module_name); + + $object = new $object_name(); + $seedUsersLastImport->list_fields = $object->list_fields; + + $list_result = $adb->query($list_query); + //Retreiving the no of rows + $noofrows = $adb->num_rows($list_result); + + if($noofrows < 1) { + if($module_name == $_REQUEST['req_mod']) { + echo ""; + echo "
    "; + echo "
    + + + + + + +
    + $app_strings[LBL_NO] $mod_strings[LBL_LAST_IMPORTED] $app_strings[$module_name]
    +
    "; + echo "
    "; + } + } else { + if($module_name != 'Accounts') + { + $implict_account=true; + } + + if($module_name == 'Accounts' && $implict_account==true) + $display_header_msg = "Newly created Accounts"; + else + $display_header_msg = "".$mod_strings['LBL_LAST_IMPORTED']." ".$app_strings[$module_name].""; + + //Display the Header Message + echo " + + + + +
    + ".$mod_strings['LBL_LAST_IMPORTED']." ".$app_strings[$module_name]." +
    + "; + + $smarty = new vtigerCRM_Smarty; + + $smarty->assign("MOD", $mod_strings); + $smarty->assign("APP", $app_strings); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE",$module_name); + $smarty->assign("SINGLE_MOD",$module_name); + $smarty->assign("SHOW_MASS_SELECT",'false'); + + //Retreiving the start value from request + if($module_name == $_REQUEST['nav_module'] && isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); + } else { + $start = 1; + } + + $info_message='&recordcount='.vtlib_purify($_REQUEST['recordcount']).'&noofrows='.vtlib_purify($_REQUEST['noofrows']).'&message='.vtlib_purify($_REQUEST['message']).'&skipped_record_count='.vtlib_purify($_REQUEST['skipped_record_count']); + $url_string = '&modulename='.vtlib_purify($_REQUEST['modulename']).'&nav_module='.$module_name.$info_message; + $viewid = ''; + + //Retreive the Navigation array + $navigation_array = getNavigationValues($start, $noofrows, $list_max_entries_per_page); + $navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Import","ImportSteplast",$viewid); + + //Retreive the List View Header and Entries + $listview_header = getListViewHeader($object,$module_name); + $listview_entries = getListViewEntries($object,$module_name,$list_result,$navigation_array,"","","EditView","Delete",""); + //commented to remove navigation buttons from import list view + //$smarty->assign("NAVIGATION", $navigationOutput); + $smarty->assign("HIDE_CUSTOM_LINKS", 1);//Added to hide the CustomView links in imported records ListView + + // Remove all the links for the list view header as they do not work in this page. + for($i=0;$iassign("LISTHEADER", $listview_header); + $smarty->assign("LISTENTITY", $listview_entries); + + // Include required scripts + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + + $smarty->display("ListViewEntries.tpl"); + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Import/parse_utils.php b/oss/vtiger/trunk/modules/Import/parse_utils.php new file mode 100644 index 00000000..ac0af155 --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/parse_utils.php @@ -0,0 +1,148 @@ +&$rows, "field_count"=>$field_count where as &rows is the reference of rows which contains all the parsed rows and $field_count is the number of fields available per row + */ +function parse_import($file_name,$delimiter,$max_lines,$has_header) +{ + $line_count = 0; + + $field_count = 0; + + $rows = array(); + + if (! file_exists($file_name)) + { + return -1; + } + + $fh = fopen($file_name,"r"); + + if (! $fh) + { + return -1; + } + + while ( (( $fields = fgetcsv($fh, 4096, $delimiter) ) !== FALSE) + && ( $max_lines == -1 || $line_count < $max_lines)) + { + + if ( count($fields) == 1 && isset($fields[0]) && $fields[0] == '') + { + break; + } + $this_field_count = count($fields); + + if ( $this_field_count > $field_count) + { + $field_count = $this_field_count; + } + + array_push($rows,$fields); + + $line_count++; + + } + + // got no rows + if ( count($rows) == 0) + { + return -3; + } + + $ret_array = array( + "rows"=>&$rows, + "field_count"=>$field_count + ); + + return $ret_array; + +} + +/** function used to parse the act file + * @param string $file_name - file name + * @param character $delimiter - delimiter of the csv file + * @param int $max_lines - maximum number of lines to parse + * @param int $has_header - if the file has header then 1 otherwise 0 + * @return array $ret_array - return an array which will be "rows"=>&$rows, "field_count"=>$field_count where as &rows is the reference of rows which contains all the parsed rows and $field_count is the number of fields available per row + */ +function parse_import_act($file_name,$delimiter,$max_lines,$has_header) +{ + $line_count = 0; + + $field_count = 0; + + $rows = array(); + + if (! file_exists($file_name)) + { + return -1; + } + + $fh = fopen($file_name,"r"); + + if (! $fh) + { + return -1; + } + + while ( ($line = fgets($fh, 4096)) + && ( $max_lines == -1 || $line_count < $max_lines) ) + + { + + $line = trim($line); + $line = substr_replace($line,"",0,1); + $line = substr_replace($line,"",-1); + $fields = explode("\",\"",$line); + + $this_field_count = count($fields); + + if ( $this_field_count > $field_count) + { + $field_count = $this_field_count; + } + + array_push($rows,$fields); + + $line_count++; + + } + + // got no rows + if ( count($rows) == 0) + { + return -3; + } + + $ret_array = array( + "rows"=>&$rows, + "field_count"=>$field_count + ); + + return $ret_array; + +} +?> diff --git a/oss/vtiger/trunk/modules/Import/picklist_addition.php b/oss/vtiger/trunk/modules/Import/picklist_addition.php new file mode 100644 index 00000000..2f73f15e --- /dev/null +++ b/oss/vtiger/trunk/modules/Import/picklist_addition.php @@ -0,0 +1,104 @@ +pquery("select fieldname from vtiger_field where uitype in ('15') and tabid=? and vtiger_field.presence in (0,2)", array($tabid)); +$no_of_picklists = $adb->num_rows($picklist_result); +for($i=0;$i<$no_of_picklists;$i++) +{ + $fieldname = $adb->query_result($picklist_result, $i, 'fieldname'); + $tablename = "vtiger_".$fieldname; + $picklist_result2 = $adb->query("select * from $tablename"); + $available_picklists[] = $fieldname; + //Now get all picklist values + for($j=0;$j<$adb->num_rows($picklist_result2);$j++) + { + $table_picklist[$fieldname][$j]=$adb->query_result($picklist_result2, $j, $fieldname); + $converted_table_picklist_values[$fieldname][$j] = strtolower($adb->query_result($picklist_result2, $j, $fieldname)); + } +} + +//Collect all picklist values from csv file +foreach($field_to_pos as $fieldname => $ind) +{ + if(in_array($fieldname,$available_picklists)) + { + $adb->println("Picklist - $fieldname is mapped."); + $picklist_pos[$fieldname] = $ind; + for($i=1;$i $temp_array) +{ + $tablename = "vtiger_$fieldname"; + + foreach($temp_array as $ind => $picklist_value) + { + $pick_val = strtolower($picklist_value); + //Check whether $picklist_value is exist in the array of available picklist entries + if(!in_array($pick_val, $converted_table_picklist_values[$fieldname])) + { + + //Not exist, so we have to add this $picklist_value in $fieldname(picklist name) table + $picklist_value = addslashes($picklist_value); + + $adb->println("$picklist_value has to be added in the table $tablename"); + + $cfId=$adb->getUniqueID($tablename); + $unique_picklist_value = getUniquePicklistID(); + $qry="insert into $tablename values(?,?,?,?)"; + $adb->pquery($qry, array($cfId,$picklist_value,1,$unique_picklist_value)); + //added to fix ticket#4492 + $picklistId_qry = "select picklistid from vtiger_picklist where name=?"; + $picklistId_res = $adb->pquery($picklistId_qry,array($fieldname)); + $picklist_Id = $adb->query_result($picklistId_res,0,'picklistid'); + + $role_id = $current_user->roleid; + $sort_qry = "select max(sortid)+1 as sortid from vtiger_role2picklist where picklistid=? and roleid=?"; + $sort_qry_res = $adb->pquery($sort_qry,array($picklist_Id,$role_id)); + $sort_id = $adb->query_result($sort_qry_res,0,'sortid'); + $role_picklist = "insert into vtiger_role2picklist values (?,?,?,?)"; + $adb->pquery($role_picklist,array($role_id,$unique_picklist_value,$picklist_Id,$sort_id)); + } + + + } + +} +function getPicklist($field,$value) +{ + global $table_picklist,$converted_table_picklist_values; + $orginal_val = $table_picklist[$field]; + $converted_val = $converted_table_picklist_values[$field]; + $temp_val = strtolower($value); + + if(in_array($temp_val,$converted_val)) + { + $existkey = array_search($temp_val,$converted_val); + $correct_val=$orginal_val[$existkey]; + return $correct_val; + }else + return null; + +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/CallRelatedList.php b/oss/vtiger/trunk/modules/Invoice/CallRelatedList.php new file mode 100644 index 00000000..b238a8d0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/CallRelatedList.php @@ -0,0 +1,75 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['subject']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings; + global $currentModule; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array=getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("CATEGORY",$category); + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("ID",$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 + + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$mod_strings['Invoice']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/CreatePDF.php b/oss/vtiger/trunk/modules/Invoice/CreatePDF.php new file mode 100644 index 00000000..ad50e7d0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/CreatePDF.php @@ -0,0 +1,27 @@ +Output($filepath,'F'); //added file name to make it work in IE, also forces the download giving the user the option to save + +}else { + $pdf->Output('Invoice.pdf','D'); //added file name to make it work in IE, also forces the download giving the user the option to save + exit(); +} + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/CustomView.php b/oss/vtiger/trunk/modules/Invoice/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Invoice/Delete.php b/oss/vtiger/trunk/modules/Invoice/Delete.php new file mode 100644 index 00000000..fdc8a921 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/Delete.php @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/DetailView.php b/oss/vtiger/trunk/modules/Invoice/DetailView.php new file mode 100644 index 00000000..6676a71d --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/DetailView.php @@ -0,0 +1,126 @@ +retrieve_entity_info($_REQUEST['record'],"Invoice"); + $focus->id = $_REQUEST['record']; + $focus->name=$focus->column_fields['subject']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Order detail view"); + + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("MODULE",$currentModule); + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +// 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 + +$smarty->assign("SINGLE_MOD", 'Invoice'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +if(isPermitted("Invoice","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +$smarty->assign("CREATEPDF","permitted"); + +if(isPermitted("Invoice","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +//Get the associated Products and then display above Terms and Conditions +$smarty->assign("ASSOCIATED_PRODUCTS",getDetailAssociatedProducts('Invoice',$focus)); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$tabid = getTabid("Invoice"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("SinglePane_View", $singlepane_view); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("Inventory/InventoryDetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/DetailViewAjax.php b/oss/vtiger/trunk/modules/Invoice/DetailViewAjax.php new file mode 100644 index 00000000..97801f10 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/DetailViewAjax.php @@ -0,0 +1,46 @@ +retrieve_entity_info($crmid,"Invoice"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Invoice"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/EditView.php b/oss/vtiger/trunk/modules/Invoice/EditView.php new file mode 100644 index 00000000..6a7195ac --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/EditView.php @@ -0,0 +1,387 @@ +assign("SEARCH", $searchurl); +//4600 ends + +$currencyid = fetchCurrency($current_user->id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; +if (isset ($_REQUEST['record']) && $_REQUEST['record'] != '') { + if (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'quotetoinvoice') { + $quoteid = $_REQUEST['record']; + $quote_focus = new Quotes(); + $quote_focus->id = $quoteid; + $quote_focus->retrieve_entity_info($quoteid, "Quotes"); + $focus = getConvertQuoteToInvoice($focus, $quote_focus, $quoteid); + + // Reset the value w.r.t Quote Selected + $currencyid = $quote_focus->column_fields['currency_id']; + $rate = $quote_focus->column_fields['conversion_rate']; + + //Added to display the Quote's associated vtiger_products -- when we create vtiger_invoice from Quotes DetailView + $associated_prod = getAssociatedProducts("Quotes", $quote_focus); + $txtTax = (($quote_focus->column_fields['txtTax'] != '') ? $quote_focus->column_fields['txtTax'] : '0.000'); + $txtAdj = (($quote_focus->column_fields['txtAdjustment'] != '') ? $quote_focus->column_fields['txtAdjustment'] : '0.000'); + + $smarty->assign("CONVERT_MODE", vtlib_purify($_REQUEST['convertmode'])); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $quote_focus->mode); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + } + elseif (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'sotoinvoice') { + $soid = $_REQUEST['record']; + $so_focus = new SalesOrder(); + $so_focus->id = $soid; + $so_focus->retrieve_entity_info($soid, "SalesOrder"); + $focus = getConvertSoToInvoice($focus, $so_focus, $soid); + + // Reset the value w.r.t SalesOrder Selected + $currencyid = $so_focus->column_fields['currency_id']; + $rate = $so_focus->column_fields['conversion_rate']; + + //added to set the PO number and terms and conditions + $focus->column_fields['vtiger_purchaseorder'] = $so_focus->column_fields['vtiger_purchaseorder']; + $focus->column_fields['terms_conditions'] = $so_focus->column_fields['terms_conditions']; + + //Added to display the SalesOrder's associated vtiger_products -- when we create vtiger_invoice from SO DetailView + $associated_prod = getAssociatedProducts("SalesOrder", $so_focus); + $txtTax = (($so_focus->column_fields['txtTax'] != '') ? $so_focus->column_fields['txtTax'] : '0.000'); + $txtAdj = (($so_focus->column_fields['txtAdjustment'] != '') ? $so_focus->column_fields['txtAdjustment'] : '0.000'); + + $smarty->assign("CONVERT_MODE", vtlib_purify($_REQUEST['convertmode'])); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $so_focus->mode); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + + } + elseif (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'potentoinvoice') { + $focus->mode = ''; + } + elseif (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'update_so_val') { + //Updating the Selected SO Value in Edit Mode + foreach ($focus->column_fields as $fieldname => $val) { + if (isset ($_REQUEST[$fieldname])) { + $value = $_REQUEST[$fieldname]; + $focus->column_fields[$fieldname] = $value; + } + + } + //Handling for dateformat in vtiger_invoicedate vtiger_field + if ($focus->column_fields['invoicedate'] != '') { + $curr_due_date = $focus->column_fields['invoicedate']; + $focus->column_fields['invoicedate'] = getDBInsertDateValue($curr_due_date); + } + + $soid = $focus->column_fields['salesorder_id']; + $so_focus = new SalesOrder(); + $so_focus->id = $soid; + $so_focus->retrieve_entity_info($soid, "SalesOrder"); + $focus = getConvertSoToInvoice($focus, $so_focus, $soid); + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->name = $focus->column_fields['subject']; + + // Reset the value w.r.t SalesOrder Selected + $currencyid = $so_focus->column_fields['currency_id']; + $rate = $so_focus->column_fields['conversion_rate']; + } else { + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'], "Invoice"); + $focus->name = $focus->column_fields['subject']; + } +} else { + if (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'update_so_val') { + //Updating the Selected SO Value in Create Mode + foreach ($focus->column_fields as $fieldname => $val) { + if (isset ($_REQUEST[$fieldname])) { + $value = $_REQUEST[$fieldname]; + $focus->column_fields[$fieldname] = $value; + } + + } + //Handling for dateformat in vtiger_invoicedate vtiger_field + if ($focus->column_fields['invoicedate'] != '') { + $curr_due_date = $focus->column_fields['invoicedate']; + $focus->column_fields['invoicedate'] = getDBInsertDateValue($curr_due_date); + } + + $soid = $focus->column_fields['salesorder_id']; + $so_focus = new SalesOrder(); + $so_focus->id = $soid; + $so_focus->retrieve_entity_info($soid, "SalesOrder"); + $focus = getConvertSoToInvoice($focus, $so_focus, $soid); + + // Reset the value w.r.t SalesOrder Selected + $currencyid = $so_focus->column_fields['currency_id']; + $rate = $so_focus->column_fields['conversion_rate']; + + //Added to display the SO's associated products -- when we select SO in New Invoice page + if (isset ($_REQUEST['salesorder_id']) && $_REQUEST['salesorder_id'] != '') { + $associated_prod = getAssociatedProducts("SalesOrder", $so_focus, $focus->column_fields['salesorder_id']); + } + + $smarty->assign("SALESORDER_ID", $focus->column_fields['salesorder_id']); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $so_focus->mode); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + + } +} +if (isset ($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $smarty->assign("DUPLICATE_FROM", $focus->id); + $INVOICE_associated_prod = getAssociatedProducts("Invoice", $focus); + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} +if (isset ($_REQUEST['opportunity_id']) && $_REQUEST['opportunity_id'] != '') { + $potfocus = new Potentials(); + $potfocus->column_fields['potential_id'] = $_REQUEST['opportunity_id']; + $associated_prod = getAssociatedProducts("Potentials", $potfocus, $potfocus->column_fields['potential_id']); + +} +if (isset ($_REQUEST['product_id']) && $_REQUEST['product_id'] != '') { + $focus->column_fields['product_id'] = $_REQUEST['product_id']; + $log->debug("Invoice EditView: Product Id from the request is " . $_REQUEST['product_id']); + $associated_prod = getAssociatedProducts("Products", $focus, $focus->column_fields['product_id']); + for ($i=1; $i<=count($associated_prod);$i++) { + $associated_prod_id = $associated_prod[$i]['hdnProductId'.$i]; + $associated_prod_prices = getPricesForProducts($currencyid,array($associated_prod_id),'Products'); + $associated_prod[$i]['listPrice'.$i] = $associated_prod_prices[$associated_prod_id]; + } + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); +} +if (!empty ($_REQUEST['parent_id']) && !empty ($_REQUEST['return_module'])) { + if ($_REQUEST['return_module'] == 'Services') { + $focus->column_fields['product_id'] = $_REQUEST['parent_id']; + $log->debug("Service Id from the request is " . $_REQUEST['parent_id']); + $associated_prod = getAssociatedProducts("Services", $focus, $focus->column_fields['product_id']); + for ($i=1; $i<=count($associated_prod);$i++) { + $associated_prod_id = $associated_prod[$i]['hdnProductId'.$i]; + $associated_prod_prices = getPricesForProducts($currencyid,array($associated_prod_id),'Services'); + $associated_prod[$i]['listPrice'.$i] = $associated_prod_prices[$associated_prod_id]; + } + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + } +} + +if (isset ($_REQUEST['account_id']) && $_REQUEST['account_id'] != '' && ($_REQUEST['record'] == '' || $_REQUEST['convertmode'] == "potentoinvoice") && ($_REQUEST['convertmode'] != 'update_so_val')) { + require_once ('modules/Accounts/Accounts.php'); + $acct_focus = new Accounts(); + $acct_focus->retrieve_entity_info($_REQUEST['account_id'], "Accounts"); + $focus->column_fields['bill_city'] = $acct_focus->column_fields['bill_city']; + $focus->column_fields['ship_city'] = $acct_focus->column_fields['ship_city']; + $focus->column_fields['bill_street'] = $acct_focus->column_fields['bill_street']; + $focus->column_fields['ship_street'] = $acct_focus->column_fields['ship_street']; + $focus->column_fields['bill_state'] = $acct_focus->column_fields['bill_state']; + $focus->column_fields['ship_state'] = $acct_focus->column_fields['ship_state']; + $focus->column_fields['bill_code'] = $acct_focus->column_fields['bill_code']; + $focus->column_fields['ship_code'] = $acct_focus->column_fields['ship_code']; + $focus->column_fields['bill_country'] = $acct_focus->column_fields['bill_country']; + $focus->column_fields['ship_country'] = $acct_focus->column_fields['ship_country']; + $focus->column_fields['bill_pobox'] = $acct_focus->column_fields['bill_pobox']; + $focus->column_fields['ship_pobox'] = $acct_focus->column_fields['ship_pobox']; + +} + +global $theme; +$theme_path = "themes/" . $theme . "/"; +$image_path = $theme_path . "images/"; + +$disp_view = getView($focus->mode); +$mode = $focus->mode; +if ($disp_view == 'edit_view') + $smarty->assign("BLOCKS", getBlocks($currentModule, $disp_view, $mode, $focus->column_fields)); +else { + $bas_block = getBlocks($currentModule, $disp_view, $mode, $focus->column_fields, 'BAS'); + $adv_block = getBlocks($currentModule, $disp_view, $mode, $focus->column_fields, 'ADV'); + + $blocks['basicTab'] = $bas_block; + if (is_array($adv_block)) + $blocks['moreTab'] = $adv_block; + + $smarty->assign("BLOCKS", $blocks); + $smarty->assign("BLOCKS_COUNT", count($blocks)); +} + +$smarty->assign("OP_MODE", $disp_view); + +$smarty->assign("MODULE", $currentModule); +$smarty->assign("SINGLE_MOD", 'Invoice'); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$log->info("Invoice view"); + +if (isset ($focus->name)) + $smarty->assign("NAME", $focus->name); +else + $smarty->assign("NAME", ""); + +if (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'quotetoinvoice') { + $smarty->assign("MODE", $quote_focus->mode); + $se_array = getProductDetailsBlockInfo($quote_focus->mode, "Quotes", $quote_focus); +} +elseif (isset ($_REQUEST['convertmode']) && ($_REQUEST['convertmode'] == 'sotoinvoice' || $_REQUEST['convertmode'] == 'update_so_val')) { + $smarty->assign("MODE", $focus->mode); + $se_array = getProductDetailsBlockInfo($focus->mode, "SalesOrder", $so_focus); + + $txtTax = (($so_focus->column_fields['txtTax'] != '') ? $so_focus->column_fields['txtTax'] : '0.000'); + $txtAdj = (($so_focus->column_fields['txtAdjustment'] != '') ? $so_focus->column_fields['txtAdjustment'] : '0.000'); + + $associated_prod = getAssociatedProducts("SalesOrder", $so_focus); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $focus->mode); +} +elseif ($focus->mode == 'edit') { + $smarty->assign("UPDATEINFO", updateInfo($focus->id)); + $associated_prod = getAssociatedProducts("Invoice", $focus); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $focus->mode); +} +elseif (isset ($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $associated_prod = $INVOICE_associated_prod; + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + $smarty->assign("MODE", $focus->mode); +} +elseif ((isset ($_REQUEST['product_id']) && $_REQUEST['product_id'] != '') || (isset ($_REQUEST['opportunity_id']) && $_REQUEST['opportunity_id'] != '')) { + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $InvTotal = getInventoryTotal($_REQUEST['return_module'], $_REQUEST['return_id']); + $smarty->assign("MODE", $focus->mode); + + //this is to display the Product Details in first row when we create new PO from Product relatedlist + if ($_REQUEST['return_module'] == 'Products') { + $smarty->assign("PRODUCT_ID", vtlib_purify($_REQUEST['product_id'])); + $smarty->assign("PRODUCT_NAME", getProductName($_REQUEST['product_id'])); + $smarty->assign("UNIT_PRICE", vtlib_purify($_REQUEST['product_id'])); + $smarty->assign("QTY_IN_STOCK", getPrdQtyInStck($_REQUEST['product_id'])); + $smarty->assign("VAT_TAX", getProductTaxPercentage("VAT", $_REQUEST['product_id'])); + $smarty->assign("SALES_TAX", getProductTaxPercentage("Sales", $_REQUEST['product_id'])); + $smarty->assign("SERVICE_TAX", getProductTaxPercentage("Service", $_REQUEST['product_id'])); + } +} + +if (isset ($cust_fld)) { + $smarty->assign("CUSTOMFIELD", $cust_fld); +} + +$smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + +if (isset ($_REQUEST['return_module'])) + $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else + $smarty->assign("RETURN_MODULE", "Invoice"); +if (isset ($_REQUEST['return_action'])) + $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else + $smarty->assign("RETURN_ACTION", "index"); +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=" . session_id() . $GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +//in create new Invoice, get all available product taxes and shipping & Handling taxes + +if ($focus->mode != 'edit') { + $tax_details = getAllTaxes('available'); + $sh_tax_details = getAllTaxes('available', 'sh'); +} else { + $tax_details = getAllTaxes('available', '', $focus->mode, $focus->id); + $sh_tax_details = getAllTaxes('available', 'sh', 'edit', $focus->id); +} +$smarty->assign("GROUP_TAXES", $tax_details); +$smarty->assign("SH_TAXES", $sh_tax_details); + +$tabid = getTabid("Invoice"); +$validationData = getDBValidationData($focus->tab_name, $tabid); +$data = split_validationdataArray($validationData); +$category = getParentTab(); +$smarty->assign("CATEGORY", $category); + +$smarty->assign("VALIDATION_DATA_FIELDNAME", $data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE", $data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL", $data['fieldlabel']); + +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 '
    ' . getTranslatedString('LBL_DUPLICATE') . ' ' . getTranslatedString($mod_seq_field['label']) . + ' - ' . getTranslatedString('LBL_CLICK') . ' ' . getTranslatedString('LBL_HERE') . ' ' . getTranslatedString('LBL_TO_CONFIGURE') . ' ' . getTranslatedString($mod_seq_field['label']) . ''; + else + $smarty->assign("MOD_SEQ_ID", $autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +$smarty->assign("CURRENCIES_LIST", getAllCurrencies()); +if ($focus->mode == 'edit' || $_REQUEST['isDuplicate'] == 'true') { + $inventory_cur_info = getInventoryCurrencyInfo('Invoice', $focus->id); + $smarty->assign("INV_CURRENCY_ID", $inventory_cur_info['currency_id']); +} else { + $smarty->assign("INV_CURRENCY_ID", $currencyid); +} + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); +if ($focus->mode == 'edit') + $smarty->display("Inventory/InventoryEditView.tpl"); +else + $smarty->display('Inventory/InventoryCreateView.tpl'); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/Invoice.js b/oss/vtiger/trunk/modules/Invoice/Invoice.js new file mode 100644 index 00000000..d1c18bda --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/Invoice.js @@ -0,0 +1,55 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + +document.write(""; +exit(); +?> diff --git a/oss/vtiger/trunk/modules/Invoice/Settings.php b/oss/vtiger/trunk/modules/Invoice/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Invoice/TagCloud.php b/oss/vtiger/trunk/modules/Invoice/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Invoice/UnifiedSearch.php b/oss/vtiger/trunk/modules/Invoice/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Invoice/index.php b/oss/vtiger/trunk/modules/Invoice/index.php new file mode 100644 index 00000000..986c4aa8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/index.php @@ -0,0 +1,52 @@ + diff --git a/oss/vtiger/trunk/modules/Invoice/language/en_us.lang.php b/oss/vtiger/trunk/modules/Invoice/language/en_us.lang.php new file mode 100644 index 00000000..e180996c --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/language/en_us.lang.php @@ -0,0 +1,201 @@ +'Invoice', +'LBL_SO_MODULE_NAME'=>'Invoice', +'LBL_RELATED_PRODUCTS'=>'Product Details', +'LBL_MODULE_TITLE'=>'Invoice: Home', +'LBL_SEARCH_FORM_TITLE'=>'Invoice Search', +'LBL_LIST_FORM_TITLE'=>'Invoice List', +'LBL_LIST_SO_FORM_TITLE'=>'Sales Order List', +'LBL_NEW_FORM_TITLE'=>'New Invoice', +'LBL_NEW_FORM_SO_TITLE'=>'New Sales Order', +'LBL_MEMBER_ORG_FORM_TITLE'=>'Member Organizations', + +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_LIST_CITY'=>'City', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_STATE'=>'State', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_EMAIL_ADDRESS'=>'Email Address', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'Account:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_PHONE'=>'Phone:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_TICKER_SYMBOL'=>'Ticker Symbol:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_MEMBER_OF'=>'Member of:', +'LBL_EMAIL'=>'Email:', +'LBL_EMPLOYEES'=>'Employees:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_OWNERSHIP'=>'Ownership:', +'LBL_RATING'=>'Rating:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_SIC_CODE'=>'SIC Code:', +'LBL_TYPE'=>'Type:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_Quote_INFORMATION'=>'Account Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_BILLING_ADDRESS'=>'Billing Address:', +'LBL_SHIPPING_ADDRESS'=>'Shipping Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_DESCRIPTION'=>'Description:', +'LBL_TERMS_INFORMATION'=>'Terms & Conditions', +'NTC_COPY_BILLING_ADDRESS'=>'Copy billing address to shipping address', +'NTC_COPY_SHIPPING_ADDRESS'=>'Copy shipping address to billing address', +'NTC_REMOVE_MEMBER_ORG_CONFIRMATION'=>'Are you sure you want to remove this record as a member organization?', +'LBL_DUPLICATE'=>'Potential Duplicate Accounts', +'MSG_DUPLICATE' => 'Creating this vtiger_account may vtiger_potentialy create a duplicate vtiger_account. You may either select an vtiger_account from the list below or you may click on Create New Account to continue creating a new vtiger_account with the previously entered data.', + +'LBL_INVITEE'=>'Contacts', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", + +'LBL_SELECT_ACCOUNT'=>'Select Account', +'LBL_GENERAL_INFORMATION'=>'General Information', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_PROSPECT'=>'Prospect', +'LBL_INVESTOR'=>'Investor', +'LBL_RESELLER'=>'Reseller', +'LBL_PARTNER'=>'Partner', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Account Tools', +//Added for 4GA +'Subject'=>'Subject', +'Quote Name'=>'Quote Name', +'Vendor Name'=>'Vendor Name', +'Invoice Terms'=>'Invoice Terms', +'Contact Name'=>'Contact Name',//to include contact name vtiger_field in Invoice +'Invoice Date'=>'Invoice Date', +'Sub Total'=>'Sub Total', +'Due Date'=>'Due Date', +'Carrier'=>'Carrier', +'Type'=>'Type', +'Sales Tax'=>'Sales Tax', +'Sales Commission'=>'Sales Commission', +'Excise Duty'=>'Excise Duty', +'Total'=>'Total', +'Product Name'=>'Product Name', +'Assigned To'=>'Assigned To', +'Billing Address'=>'Billing Address', +'Shipping Address'=>'Shipping Address', +'Billing City'=>'Billing City', +'Billing State'=>'Billing State', +'Billing Code'=>'Billing Postal Code', +'Billing Country'=>'Billing Country', +'Billing Po Box'=>'Billing PO Box', +'Shipping Po Box'=>'Shipping PO Box', +'Shipping City'=>'Shipping City', +'Shipping State'=>'Shipping State', +'Shipping Code'=>'Shipping Postal Code', +'Shipping Country'=>'Shipping Country', +'City'=>'City', +'State'=>'State', +'Code'=>'Code', +'Country'=>'Country', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Description'=>'Description', +'Potential Name'=>'Potential Name', +'Customer No'=>'Customer No', +'Sales Order'=>'Sales Order', +'Pending'=>'Pending', +'Account Name'=>'Account Name', +'Terms & Conditions'=>'Terms & Conditions', +//Quote Info +'LBL_INVOICE_INFORMATION'=>'Invoice Information', +'LBL_INVOICE'=>'Invoice:', +'LBL_SO_INFORMATION'=>'Sales Order Information', +'LBL_SO'=>'Sales Order:', + +//Added in release 4.2 +'LBL_SUBJECT'=>'Subject:', +'LBL_SALES_ORDER'=>'Sales order:', +'Invoice Id'=>'Invoice Id', +'LBL_MY_TOP_INVOICE'=>'My Top Open Invoice', +'LBL_INVOICE_NAME'=>'Invoice Name:', +'Purchase Order'=>'Purchase Order', +'Status'=>'Status', +'Id'=>'Invoice Id', +'Invoice'=>'Invoice', + +//Added for existing Picklist Entries + +'Created'=>'Created', +'Approved'=>'Approved', +'Sent'=>'Sent', +'Credit Invoice'=>'Credit Invoice', +'Paid'=>'Paid', +//Added to Custom Invoice Number +'Invoice No'=>'Invoice No', +'Adjustment'=>'Adjustment', + +//Added for Reports (5.0.4) +'Tax Type'=>'Tax Type', +'Discount Percent'=>'Discount Percent', +'Discount Amount'=>'Discount Amount', +'Terms & Conditions'=>'Terms & Conditions', +'No'=>'No', +'Date'=>'Date', + +// Added affter 5.0.4 GA +//Added for Documents module +'Documents'=>'Documents', +); + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Invoice/language/zh_cn.lang.php new file mode 100644 index 00000000..32fa6db2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/language/zh_cn.lang.php @@ -0,0 +1,200 @@ + '发票', + 'LBL_SO_MODULE_NAME' => '发票', + 'LBL_RELATED_PRODUCTS' => '在线清单', + 'LBL_MODULE_TITLE' => '发票:首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻发票', + 'LBL_LIST_FORM_TITLE' => '发票列表', + 'LBL_LIST_SO_FORM_TITLE' => '销售列表', + 'LBL_NEW_FORM_TITLE' => '新增发票', + 'LBL_NEW_FORM_SO_TITLE' => '新增销售', + 'LBL_MEMBER_ORG_FORM_TITLE' => '会员所属单位', + +'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_LIST_CITY' => '乡镇市区', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '市(县)', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件', + 'LBL_LIST_CONTACT_NAME' => '联络人名称', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + + 'LBL_ACCOUNT' => '客户:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_PHONE' => '电话:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_TICKER_SYMBOL' => '传票符号:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_ANY_PHONE' => '其它电话:', + 'LBL_MEMBER_OF' => '会员:', + 'LBL_EMAIL' => '电子信箱:', + 'LBL_EMPLOYEES' => '员工数:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子信箱:', + 'LBL_ANY_EMAIL' => '其它电子信箱:', + 'LBL_OWNERSHIP' => '负责人:', + 'LBL_RATING' => '评分:', +'LBL_INDUSTRY' => '产业别:', + 'LBL_SIC_CODE' => '统一编号:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年收入:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_Quote_INFORMATION' => '客户信息', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + 'LBL_BILLING_ADDRESS' => '发票地址:', + 'LBL_SHIPPING_ADDRESS' => '送货地址:', + 'LBL_ANY_ADDRESS' => '任一地址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '市(县):', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '省(市/自治区):', + 'LBL_DESCRIPTION_INFORMATION' => '细节内容', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_TERMS_INFORMATION' => '限制与条件', + 'NTC_COPY_BILLING_ADDRESS' => '复制发票地址到送货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '复制送货地址到发票地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '您确定要移除这笔会员所属单位记录?', + 'LBL_DUPLICATE' => '潜在案件内容复制到客户', + 'MSG_DUPLICATE' => '建立这笔客户数据来自于潜在案件内容,您可以点选客户列表中的客户以复制建立新的客户,并且继承它的相关数据。', + + 'LBL_INVITEE' => '联络人', + 'ERR_DELETE_RECORD' => '必须指定一笔记录编号才能够删除客户。', + 'LBL_SELECT_ACCOUNT' => '选择客户', + 'LBL_GENERAL_INFORMATION' => '一般信息', + +//for v4 release added + 'LBL_NEW_POTENTIAL' => '新增潜在案件', + 'LBL_POTENTIAL_TITLE' => '潜在案件', + + 'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议记录', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '邮件', + 'LBL_NEW_CONTACT' => '新增联络人', + 'LBL_CONTACT_TITLE' => '联络人', + +//Added vtiger_fields after RC1 - Release + 'LBL_ALL' => '全部', + 'LBL_PROSPECT' => '期望', + 'LBL_INVESTOR' => '投资者', + 'LBL_RESELLER' => '转售人', + 'LBL_PARTNER' => '伙伴', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '客户工具', +//Added for 4GA + 'Subject' => '标题', + 'Quote Name' => '报价名称', + 'Vendor Name' => '卖方名称', + 'Invoice Terms' => '发票期限', + 'Contact Name' => '联络人名称',//to include contact name vtiger_field in Invoice + 'Invoice Date' => '发票日期', + 'Sub Total' => '小计', + 'Due Date' => '应付日期', + 'Carrier' => '货运商', + 'Type' => '类型', + 'Sales Tax' => '销售税金', + 'Sales Commission' => '销售佣金', + 'Excise Duty' => '营业税', + 'Total' => '总计 ', + 'Product Name' => '商品名称', + 'Assigned To' => '负责人', + 'Billing Address' => '发票地址', + 'Shipping Address' => '送货地址', + 'Billing City' => '[发票地址]乡镇市区', + 'Billing State' => '[发票地址]市(县)', + 'Billing Code' => '[发票地址]邮政编码', + 'Billing Country' => '[发票地址]省(市/自治区)', + 'Billing Po Box' => '[发票地址]邮政信箱', + 'Shipping Po Box' => '[送货地址]邮政信箱', + 'Shipping City' => '[送货地址]乡镇市区', + 'Shipping State' => '[送货地址]市(县)', + 'Shipping Code' => '[送货地址]邮政编码', + 'Shipping Country' => '[送货地址]省(市/自治区)', +'City' => '乡镇市区', + 'State' => '市(县)', + 'Code' => '邮政编码', + 'Country' => '省(市/自治区)', + 'Created Time' => '建档时间', + 'Modified Time' => '修改时间', + 'Description' => '细节内容', + 'Potential Name' => '潜在案件名称', + 'Customer No' => '客户编号', + 'Sales Order' => '销售', + 'Notes' => '备忘录', + 'Pending' => '期间', + 'Account Name' => '客户名称', + 'Terms & Conditions' => '限制与条件', +//Quote Info + 'LBL_INVOICE_INFORMATION' => '发票信息', + 'LBL_INVOICE' => '发票:', + 'LBL_SO_INFORMATION' => '销售订单信息', + 'LBL_SO' => '销售订单:', + +//Added in release 4.2 + 'LBL_SUBJECT' => '主旨:', + 'LBL_SALES_ORDER' => '销售订单:', + 'Invoice Id' => '发票号码', + 'LBL_MY_TOP_INVOICE' => '自己未处理的发票', + 'LBL_INVOICE_NAME' => '发票名称:', + 'Purchase Order' => '采购订单', + 'Status' => '状态', + 'Id' => '发票编号', + 'Invoice' => '发票', + +//Added for existing Picklist Entries + + 'Created' => '已建立', + 'Approved' => '已审核', + 'Sent' => '已寄送', + 'Credit Invoice' => '贷方发票', + 'Paid' => '已付款', +//Added to Custom Invoice Number +'Invoice No'=>'发票号码', +'Adjustment'=>'调整', +//Added for Reports (5.0.4) +'Tax Type'=>'Tax Type', +'Discount Percent'=>'Discount Percent', +'Discount Amount'=>'Discount Amount', +'Terms & Conditions'=>'Terms & Conditions', +'No'=>'No', +'Date'=>'Date', + +// Added affter 5.0.4 GA +//Added for Documents module +'Documents'=>'Documents', +); + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/pdf_templates/footer.php b/oss/vtiger/trunk/modules/Invoice/pdf_templates/footer.php new file mode 100644 index 00000000..e5b2b016 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/pdf_templates/footer.php @@ -0,0 +1,35 @@ +addDescBlock($description, $app_strings["Description"], $descBlock); + +/* ************** End Description *********************** */ + + + +/* **************** Begin Terms ****************** */ +$termBlock=array("107",$top,"53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/pdf_templates/header.php b/oss/vtiger/trunk/modules/Invoice/pdf_templates/header.php new file mode 100644 index 00000000..5965594a --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/pdf_templates/header.php @@ -0,0 +1,104 @@ +addImage( $logo_name, $imageBlock); + +// x,y,width +if($org_phone != '') + $phone ="\n".$app_strings["Phone"].":".$org_phone; + +$companyBlockPositions=array( "10","23","62" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone."\n".$org_website; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + +// ************** End company information ******************* + + + +// ************* Begin Top-Right Header *************** +// title +$titleBlock=array("147","7"); +$pdf->title( $app_strings["Invoice"],"", $titleBlock ); + +$soBubble=array("168","17","12"); +$pdf->addBubbleBlock($so_name, $app_strings["SalesOrder"], $soBubble); + +$poBubble=array("114","17","12"); +$pdf->addBubbleBlock($po_name, $app_strings["PurchaseOrder"], $poBubble); + +// page number +$pageBubble=array("147","17",0); +$pdf->addBubbleBlock($page_num, $app_strings["Page"], $pageBubble); +// ************** End Top-Right Header ***************** + + + +// ************** Begin Addresses ************** +// shipping Address +$shipLocation = array("147","40","61"); +if(trim($ship_street)!='') + $shipText = $ship_street."\n"; +if(trim($ship_city) !='') + $shipText .= $ship_city.", "; +if(trim($ship_state)!='' || trim($ship_code)!= '') + $shipText .= $ship_state." ".$ship_code."\n"; + + $shipText .=$ship_country; + +$pdf->addTextBlock( $app_strings["Shipping Address"].":", $shipText, $shipLocation ); + +// billing Address +$billPositions = array("10","51","61"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); +// ********** End Addresses ****************** + + + +/* ******** Begin Invoice Data ************************ */ +// terms block +$termBlock=array("10","67"); +$pdf->addRecBlock($account_name, $app_strings["Customer Name"], $termBlock); + +// issue date block +$issueBlock=array("80","37"); +$pdf->addRecBlock(getDisplayDate(date("Y-m-d")), $app_strings["Issue Date"],$issueBlock); + +// due date block +$dueBlock=array("81","52"); +$pdf->addRecBlock($valid_till, $app_strings["Due Date"],$dueBlock); + +// Contact Name block +$conBlock=array("79","67"); +$pdf->addRecBlock($contact_name, $app_strings["Contact Name"],$conBlock); + +// vtiger_invoice number block +$invBlock=array("145","67"); +$pdf->addRecBlock($invoice_no, $app_strings["Invoice Number"],$invBlock); + +/* ************ End Invoice Data ************************ */ + + + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/pdf_templates/lastpage/body.php b/oss/vtiger/trunk/modules/Invoice/pdf_templates/lastpage/body.php new file mode 100644 index 00000000..fc4720c1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/pdf_templates/lastpage/body.php @@ -0,0 +1,62 @@ +watermark( $app_strings["Thank You"], $waterMarkPositions, $waterMarkRotate ); +$waterMarkPositions=array("30","130"); +$pdf->watermark( $app_strings["For Your Business"], $waterMarkPositions, $waterMarkRotate ); + +// blowing bubbles +$Bubble=array("10","80","170","4"); +$pdf->addBubble("", "", $Bubble); + +$Bubble=array("168","131","12"); +//$pdf->addBubbleBlock("Neat Look", "For A", $Bubble); +$Bubble=array("10","131","12"); +//$pdf->addBubbleBlock("The Corners", "Line Up", $Bubble); + + +/* ************* Begin Totals ************************** */ +$totalBlock=array("59","135"); +$names=array($app_strings["Subtotal"],$app_strings["Tax"],$app_strings["Adjustment"],$app_strings["Total"]); +$totals=array($price_subtotal,$price_salestax,$price_adjustment,$price_total); +$pdf->addTotalsRec($names,$totals,$totalBlock); +/* ************* End Totals *************************** */ + +// lets add an image :) +$imageBlock=array("15","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); +$imageBlock=array("185","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); + +// descriptions that change sizes! +$descc=count(explode("\n",$description)); +$condc=count(explode("\n",$conditions)); +if( (strlen($description) > 256) || (strlen($conditions) > 256) || $condc >6 || $descc > 6 ) + $num=255; +else + $num=150; + +/* **************** Begin Description ****************** */ +$descBlock=array("10","160","53", $num); +$pdf->addDescBlock($description, $app_strings["Description"], $descBlock); + + +$termBlock=array("107","160","53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/pdf_templates/lastpage/footer.php b/oss/vtiger/trunk/modules/Invoice/pdf_templates/lastpage/footer.php new file mode 100644 index 00000000..67de6bfb --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/pdf_templates/lastpage/footer.php @@ -0,0 +1,59 @@ +drawLine($linePos); + $i = (($i+$width)+$pad)-1; +} + +// company addy +if($org_phone != '') +$phone="\n".$app_strings["Phone"].": ".$org_phone; +if($org_fax != '') + $fax ="\nFax: ".$org_fax; +$companyBlockPositions=array( "10","220","60" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone." ".$fax."\n".$org_website ; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + + +// billing Address +$billPositions = array("85","235","60"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); + +// totals +$totalBlock=array("145","235","10", "110"); +$totalText=$app_strings["Subtotal"].": ".$price_subtotal."\n". + $app_strings["Tax"].": ".$price_salestax."\n". + $app_strings["Adjustment"].": ".$price_adjustment."\n". + $app_strings["Total"].": ".$price_total; +$pdf->addDescBlock($totalText, $app_strings["Total Due"], $totalBlock); + +$blurbBlock=array("10","265","150", "60"); +$blockText=$app_strings["Detach_Info"]; +$pdf->addDescBlock($blockText, $app_strings["Instructions"], $blurbBlock); + +?> diff --git a/oss/vtiger/trunk/modules/Invoice/updateRelations.php b/oss/vtiger/trunk/modules/Invoice/updateRelations.php new file mode 100644 index 00000000..85798501 --- /dev/null +++ b/oss/vtiger/trunk/modules/Invoice/updateRelations.php @@ -0,0 +1,48 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/CallRelatedList.php b/oss/vtiger/trunk/modules/Leads/CallRelatedList.php new file mode 100644 index 00000000..f2945827 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/CallRelatedList.php @@ -0,0 +1,103 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->firstname=$focus->column_fields['firstname']; + $focus->lastname=$focus->column_fields['lastname']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings; + global $theme; + global $currentModule; + global $current_user; + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + + if(!$_SESSION['rlvs'][$module]) + { + unset($_SESSION['rlvs']); + } + + if(isset($_REQUEST['record']) && $_REQUEST['record']!='') + { + $userid = $current_user->id; + $sql = "select fieldname from vtiger_field where uitype = '13' and tabid = 7 and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array()); + $num_fieldnames = $adb->num_rows($result); + for($i = 0; $i < $num_fieldnames; $i++) + { + $fieldname = $adb->query_result($result,$i,"fieldname"); + $permit= getFieldVisibilityPermission("Leads",$userid,$fieldname); + } + } + + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("CATEGORY",$category); + $parent_email = getEmailParentsList('Leads',$focus->id, $focus); + $smarty->assign("HIDDEN_PARENTS_LIST",$parent_email); + + // 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 + + $smarty->assign("ID",$focus->id); + $smarty->assign("NAME",$focus->lastname.' '.$focus->firstname); + $smarty->assign("EMAIL",$focus->column_fields['email']); + $smarty->assign("YAHOO",$focus->column_fields['yahooid']); + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("SINGLE_MOD",$app_strings['Lead']); + $smarty->assign("MODULE", $currentmodule); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/ConvertLead.php b/oss/vtiger/trunk/modules/Leads/ConvertLead.php new file mode 100644 index 00000000..462b6470 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/ConvertLead.php @@ -0,0 +1,272 @@ +debug(" the id is ".$id); +} +$category = getParentTab(); +//Retreive lead details from database +$sql = "SELECT firstname, lastname, company, smownerid from vtiger_leaddetails inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid where vtiger_leaddetails.leadid =?"; +$result = $adb->pquery($sql, array($id)); +$row = $adb->fetch_array($result); + +//if company field is not present +if(getFieldVisibilityPermission('Leads',$current_user->id,'company') == '1'){ + $row["company"] = ''; +} + +$firstname = $row["firstname"]; +$lastname = $row["lastname"]; +$company = $row["company"]; +$potentialname = $row["company"] ."-"; +$userid = $row["smownerid"]; + +//Retreiving the current user id +$modified_user_id = $current_user->id; +$log->info("Convert Lead view"); + +$date_format = parse_calendardate($app_strings['NTC_DATE_FORMAT']); + +$roleid=$current_user->roleid; +$subrole = getRoleSubordinates($roleid); +if(count($subrole)> 0) +{ + $roleids = $subrole; + array_push($roleids, $roleid); +} +else +{ + $roleids = $roleid; +} +if($sortid != '') { + $sales_stage_query="select sales_stage from vtiger_sales_stage"; + $params = array(); +} +elseif($is_admin) +{ + $sales_stage_query="select sales_stage from vtiger_sales_stage inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_sales_stage.picklist_valueid where roleid != 'H1' order by sortid"; + $params = array(); +}else +{ + if (count($roleids) > 0) { + $sales_stage_query="select sales_stage from vtiger_sales_stage inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_sales_stage.picklist_valueid where roleid in (". generateQuestionMarks($roleids) .") and picklistid in (select picklistid from vtiger_sales_stage) order by sortid"; + $params = array($roleids); + } else { + $sales_stage_query="select sales_stage from vtiger_sales_stage inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_sales_stage.picklist_valueid where picklistid in (select picklistid from vtiger_sales_stage) order by sortid"; + $params = array(); + } +} +$sales_stage_result = $adb->pquery($sales_stage_query, $params); +$noofsalesRows = $adb->num_rows($sales_stage_result); +$sales_stage_fld = ''; +$sales_stage_list[] = array(); +for($j = 0; $j < $noofsalesRows; $j++) +{ + + $sales_stageValue=$adb->query_result($sales_stage_result,$j,strtolower(sales_stage)); + if(in_array($sales_stageValue,$sales_stage_list)) continue; + $sales_stage_list[] = $sales_stageValue; + if($value == $sales_stageValue) + { + $chk_val = "selected"; + } + else + { + $chk_val = ''; + } + + $sales_stage_fld.= ''; +} +function isActive($field,$mod){ + global $adb,$theme; + $tabid = getTabid($mod); + $query = 'select * from vtiger_field where fieldname = ? and tabid = ? and presence in (0,2)'; + $res = $adb->pquery($query,array($field,$tabid)); + $rows = $adb->num_rows($res); + if($rows > 0){ + return true; + }else + return false; +} +$userselected = ''; +$groupselected = ''; +$userdisplay = 'none'; +$groupdisplay = 'none'; +$private = ''; +if($userid != ''){ + global $adb; + $query = "SELECT * from vtiger_users WHERE id = ?"; + $res = $adb->pquery($query,array($userid)); + $rows = $adb->num_rows($res); + if($rows > 0){ + $userselected = 'checked'; + $userdisplay= 'block'; + }else{ + $groupselected = 'checked'; + $groupdisplay= 'block'; + } +} + +if($current_user->id != 1){ + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $Acc_tabid= getTabid('Accounts'); + $con_tabid = getTabid('Contacts'); + if($defaultOrgSharingPermission[$Acc_tabid] === 0 || $defaultOrgSharingPermission[$Acc_tabid] == 3){ + $private = 'private'; + }elseif($defaultOrgSharingPermission[$con_tabid] === 0 || $defaultOrgSharingPermission[$con_tabid] == 3){ + $private = 'private'; + } +} + +$convertlead = '
    + + + + + + +
    + + + + + +
    '.$mod_strings['LBL_CONVERT_LEAD'].' '.$firstname.' '.$lastname.'
    + + + + + +
    + + + + + + + + '; + + if(vtlib_isModuleActive('Accounts') && (isPermitted('Accounts','EditView')== 'yes')){ + $convertlead .= ' + + + '; + } +if(vtlib_isModuleActive('Potentials') && (isPermitted('Potentials','EditView')== 'yes')){ +// An array which as module => fields mapping, to check for field permissions +$fields_list = array( 'Potentials'=> array('potentialname', 'closingdate', 'amount', 'sales_stage')); +$fields_permission = array(); +foreach($fields_list as $mod=>$fields){ + foreach($fields as $key=>$field) { + if(getFieldVisibilityPermission($mod, $current_user->id, $field)=='0' && (isActive($field,$mod) == true)){ + $fields_permission[$field] = '0'; + $potTabid = getTabid('Potentials'); + global $adb; + $query = 'select typeofdata from vtiger_field where fieldname = ? and tabid = ?'; + $res = $adb->pquery($query,array($field,$potTabid)); + $type = $adb->query_result($res,0,'typeofdata'); + if(strpos($type,'M')){ + $mandatory[$field] = '*'; + } + } + else + $fields_permission[$field] = '1'; + } +} + +$convertlead .=' + + + + + + '; + +} +$convertlead .='
    '.$mod_strings['LBL_CONVERT_LEAD_INFORMATION'].'
    '.$app_strings['LBL_ASSIGNED_TO'].' +  '.$app_strings['LBL_USER'].' +  '.$app_strings['LBL_GROUP'].' + + + + + + +
    '.$mod_strings['LBL_ACCOUNT_NAME'].'
    '.$mod_strings['LBL_DO_NOT_CREATE_NEW_POTENTIAL'].'
    +
    + '; + if($fields_permission['potentialname']=='0') { + + $convertlead .= ' + + + '; + } + if($fields_permission['closingdate']=='0') { + $convertlead .= ' + + + '; + } + if($fields_permission['amount']=='0') { + $convertlead .= ' + + + '; + } + if($fields_permission['sales_stage']=='0') { + $convertlead .=' + + + '; + } + $convertlead .='
    '.$mandatory['potentialname'].''.$mod_strings['LBL_POTENTIAL_NAME'].' + + +
    '.$mandatory['closingdate'].''.$mod_strings['LBL_POTENTIAL_CLOSE_DATE'].' + + + + ('.$current_user->date_format.') + +
    '.$mandatory['amount'].''.$mod_strings['LBL_POTENTIAL_AMOUNT'].' + + '.$potential_amount.'
    '.$mandatory['sales_stage'].''.$mod_strings['LBL_POTENTIAL_SALES_STAGE'].' + +
    +
    +
    +
    + + + + +
    +    + +
    +
    '; +echo $convertlead; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/CustomAction.php b/oss/vtiger/trunk/modules/Leads/CustomAction.php new file mode 100644 index 00000000..f72082d0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/CustomAction.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/CustomView.php b/oss/vtiger/trunk/modules/Leads/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/Delete.php b/oss/vtiger/trunk/modules/Leads/Delete.php new file mode 100644 index 00000000..2f7b16bf --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/Delete.php @@ -0,0 +1,39 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/DetailView.php b/oss/vtiger/trunk/modules/Leads/DetailView.php new file mode 100644 index 00000000..ee12e74f --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/DetailView.php @@ -0,0 +1,179 @@ +id = $_REQUEST['record']; + + $focus->retrieve_entity_info($_REQUEST['record'],"Leads"); + $focus->id = $_REQUEST['record']; + $log->debug("id is ".$focus->id); + $focus->firstname=$focus->column_fields['firstname']; + $focus->lastname=$focus->column_fields['lastname']; + +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +global $theme,$current_user; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Lead detail view"); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $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 + +$smarty->assign("SINGLE_MOD", 'Lead'); + +$lead_name = $focus->lastname; +if (getFieldVisibilityPermission($currentModule, $current_user->id,'firstname') == '0') { + $lead_name .= ' '.$focus->firstname; +} +$smarty->assign("NAME",$lead_name ); + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); +$smarty->assign("CUSTOMFIELD", $cust_fld); + +if(useInternalMailer() == 1) + $smarty->assign("INT_MAILER","true"); + + +$val = isPermitted("Leads","EditView",$_REQUEST['record']); + +if(isPermitted("Leads","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("Leads","EditView",$_REQUEST['record']) == 'yes' && isPermitted("Leads","ConvertLead") =='yes' && (isPermitted("Accounts","EditView") =='yes' || isPermitted("Contacts","EditView") == 'yes') && (vtlib_isModuleActive('Contacts') || vtlib_isModuleActive('Accounts'))) +{ + $smarty->assign("CONVERTLEAD","permitted"); +} + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + + +if(isPermitted("Leads","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +if(isPermitted("Emails","EditView",'') == 'yes') +{ + //Added to pass the parents list as hidden for Emails -- 09-11-2005 + $parent_email = getEmailParentsList('Leads',$_REQUEST['record'], $focus); + $smarty->assign("HIDDEN_PARENTS_LIST",$parent_email); + $smarty->assign("SENDMAILBUTTON","permitted"); + $smarty->assign("EMAIL1",$focus->column_fields['email']); + $smarty->assign("EMAIL2",$focus->column_fields['yahooid']); + +} + +if(isPermitted("Leads","Merge",'') == 'yes') +{ + global $current_user; + require("user_privileges/user_privileges_".$current_user->id.".php"); + + $wordTemplateResult = fetchWordTemplateList("Leads"); + $tempCount = $adb->num_rows($wordTemplateResult); + $tempVal = $adb->fetch_array($wordTemplateResult); + for($templateCount=0;$templateCount<$tempCount;$templateCount++) + { + $optionString[$tempVal["templateid"]] =$tempVal["filename"]; + $tempVal = $adb->fetch_array($wordTemplateResult); + } + if($is_admin) + $smarty->assign("MERGEBUTTON","permitted"); + elseif($tempCount >0) + $smarty->assign("MERGEBUTTON","permitted"); + + $smarty->assign("TEMPLATECOUNT",$tempCount); + $smarty->assign("WORDTEMPLATEOPTIONS",$app_strings['LBL_SELECT_TEMPLATE_TO_MAIL_MERGE']); + $smarty->assign("TOPTIONS",$optionString); +} + +$tabid = getTabid("Leads"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$smarty->assign("MODULE", $currentModule); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); +$smarty->assign("USE_ASTERISK", get_use_asterisk($current_user->id)); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} +$smarty->assign("SinglePane_View", $singlepane_view); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +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)); + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("DetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/DetailViewAjax.php b/oss/vtiger/trunk/modules/Leads/DetailViewAjax.php new file mode 100644 index 00000000..d3de34ce --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/DetailViewAjax.php @@ -0,0 +1,45 @@ +retrieve_entity_info($crmid,"Leads"); + $leadObj->column_fields[$fieldname] = $fieldvalue; + $leadObj->id = $crmid; + $leadObj->mode = "edit"; + $leadObj->save("Leads"); + if($leadObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/EditView.php b/oss/vtiger/trunk/modules/Leads/EditView.php new file mode 100644 index 00000000..11a1886c --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/EditView.php @@ -0,0 +1,141 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if(isset($_REQUEST['record']) && isset($_REQUEST['record'])) { + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Leads"); + $focus->firstname=$focus->column_fields['firstname']; + $focus->lastname=$focus->column_fields['lastname']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['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,$mode,$focus->column_fields)); +else +{ + $smarty->assign("BASBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS')); + $smarty->assign("ADVBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'ADV')); +} +$smarty->assign("OP_MODE",$disp_view); + + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +//retreiving the combo values array + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$lead_name = $focus->lastname; +if (getFieldVisibilityPermission($currentModule, $current_user->id,'firstname') == '0') { + $lead_name .= ' '.$focus->firstname; +} +$smarty->assign("NAME",$lead_name); + +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} + +if(isset($_REQUEST['campaignid'])) +$smarty->assign("campaignid",vtlib_purify($_REQUEST['campaignid'])); +if (isset($_REQUEST['return_module'])) +$smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else +$smarty->assign("RETURN_MODULE","Leads"); +if (isset($_REQUEST['return_action'])) +$smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else +$smarty->assign("RETURN_ACTION","index"); +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id()); +$smarty->assign("ID", $focus->id); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Lead'); + +//create the html select code here and assign it +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + + + $tabid = getTabid("Leads"); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data = split_validationdataArray($validationData); + + $smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); + $smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); + $smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 || $adb->num_rows($mod_seq_string) == 0 || $focus->checkModuleSeqNumber($focus->table_name, $mod_seq_field['column'], $mod_seq_prefix.$mod_seq_no)) + echo '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +if($focus->mode == 'edit') +$smarty->display("salesEditView.tpl"); +else +$smarty->display("CreateView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/ExportRecords.php b/oss/vtiger/trunk/modules/Leads/ExportRecords.php new file mode 100644 index 00000000..dcbf10eb --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/ExportRecords.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/Leads/FindDuplicateRecords.php new file mode 100644 index 00000000..02efee01 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/FindDuplicateRecords.php @@ -0,0 +1,107 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    + $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/Import.php b/oss/vtiger/trunk/modules/Leads/Import.php new file mode 100644 index 00000000..ae570f61 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/Import.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/LeadConvertToEntities.php b/oss/vtiger/trunk/modules/Leads/LeadConvertToEntities.php new file mode 100644 index 00000000..780307a9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/LeadConvertToEntities.php @@ -0,0 +1,595 @@ +id.'.php'); +if($assigned_to == "U") + $log->debug("id = $id \n assigned_user_id = $assigned_user_id \n createpotential = $createpotential \n close date = $close_date \n current user id = $current_user_id \n accountname = $accountname \n module = $module"); +else + $log->debug("id = $id \n assigned_user_id = $assigned_group_id \n createpotential = $createpotential \n close date = $close_date \n current user id = $current_user_id \n accountname = $accountname \n module = $module"); + +$rate_symbol=getCurrencySymbolandCRate($user_info['currency_id']); +$rate = $rate_symbol['rate']; +if($potential_amount != '') + $potential_amount = convertToDollar($potential_amount,$rate); + +//Retrieve info from all the vtiger_tables related to leads +$focus = new Leads(); +$focus->retrieve_entity_info($id,"Leads"); + +//get all the lead related columns +$row = $focus->column_fields; + +$date_entered = $adb->formatDate(date('Y-m-d H:i:s'), true); +$date_modified = $adb->formatDate(date('Y-m-d H:i:s'), true); + +/** Function for getting the custom values from leads and saving to vtiger_account/contact/potential custom vtiger_fields. + * @param string $type - Field Type (eg: text, list) + * @param integer $type_id - Field Type ID +*/ +function getInsertValues($type,$type_id) +{ + global $id,$adb,$log; + $log->debug("Entering getInsertValues(".$type.",".$type_id.") method ..."); + $sql_convert_lead="select * from vtiger_convertleadmapping "; + $convert_result = $adb->pquery($sql_convert_lead, array()); + $noofrows = $adb->num_rows($convert_result); + + $value_cf_array = Array(); + for($i=0;$i<$noofrows;$i++) + { + $flag="false"; + $log->info("In vtiger_convertleadmapping function"); + $lead_id=$adb->query_result($convert_result,$i,"leadfid"); + //Getting the relatd customfields for Accounts/Contact/potential from vtiger_convertleadmapping vtiger_table + $account_id_val=$adb->query_result($convert_result,$i,"accountfid"); + $contact_id_val=$adb->query_result($convert_result,$i,"contactfid"); + $potential_id_val=$adb->query_result($convert_result,$i,"potentialfid"); + + $sql_leads_column="select vtiger_field.uitype,vtiger_field.fieldid,vtiger_field.columnname from vtiger_field,vtiger_tab where vtiger_field.tabid=vtiger_tab.tabid and generatedtype=2 and vtiger_tab.name='Leads' and fieldid=? and vtiger_field.presence in (0,2)"; //getting the columnname for the customfield of the lead + $log->debug("Lead's custom vtiger_field coumn name is ".$sql_leads_column); + + $lead_column_result = $adb->pquery($sql_leads_column, array($lead_id)); + $leads_no_rows = $adb->num_rows($lead_column_result); + if($leads_no_rows>0) + { + $lead_column_name=$adb->query_result($lead_column_result,0,"columnname"); + $lead_uitype=$adb->query_result($lead_column_result,0,"uitype"); + $sql_leads_val="select $lead_column_name from vtiger_leadscf where leadid=?"; //custom vtiger_field value for lead + $lead_val_result = $adb->pquery($sql_leads_val,array($id)); + $lead_value=$adb->query_result($lead_val_result,0,$lead_column_name); + $log->debug("Lead's custom vtiger_field value is ".$lead_value); + } + //Query for getting the column name for Accounts/Contacts/Potentials if custom vtiger_field for lead is mappped + $sql_type="select vtiger_field.fieldid,vtiger_field.uitype,vtiger_field.columnname from vtiger_field,vtiger_tab where vtiger_field.tabid=vtiger_tab.tabid and generatedtype=2 and vtiger_field.presence in (0,2) and vtiger_tab.name="; + $params = array(); + if($type=="Accounts") + { + if($account_id_val!="" && $account_id_val!=0) + { + $flag="true"; + $log->info("Getting the Accounts custom vtiger_field column name "); + $sql_type.="'Accounts' and fieldid=?"; + array_push($params, $account_id_val); + } + } + else if($type == "Contacts") + { + if($contact_id_val!="" && $contact_id_val!=0) + { + $flag="true"; + $log->info("Getting the Contacts custom vtiger_field column name "); + $sql_type.="'Contacts' and fieldid=?"; + array_push($params, $contact_id_val); + } + } + else if($type == "Potentials") + { + if($potential_id_val!="" && $potential_id_val!=0) + { + $flag="true"; + $log->info("Getting the Potentials custom vtiger_field column name "); + $sql_type.="'Potentials' and fieldid=?"; + array_push($params, $potential_id_val); + } + } + if($flag=="true") + { + $type_result=$adb->pquery($sql_type, $params); + //To construct the cf array + $colname = $adb->query_result($type_result,0,"columnname"); + $type_insert_column[] = $colname; + $type_uitype =$adb->query_result($type_result,0,"uitype") ; + + //To construct the cf array + $ins_val = $adb->query_result($lead_val_result,0,$lead_column_name); + + //This array is used to store the tablename as the key and the value for that table in the custom field of the uitype only for 15 and 33(Multiselect cf)... + if($lead_uitype == 33 || $lead_uitype == 15) { + $lead_val_arr[$colname] = $lead_column_name; + $value_cf_array[$colname]=$ins_val; + } + + $insert_value[] = $ins_val; + } + } + if(count($value_cf_array) > 0) + { + if(count($type_insert_column) > 0) + { + foreach($value_cf_array as $key => $value) + { + $tableName = $key; + $tableVal = $value; + if($tableVal != '') + { + $tab_val = explode ("|##|",$value); + if(count($tab_val)>0) + { + for($k=0;$knum_rows($adb->query($sql)); + $count=0; + for($n=0;$n < $numRow;$n++) + { + $exist_val = $adb->query_result($adb->query($sql),$n,$tableName); + if(trim($exist_val) == trim($val)) + { + $count++; + } + } + if($count == 0) + { + $cfId=$adb->getUniqueID("vtiger_$tableName"); + $unique_picklist_value = getUniquePicklistID(); + + $qry="insert into vtiger_$tableName values(?,?,?,?)"; + $adb->pquery($qry, array($cfId,trim($val),1,$unique_picklist_value)); + //added to fix ticket#4492 + $picklistId_qry = "select picklistid from vtiger_picklist where name=?"; + $picklistId_res = $adb->pquery($picklistId_qry,array($tableName)); + $picklist_Id = $adb->query_result($picklistId_res,0,'picklistid'); + //While adding a new value into the picklist table, the roleid's which has permission for the lead cf will only given permission for contacts,potentials and account module while converting. -- refer ticket #4885 --- + $role_qry = "select roleid from vtiger_role2picklist where picklistvalueid in (select picklist_valueid from vtiger_".$lead_val_arr[$tableName]." where ".$lead_val_arr[$tableName]."='".trim($val)."')"; + $numOFRole=$adb->num_rows($adb->query($role_qry)); + for($l=0;$l<$numOFRole;$l++) + { + $role_id = $adb->query_result($adb->query($role_qry),$l,'roleid'); + $sort_qry = "select max(sortid)+1 as sortid from vtiger_role2picklist where picklistid=? and roleid=?"; + $sort_qry_res = $adb->pquery($sort_qry,array($picklist_Id,$role_id)); + $sort_id = $adb->query_result($sort_qry_res,0,'sortid'); + $role_picklist = "insert into vtiger_role2picklist values (?,?,?,?)"; + $adb->pquery($role_picklist,array($role_id,$unique_picklist_value,$picklist_Id,$sort_id)); + } + //end + } + } + } + + } + } + } + } + $log->debug("columns to be inserted are ".$type_insert_column); + $log->debug("columns to be inserted are ".$insert_value); + $values = array ('columns'=>$type_insert_column,'values'=>$insert_value); + $log->debug("Exiting getInsertValues method ..."); + return $values; +} +//function Ends + +/** Function used to get the lead related Notes and Attachments with other entities Account, Contact and Potential + * @param integer $id - leadid + * @param integer $accountid - related entity id (accountid) + */ +function getRelatedNotesAttachments($id,$related_id) +{ + global $adb,$log,$id; + $log->debug("Entering getRelatedNotesAttachments(".$id.",".$related_id.") method ..."); + + $sql_lead_notes ="select * from vtiger_senotesrel where crmid=?"; + $lead_notes_result = $adb->pquery($sql_lead_notes, array($id)); + $noofrows = $adb->num_rows($lead_notes_result); + + for($i=0; $i<$noofrows;$i++ ) + { + + $lead_related_note_id=$adb->query_result($lead_notes_result,$i,"notesid"); + $log->debug("Lead related note id ".$lead_related_note_id); + + $sql_insert_notes="insert into vtiger_senotesrel(crmid,notesid) values (?,?)"; + $adb->pquery($sql_insert_notes, array($related_id, $lead_related_note_id)); + } + + $sql_lead_attachment="select * from vtiger_seattachmentsrel where crmid=?"; + $lead_attachment_result = $adb->pquery($sql_lead_attachment, array($id)); + $noofrows = $adb->num_rows($lead_attachment_result); + + for($i=0;$i<$noofrows;$i++) + { + $lead_related_attachment_id=$adb->query_result($lead_attachment_result,$i,"attachmentsid"); + $log->debug("Lead related attachment id ".$lead_related_attachment_id); + + $sql_insert_attachment="insert into vtiger_seattachmentsrel(crmid,attachmentsid) values (?,?)"; + $adb->pquery($sql_insert_attachment, array($related_id, $lead_related_attachment_id)); + } + $log->debug("Exiting getRelatedNotesAttachments method ..."); + +} + +/** Function used to get the lead related activities with other entities Account and Contact + * @param integer $accountid - related entity id + * @param integer $contact_id - related entity id + */ +function getRelatedActivities($accountid,$contact_id) +{ + global $adb,$log,$id; + $log->debug("Entering getRelatedActivities(".$accountid.",".$contact_id.") method ..."); + $sql_lead_activity="select * from vtiger_seactivityrel where crmid=?"; + $lead_activity_result = $adb->pquery($sql_lead_activity, array($id)); + $noofrows = $adb->num_rows($lead_activity_result); + for($i=0;$i<$noofrows;$i++) + { + $lead_related_activity_id=$adb->query_result($lead_activity_result,$i,"activityid"); + $log->debug("Lead related vtiger_activity id ".$lead_related_activity_id); + + $sql_type_email="select setype from vtiger_crmentity where crmid=?"; + $type_email_result = $adb->pquery($sql_type_email, array($lead_related_activity_id)); + $type=$adb->query_result($type_email_result,0,"setype"); + $log->debug("type of vtiger_activity id ".$type); + + $sql_delete_lead_activity="delete from vtiger_seactivityrel where crmid=?"; + $adb->pquery($sql_delete_lead_activity, array($id)); + + if($type != "Emails") + { + $sql_insert_account_activity="insert into vtiger_seactivityrel(crmid,activityid) values (?,?)"; + $adb->pquery($sql_insert_account_activity, array($accountid, $lead_related_activity_id)); + + $sql_insert_contact_activity="insert into vtiger_cntactivityrel(contactid,activityid) values (?,?)"; + $adb->pquery($sql_insert_contact_activity, array($contact_id, $lead_related_activity_id)); + } + else + { + $sql_insert_contact_activity="insert into vtiger_seactivityrel(crmid,activityid) values (?,?)"; + $adb->pquery($sql_insert_contact_activity, array($contact_id, $lead_related_activity_id)); + } + } + $log->debug("Exiting getRelatedActivities method ..."); + +} + +/** Function used to save the lead related products with other entities Account, Contact and Potential + * $leadid - leadid + * $relatedid - related entity id (accountid/contactid/potentialid) + * $setype - related module(Accounts/Contacts/Potentials) + */ +function saveLeadRelatedProducts($leadid, $relatedid, $setype) +{ + global $adb, $log; + $log->debug("Entering into function saveLeadRelatedProducts($leadid, $relatedid)"); + + $product_result = $adb->pquery("select * from vtiger_seproductsrel where crmid=?", array($leadid)); + $noofproducts = $adb->num_rows($product_result); + for($i = 0; $i < $noofproducts; $i++) + { + $productid = $adb->query_result($product_result,$i,'productid'); + $adb->pquery("insert into vtiger_seproductsrel values(?,?,?)", array($relatedid, $productid, $setype)); + } + + $log->debug("Exit from function saveLeadRelatedProducts."); +} + +/** Function used to save the lead related Campaigns with Contact + * $leadid - leadid + * $relatedid - related entity id (contactid) + */ +function saveLeadRelatedCampaigns($leadid, $relatedid) +{ + global $adb, $log; + $log->debug("Entering into function saveLeadRelatedCampaigns($leadid, $relatedid)"); + + $campaign_result = $adb->pquery("select * from vtiger_campaignleadrel where leadid=?", array($leadid)); + $noofcampaigns = $adb->num_rows($campaign_result); + for($i = 0; $i < $noofcampaigns; $i++) + { + $campaignid = $adb->query_result($campaign_result,$i,'campaignid'); + + $adb->pquery("insert into vtiger_campaigncontrel (campaignid, contactid) values(?,?)", array($campaignid, $relatedid)); + } + $log->debug("Exit from function saveLeadRelatedCampaigns."); +} +$crmid =''; +if(vtlib_isModuleActive('Accounts') && isPermitted("Accounts","EditView") =='yes'){ + /*Code integrated to avoid duplicate Account creation during ConvertLead Operation START-- by Bharathi*/ + $acc_query = "select vtiger_account.accountid from vtiger_account left join vtiger_crmentity on vtiger_account.accountid = vtiger_crmentity.crmid where vtiger_crmentity.deleted=0 and vtiger_account.accountname = ?"; + $acc_res = $adb->pquery($acc_query, array($accountname)); + $acc_rows = $adb->num_rows($acc_res); + if($acc_rows != 0){ + $crmid = $adb->query_result($acc_res,0,"accountid"); + + //Retrieve the lead related products and relate them with this new account + getRelatedNotesAttachments($id,$crmid); + saveLeadRelatedProducts($id, $crmid, "Accounts"); + saveLeadRelations($id, $crmid, "Accounts"); + } else if($accountname==''){ + $crmid=''; + } else + { + $crmid = $adb->getUniqueID("vtiger_crmentity"); + + //Saving Account - starts + + $sql_crmentity = "insert into vtiger_crmentity(crmid,smcreatorid,smownerid,setype,presence,createdtime,modifiedtime,deleted,description) values(?,?,?,?,?,?,?,?,?)"; + $sql_params = array($crmid, $current_user_id, $assigned_user_id, 'Accounts', 1, $date_entered, $date_modified, 0, $row['description']); + $adb->pquery($sql_crmentity, $sql_params); + + //Module Sequence Numbering + require_once('modules/Accounts/Accounts.php'); + $acc_no_focus = new Accounts(); + $account_no = $acc_no_focus->setModuleSeqNumber("increment",'Accounts'); + // END + + /* Modified by Minnie to fix the convertlead issue -- START*/ + if(isset($row["annualrevenue"]) && !empty($row["annualrevenue"])) $annualrevenue = $row["annualrevenue"]; + else $annualrevenue = 'null'; + + if(isset($row["noofemployees"]) && !empty($row["noofemployees"])) $employees = $row["noofemployees"]; + else $employees = 'null'; + + $sql_insert_account = "INSERT INTO vtiger_account (account_no,accountid,accountname,industry,annualrevenue,phone,fax,rating,email1,website,employees) VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + /* Modified by Minnie -- END*/ + $account_params = array($account_no,$crmid, $accountname, $row["industry"], $annualrevenue, $row["phone"], $row["fax"], $row["rating"], $row["email"], $row["website"], $employees); + $adb->pquery($sql_insert_account, $account_params); + + /*if($assigned_to !="U"){ + $sql_crmentity = "insert into vtiger_accountgrouprelation(accountid,groupname) values(?,?)"; + $sql_params = array($crmid,$assigned_group_name); + $adb->pquery($sql_crmentity, $sql_params); + }*/ + + $sql_insert_accountbillads = "INSERT INTO vtiger_accountbillads (accountaddressid,bill_city,bill_code,bill_country,bill_state,bill_street,bill_pobox) VALUES (?,?,?,?,?,?,?)"; + $billads_params = array($crmid, $row["city"], $row["code"], $row["country"], $row["state"], $row["lane"], $row["pobox"]); + $adb->pquery($sql_insert_accountbillads, $billads_params); + + $sql_insert_accountshipads = "INSERT INTO vtiger_accountshipads (accountaddressid,ship_city,ship_code,ship_country,ship_pobox,ship_state,ship_street) VALUES (?,?,?,?,?,?,?)"; + $shipads_params = array($crmid, $row["city"], $row["code"], $row["country"], $row["pobox"], $row["state"], $row["lane"]); + $adb->pquery($sql_insert_accountshipads, $shipads_params); + + //Getting the custom vtiger_field values from leads and inserting into Accounts if the vtiger_field is mapped - Jaguar + $col_val= getInsertValues("Accounts",$crmid); + $insert_columns = $col_val['columns']; + $insert_columns[] = "accountid"; + $insert_values = $col_val['values']; + $insert_values[] = $crmid; + $insert_val_str = generateQuestionMarks($insert_values); + $sql_insert_accountcustomfield = "INSERT INTO vtiger_accountscf (". implode(",",$insert_columns) .") VALUES (".$insert_val_str.")"; + $adb->pquery($sql_insert_accountcustomfield, $insert_values); + //Saving Account - ends + + getRelatedNotesAttachments($id,$crmid); + //Retrieve the lead related products and relate them with this new account + saveLeadRelatedProducts($id, $crmid, "Accounts"); + saveLeadRelations($id, $crmid, "Accounts"); + } +} +//Up to this, Account related data save finshed + +if(vtlib_isModuleActive('Contacts') && isPermitted("Contacts","EditView") =='yes'){ + $date_entered = $adb->formatDate(date('Y-m-d H:i:s'), true); + $date_modified = $adb->formatDate(date('Y-m-d H:i:s'), true); + + //Saving Contact - starts + $crmcontactid = $adb->getUniqueID("vtiger_crmentity"); + + $sql_crmentity1 = "insert into vtiger_crmentity(crmid,smcreatorid,smownerid,setype,presence,deleted,description,createdtime,modifiedtime) values(?,?,?,?,?,?,?,?,?)"; + $sql_params = array($crmcontactid, $current_user_id, $assigned_user_id, 'Contacts', 0, 0, $row['description'], $date_entered, $date_modified); + $adb->pquery($sql_crmentity1, $sql_params); + + $contact_id = $crmcontactid; + $log->debug("contact id is ".$contact_id); + + // Module Sequence Numbering + require_once('modules/Contacts/Contacts.php'); + $cont_no_focus = new Contacts(); + $contact_no = $cont_no_focus->setModuleSeqNumber("increment",'Contacts'); + // END + + $sql_insert_contact = "INSERT INTO vtiger_contactdetails (contact_no,contactid,accountid,salutation,firstname,lastname,email,phone,mobile,title,fax,yahooid) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; + $contact_params = array($contact_no, $contact_id, $crmid, $row["salutationtype"], $row["firstname"], $row["lastname"], $row["email"], $row["phone"], $row["mobile"], $row["designation"], $row["fax"], $row['yahooid']); + $adb->pquery($sql_insert_contact, $contact_params); + + /*if($assigned_to !="U"){ + $sql_crmentity = "insert into vtiger_contactgrouprelation(contactid,groupname) values(?,?)"; + $sql_params = array($contact_id,$assigned_group_name); + $adb->pquery($sql_crmentity, $sql_params); + }*/ + $sql_insert_contactsubdetails = "INSERT INTO vtiger_contactsubdetails (contactsubscriptionid,homephone,otherphone,leadsource) VALUES (?,?,?,?)"; + $c_subd_params = array($contact_id, '', '', $row['leadsource']); + $adb->pquery($sql_insert_contactsubdetails, $c_subd_params); + + $sql_insert_contactaddress = "INSERT INTO vtiger_contactaddress (contactaddressid,mailingcity,mailingstreet,mailingstate,mailingcountry,mailingpobox,mailingzip) VALUES (?,?,?,?,?,?,?)"; + $c_addr_params = array($contact_id, $row["city"], $row["lane"], $row['state'], $row["country"], $row["pobox"], $row['code']); + $adb->pquery($sql_insert_contactaddress, $c_addr_params); + + $sql_insert_customerdetails = "INSERT INTO vtiger_customerdetails (customerid) VALUES (?)"; + $adb->pquery($sql_insert_customerdetails, array($contact_id)); + + //Getting the customfield values from leads and inserting into the respected ContactCustomfield to which it is mapped - Jaguar + $col_val= getInsertValues("Contacts",$contact_id); + $insert_columns = $col_val['columns']; + $insert_columns[] = "contactid"; + $insert_values = $col_val['values']; + $insert_values[] = $contact_id; + $insert_val_str = generateQuestionMarks($insert_values); + $sql_insert_contactcustomfield = "INSERT INTO vtiger_contactscf (". implode(",",$insert_columns) .") VALUES (".$insert_val_str.")"; + $adb->pquery($sql_insert_contactcustomfield, $insert_values); + //Saving Contact - ends + + getRelatedActivities($crmid,$contact_id); //To convert relates Activites and Email -Jaguar + getRelatedNotesAttachments($id,$contact_id); + + //Retrieve the lead related products and relate them with this new contact + saveLeadRelatedProducts($id, $contact_id, "Contacts"); + saveLeadRelations($id, $contact_id, "Contacts"); + + //Retrieve the lead related Campaigns and relate them with this new contact --Minnie + saveLeadRelatedCampaigns($id, $contact_id); +} + +//Up to this, Contact related data save finshed + +//Saving Potential - starts +if((! isset($createpotential) || ! $createpotential == "on") && (!empty($potential_name)) && isPermitted("Potentials","EditView") =='yes' && ($crmid != '' || $crmcontactid != '') && vtlib_isModuleActive('Potentials')) +{ + $log->info("createpotential is not set"); + + $date_entered = $adb->formatDate(date('Y-m-d H:i:s'), true); + $date_modified = $adb->formatDate(date('Y-m-d H:i:s'), true); + + $oppid = $adb->getUniqueID("vtiger_crmentity"); + + $sql_crmentity = "insert into vtiger_crmentity(crmid,smcreatorid,smownerid,setype,presence,deleted,createdtime,modifiedtime,description) values(?,?,?,?,?,?,?,?,?)"; + $sql_params = array($oppid, $current_user_id, $assigned_user_id, 'Potentials', 0, 0, $date_entered, $date_modified, $row['description']); + $adb->pquery($sql_crmentity, $sql_params); + + // Module Sequence Numbering + require_once('modules/Potentials/Potentials.php'); + $pot_no_focus = new Potentials(); + $potential_no = $pot_no_focus->setModuleSeqNumber("increment",'Potentials'); + // END + + if(!isset($potential_amount) || $potential_amount == null) + { + $potential_amount=0; + } + + if($crmid!=''){ + $related_to = $crmid; + } else { + $related_to = $crmcontactid; + } + + $sql_insert_opp = "INSERT INTO vtiger_potential (potential_no,potentialid,related_to,potentialname,leadsource,closingdate,sales_stage,amount) VALUES (?,?,?,?,?,?,?,?)"; + $opp_params = array($potential_no, $oppid, $related_to, $potential_name, $row['leadsource'], $close_date, $potential_sales_stage, $potential_amount); + $adb->pquery($sql_insert_opp, $opp_params); + + //Getting the customfield values from leads and inserting into the respected PotentialCustomfield to which it is mapped - Jaguar + $col_val= getInsertValues("Potentials",$oppid); + $insert_columns = $col_val['columns']; + $insert_columns[] = "potentialid"; + $insert_values = $col_val['values']; + $insert_values[] = $oppid; + $insert_val_str = generateQuestionMarks($insert_values); + $sql_insert_potentialcustomfield = "INSERT INTO vtiger_potentialscf (". implode(",",$insert_columns) .") VALUES (".$insert_val_str.")"; + $adb->pquery($sql_insert_potentialcustomfield, $insert_values); + + if($crmid != '' && $contact_id != ''){ + $sql_insert2contpotentialrel ="insert into vtiger_contpotentialrel values(?,?)"; + $adb->pquery($sql_insert2contpotentialrel, array($contact_id, $oppid)); + } + //Retrieve the lead related products and relate them with this new potential + saveLeadRelatedProducts($id, $oppid, "Potentials"); + saveLeadRelations($id, $oppid, "Potentials"); +} +//Saving Potential - ends +//Up to this, Potential related data save finshed + + +//Deleting from the vtiger_tracker +$sql_delete_tracker= "DELETE from vtiger_tracker where item_id=?"; +$adb->pquery($sql_delete_tracker, array($id)); +$category = getParentTab(); +//Updating the deleted status +if($crmid != '' || $crmcontactid != ''){ + $sql_update_converted = "UPDATE vtiger_leaddetails SET converted = 1 where leadid=?"; + $adb->pquery($sql_update_converted, array($id)); + //updating the campaign-lead relation --Minnie + $sql_update_campleadrel = "delete from vtiger_campaignleadrel where leadid=?"; + $adb->pquery($sql_update_campleadrel, array($id)); +} +if($crmid!=''){ + header("Location: index.php?action=DetailView&module=Accounts&record=$crmid&parenttab=$category"); +} elseif($crmcontactid != '') { + header("Location: index.php?action=DetailView&module=Contacts&record=$crmcontactid&parenttab=$category"); +}else{ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    $currentModule $app_strings[CANNOT_CONVERT]
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; +} + +/** Function used to save the lead related services with other entities Account, Contact and Potential + * $leadid - leadid + * $relatedid - related entity id (accountid/contactid/potentialid) + * $setype - related module(Accounts/Contacts/Potentials) + */ +function saveLeadRelations($leadid, $relatedid, $setype) +{ + global $adb, $log; + $log->debug("Entering into function saveLeadRelatedProducts($leadid, $relatedid)"); + + $result = $adb->pquery("select * from vtiger_crmentityrel where crmid=?", array($leadid)); + $noofproducts = $adb->num_rows($result); + for($i = 0; $i < $noofproducts; $i++) + { + $recordid = $adb->query_result($result,$i,'relcrmid'); + $recordmodule = $adb->query_result($result,$i,'relmodule'); + $adb->pquery("insert into vtiger_crmentityrel values(?,?,?,?)", array($relatedid, $setype, $recordid, $recordmodule)); + } + $result = $adb->pquery("select * from vtiger_crmentityrel where relcrmid=?", array($leadid)); + $noofproducts = $adb->num_rows($result); + for($i = 0; $i < $noofproducts; $i++) + { + $recordid = $adb->query_result($result,$i,'crmid'); + $recordmodule = $adb->query_result($result,$i,'module'); + $adb->pquery("insert into vtiger_crmentityrel values(?,?,?,?)", array($relatedid, $setype, $recordid, $recordmodule)); + } + + $log->debug("Exit from function saveLeadRelatedProducts."); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/Leads.js b/oss/vtiger/trunk/modules/Leads/Leads.js new file mode 100644 index 00000000..a2ef6330 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/Leads.js @@ -0,0 +1,152 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + + +document.write(" +pquery($sql, array($templateid)); +$temparray = $adb->fetch_array($result); + +$fileContent = $temparray['data']; +$filename=html_entity_decode($temparray['filename'], ENT_QUOTES, $default_charset); + +// Fix For: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$filename= $randomfilename . "_word.doc"; + +$filesize=$temparray['filesize']; +$wordtemplatedownloadpath =$root_directory ."/test/wordtemplatedownload/"; + + +$handle = fopen($wordtemplatedownloadpath .$filename,"wb"); +fwrite($handle,base64_decode($fileContent),$filesize); +fclose($handle); + +//for mass merge +$mass_merge = $_REQUEST['allselectedboxes']; +$single_record = $_REQUEST['record']; + +if($mass_merge != "") +{ + $mass_merge = explode(";",$mass_merge); + //array_pop($mass_merge); + $temp_mass_merge = $mass_merge; + if(array_pop($temp_mass_merge)=="") + array_pop($mass_merge); + //$mass_merge = implode(",",$mass_merge); +}else if($single_record != "") +{ + $mass_merge = $single_record; +}else +{ + die("Record Id is not found"); +} + +//<<<<<<<<<<<<<<<
    >>>>>>>>>>>>>>>>>>>>>>> + +global $current_user; +require('user_privileges/user_privileges_'.$current_user->id.'.php'); +if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0 || $module == "Users" || $module == "Emails") +{ + $query1="select tablename,columnname,fieldlabel from vtiger_field where tabid=7 and vtiger_field.presence in (0,2) order by tablename"; + $params1 = array(); +} +else +{ + $profileList = getCurrentUserProfileList(); + $query1="select vtiger_field.tablename,vtiger_field.columnname,vtiger_field.fieldlabel from vtiger_field INNER JOIN vtiger_profile2field ON vtiger_profile2field.fieldid=vtiger_field.fieldid INNER JOIN vtiger_def_org_field ON vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid in (7) AND vtiger_profile2field.visible=0 AND vtiger_def_org_field.visible=0 AND vtiger_profile2field.profileid IN (". generateQuestionMarks($profileList) .") and vtiger_field.presence in (0,2) GROUP BY vtiger_field.fieldid order by vtiger_field.tablename"; + $params1 = array($profileList); + //Postgres 8 fixes + if( $adb->dbType == "pgsql") + $query1 = fixPostgresQuery( $query1, $log, 0); +} + +$result = $adb->pquery($query1, $params1); +$y=$adb->num_rows($result); + +for ($x=0; $x<$y; $x++) +{ + $tablename = $adb->query_result($result,$x,"tablename"); + $columnname = $adb->query_result($result,$x,"columnname"); + $querycolumns[$x] = $tablename.".".$columnname; + if($columnname == "smownerid") + { + $querycolumns[$x] = "case when (vtiger_users.user_name not like '') then concat(vtiger_users.last_name,' ',vtiger_users.first_name) else vtiger_groups.groupname end as username,vtiger_users.first_name,vtiger_users.last_name,vtiger_users.user_name,vtiger_users.yahoo_id,vtiger_users.title,vtiger_users.phone_work,vtiger_users.department,vtiger_users.phone_mobile,vtiger_users.phone_other,vtiger_users.phone_fax,vtiger_users.email1,vtiger_users.phone_home,vtiger_users.email2,vtiger_users.address_street,vtiger_users.address_city,vtiger_users.address_state,vtiger_users.address_postalcode,vtiger_users.address_country"; + } + $field_label[$x] = "LEAD_".strtoupper(str_replace(" ","",$adb->query_result($result,$x,"fieldlabel"))); + if($columnname == "smownerid") + { + $field_label[$x] = $field_label[$x].",USER_FIRSTNAME,USER_LASTNAME,USER_USERNAME,USER_YAHOOID,USER_TITLE,USER_OFFICEPHONE,USER_DEPARTMENT,USER_MOBILE,USER_OTHERPHONE,USER_FAX,USER_EMAIL,USER_HOMEPHONE,USER_OTHEREMAIL,USER_PRIMARYADDRESS,USER_CITY,USER_STATE,USER_POSTALCODE,USER_COUNTRY"; + } +} +$csvheader = implode(",",$field_label); +//<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>> + +if(count($querycolumns) > 0) +{ + $selectcolumns = implode($querycolumns,","); + +$query = "select ".$selectcolumns." from vtiger_leaddetails + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid + inner join vtiger_leadsubdetails on vtiger_leadsubdetails.leadsubscriptionid=vtiger_leaddetails.leadid + inner join vtiger_leadaddress on vtiger_leadaddress.leadaddressid=vtiger_leadsubdetails.leadsubscriptionid + inner join vtiger_leadscf on vtiger_leaddetails.leadid = vtiger_leadscf.leadid + LEFT JOIN vtiger_groups + ON vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + where vtiger_crmentity.deleted=0 and vtiger_leaddetails.leadid in (". generateQuestionMarks($mass_merge) .")"; + +$result = $adb->pquery($query, array($mass_merge)); +$avail_pick_arr = getAccessPickListValues('Leads'); +while($columnValues = $adb->fetch_array($result)) +{ + $y=$adb->num_fields($result); + for($x=0; $x<$y; $x++) + { + $value = $columnValues[$x]; + foreach($columnValues as $key=>$val) + { + if($val == $value && $value != '') + { + if(array_key_exists($key,$avail_pick_arr)) + { + if(!in_array($val,$avail_pick_arr[$key])) + { + $value = "Not Accessible"; + } + } + } + } + //<<<<<<<<<<<<<<< For Blank Fields >>>>>>>>>>>>>>>>>>>>>>>>>>>> + if(trim($value) == "--None--" || trim($value) == "--none--") + { + $value = ""; + } + //<<<<<<<<<<<<<<< End >>>>>>>>>>>>>>>>>>>>>>>>>>>> + $actual_values[$x] = $value; + $actual_values[$x] = str_replace('"'," ",$actual_values[$x]); + //if value contains any line feed or carriage return replace the value with ".value." + if (preg_match ("/(\r\n)/", $actual_values[$x])) + { + $actual_values[$x] = '"'.$actual_values[$x].'"'; + } + $actual_values[$x] = decode_html(str_replace(","," ",$actual_values[$x])); + } + $mergevalue[] = implode($actual_values,","); +} +$csvdata = implode($mergevalue,"###"); +}else +{ + die("No vtiger_fields to do Merge"); +} +// Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$datafilename = $randomfilename . "_data.csv"; + +$handle = fopen($wordtemplatedownloadpath.$datafilename,"wb"); +fwrite($handle,$csvheader."\r\n"); +fwrite($handle,str_replace("###","\r\n",$csvdata)); +fclose($handle); + +?> + + + + diff --git a/oss/vtiger/trunk/modules/Leads/Popup.php b/oss/vtiger/trunk/modules/Leads/Popup.php new file mode 100644 index 00000000..88877b45 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/Popup.php @@ -0,0 +1,20 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/ProcessDuplicates.php b/oss/vtiger/trunk/modules/Leads/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Leads/QuickCreate.php b/oss/vtiger/trunk/modules/Leads/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/Save.php b/oss/vtiger/trunk/modules/Leads/Save.php new file mode 100644 index 00000000..709666d1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/Save.php @@ -0,0 +1,175 @@ +id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; +$curr_symbol=$rate_symbol['symbol']; +//added to fix 4600 +$search=vtlib_purify($_REQUEST['search_url']); + +if(isset($_REQUEST['record'])) +{ + $focus->id = $_REQUEST['record']; +} +if(isset($_REQUEST['mode'])) +{ + $focus->mode = $_REQUEST['mode']; +} + +//$focus->retrieve($_REQUEST['record']); + +foreach($focus->column_fields as $fieldname => $val) +{ + if(isset($_REQUEST[$fieldname])) { + if(is_array($_REQUEST[$fieldname])) + $value = $_REQUEST[$fieldname]; + else + $value = trim($_REQUEST[$fieldname]); + $log->info("the value is ".$value); + $focus->column_fields[$fieldname] = $value; + } +} +if(isset($_REQUEST['annualrevenue'])) { + $value = convertToDollar($_REQUEST['annualrevenue'],$rate); + $focus->column_fields['annualrevenue'] = $value; +} + +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("Leads"); + +$return_id = $focus->id; + $log->info("the return id is ".$return_id); +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Leads"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +$local_log->debug("Saved record with id of ".$return_id); +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] == "Campaigns") +{ + if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") + { + $sql = "delete from vtiger_campaignleadrel where leadid = ?"; + $adb->pquery($sql, array($focus->id)); + $sql = "insert into vtiger_campaignleadrel values (?,?)"; + $adb->pquery($sql, array($_REQUEST['return_id'], $focus->id)); + } +} +header("Location: index.php?action=$return_action&module=$return_module&record=$return_id&parenttab=$parenttab&viewname=$return_viewname&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +/** Function to save the Lead custom fields info into database + * @param integer $entity_id - leadid +*/ +function save_customfields($entity_id) +{ + $log->debug("Entering save_customfields(".$entity_id.") method ..."); + $log->debug("save custom vtiger_field invoked ".$entity_id); + global $adb; + $dbquery="select * from customfields where module='Leads'"; + $result = $adb->pquery($dbquery, array()); + $custquery = "select * from leadcf where leadid=?"; + $cust_result = $adb->pquery($custquery, array($entity_id)); + if($adb->num_rows($result) != 0) + { + + $columns=''; + $params = array(); + $update=''; + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $fldName=$adb->query_result($result,$i,"fieldlabel"); + $colName=$adb->query_result($result,$i,"column_name"); + if(isset($_REQUEST[$colName])) + { + $fldvalue=$_REQUEST[$colName]; + $log->info("the columnName is ".$fldvalue); + if(get_magic_quotes_gpc() == 1) + { + $fldvalue = stripslashes($fldvalue); + } + } + else + { + $fldvalue = ''; + } + if(isset($_REQUEST['record']) && $_REQUEST['record'] != '' && $adb->num_rows($cust_result) !=0) + { + //Update Block + if($i == 0) + { + $update = $colName.'=?'; + } + else + { + $update .= ', '.$colName.'=?'; + } + array_push($params, $fldvalue); + } + else + { + //Insert Block + if($i == 0) + { + $columns='leadid, '.$colName; + array_push($params, $entity_id); + } + else + { + $columns .= ', '.$colName; + } + array_push($params, $fldvalue); + } + + + } + if(isset($_REQUEST['record']) && $_REQUEST['record'] != '' && $adb->num_rows($cust_result) !=0) + { + //Update Block + $query = 'update leadcf SET '.$update.' where leadid=?'; + array_push($params, $entity_id); + $adb->pquery($query, $params); + } + else + { + //Insert Block + $query = 'insert into leadcf ('.$columns.') values('. generateQuestionMarks($params) .')'; + $adb->pquery($query, $params); + } + + } + $log->debug("Exiting save_customfields method ..."); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/Settings.php b/oss/vtiger/trunk/modules/Leads/Settings.php new file mode 100644 index 00000000..1fb34223 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/Settings.php @@ -0,0 +1,76 @@ +pquery("select * from vtiger_settings_field where name = ? and active=0",array('LBL_FIELDFORMULAS')); + if($adb->num_rows($sql_result) > 0) { + $menu_array['FieldFormulas']['location'] = $adb->query_result($sql_result, 0, 'linkto').'&formodule='.$module; + $menu_array['FieldFormulas']['image_src'] = $adb->query_result($sql_result, 0, 'iconpath'); + $menu_array['FieldFormulas']['desc'] = getTranslatedString($adb->query_result($sql_result, 0, 'description'), 'FieldFormulas'); + $menu_array['FieldFormulas']['label'] = getTranslatedString($adb->query_result($sql_result, 0, 'name'), 'FieldFormulas'); + } +} + +if(vtlib_isModuleActive('Tooltip')){ + $sql_result = $adb->pquery("select * from vtiger_settings_field where name = ? and active=0",array('LBL_TOOLTIP_MANAGEMENT')); + if($adb->num_rows($sql_result) > 0) { + $menu_array['Tooltip']['location'] = $adb->query_result($sql_result, 0, 'linkto').'&formodule='.$module; + $menu_array['Tooltip']['image_src'] = vtiger_imageurl($adb->query_result($sql_result, 0, 'iconpath'), $theme); + $menu_array['Tooltip']['desc'] = getTranslatedString($adb->query_result($sql_result, 0, 'description'),'Tooltip'); + $menu_array['Tooltip']['label'] = getTranslatedString($adb->query_result($sql_result, 0, 'name'),'Tooltip'); + } +} + +$menu_array['LeadsMapping']['location'] = 'index.php?module=Settings&action=CustomFieldList&parenttab=Settings&formodule='.$module; +$menu_array['LeadsMapping']['image_src'] = vtiger_imageurl('custom.gif', $theme); +$menu_array['LeadsMapping']['desc'] = getTranslatedString('LEADS_CUSTOM_FIELD_MAPPING_DESCRIPTION'); +$menu_array['LeadsMapping']['label'] = getTranslatedString('LEADS_CUSTOM_FIELD_MAPPING'); + + +$sql_result = $adb->pquery("SELECT * FROM vtiger_settings_field WHERE name = ? AND active=0",array('LBL_WORKFLOW_LIST')); +if($adb->num_rows($sql_result) > 0) { + $menu_array['Workflow']['location'] = $adb->query_result($sql_result, 0, 'linkto').'&list_module='.$module; + $menu_array['Workflow']['image_src'] = vtiger_imageurl($adb->query_result($sql_result, 0, 'iconpath'), $theme); + $menu_array['Workflow']['desc'] = getTranslatedString($adb->query_result($sql_result, 0, 'description'),'com_vtiger_workflow'); + $menu_array['Workflow']['label'] = getTranslatedString($adb->query_result($sql_result, 0, 'name'),'com_vtiger_workflow'); +} + +//add blanks for 3-column layout +$count = count($menu_array)%3; +if($count>0) { + for($i=0;$i<3-$count;$i++) { + $menu_array[] = array(); + } +} + +$smarty->assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("IMAGE_PATH", "themes/$theme/images/"); +$smarty->assign('MODULE',$module); +$smarty->assign('MODULE_LBL',getTranslatedString($module, $module)); +$smarty->assign('MENU_ARRAY', $menu_array); + +$smarty->display(vtlib_getModuleTemplate('Vtiger','Settings.tpl')); + +?> diff --git a/oss/vtiger/trunk/modules/Leads/TagCloud.php b/oss/vtiger/trunk/modules/Leads/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/UnifiedSearch.php b/oss/vtiger/trunk/modules/Leads/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Leads/index.php b/oss/vtiger/trunk/modules/Leads/index.php new file mode 100644 index 00000000..acccb64c --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/index.php @@ -0,0 +1,21 @@ + diff --git a/oss/vtiger/trunk/modules/Leads/language/en_us.lang.php b/oss/vtiger/trunk/modules/Leads/language/en_us.lang.php new file mode 100644 index 00000000..8dcdec4e --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/language/en_us.lang.php @@ -0,0 +1,244 @@ +'Leads', +'LBL_DIRECT_REPORTS_FORM_NAME'=>'Direct Reports', +'LBL_MODULE_TITLE'=>'Leads: Home', +'LBL_SEARCH_FORM_TITLE'=>'Lead Search', +'LBL_LIST_FORM_TITLE'=>'Lead List', +'LBL_NEW_FORM_TITLE'=>'New Lead', +'LBL_LEAD_OPP_FORM_TITLE'=>'Contact-Opportunity:', +'LBL_LEAD'=>'Lead:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', + +'LBL_LIST_NAME'=>'Name', +'LBL_LIST_LAST_NAME'=>'Last Name', +'LBL_LIST_COMPANY'=>'Company', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_LEAD_NAME'=>'Lead Name', +'LBL_LIST_EMAIL'=>'Email', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_LEAD_ROLE'=>'Role', + +'LBL_NAME'=>'Name:', +'LBL_LEAD_NAME'=>'Lead Name:', +'LBL_LEAD_INFORMATION'=>'Lead Information', +'LBL_FIRST_NAME'=>'First Name:', +'LBL_PHONE'=>'Phone:', +'LBL_COMPANY'=>'Company:', +'LBL_DESIGNATION'=>'Designation:', +'LBL_PHONE'=>'Phone:', +'LBL_LAST_NAME'=>'Last Name:', +'LBL_MOBILE'=>'Mobile:', +'LBL_EMAIL'=>'Email:', +'LBL_LEAD_SOURCE'=>'Lead Source:', +'LBL_LEAD_STATUS'=>'Lead Status:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_RATING'=>'Rating:', +'LBL_LICENSE_KEY'=>'License Key:', +'LBL_NO_OF_EMPLOYEES'=>'No. of Employees:', +'LBL_YAHOO_ID'=>'Yahoo! ID:', + +'LBL_ADDRESS_STREET'=>'Street:', +'LBL_ADDRESS_POSTAL_CODE'=>'Postal Code:', +'LBL_ADDRESS_CITY'=>'City:', +'LBL_ADDRESS_COUNTRY'=>'Country:', +'LBL_ADDRESS_STATE'=>'State:', +'LBL_ADDRESS'=>'Address:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_DESCRIPTION'=>'Description:', + +'LBL_CONVERT_LEAD'=>'Convert Lead:', +'LBL_CONVERT_LEAD_INFORMATION'=>'Convert Lead Information', +'LBL_ACCOUNT_NAME'=>'Account Name', +'LBL_POTENTIAL_NAME'=>'Potential Name', +'LBL_POTENTIAL_CLOSE_DATE'=>'Potential Close Date', +'LBL_POTENTIAL_AMOUNT'=>'Potential Amount', +'LBL_POTENTIAL_SALES_STAGE'=>'Potential Sales Stage', + + +'NTC_DELETE_CONFIRMATION'=>'Are you sure you want to delete this record?', +'NTC_REMOVE_CONFIRMATION'=>'Are you sure you want to remove this contact from this case?', +'NTC_REMOVE_DIRECT_REPORT_CONFIRMATION'=>'Are you sure you want to remove this record as a direct vtiger_report?', +'NTC_REMOVE_OPP_CONFIRMATION'=>'Are you sure you want to remove this contact from this opportunity?', +'ERR_DELETE_RECORD'=>"en_us A record number must be specified to delete the contact.", +'NTC_COPY_PRIMARY_ADDRESS'=>'Copy primary address to alternate address', +'NTC_COPY_ALTERNATE_ADDRESS'=>'Copy alternate address to primary address', + +// Added vtiger_fields in fetchfile.php, import.php -- crm4-Beta +'LBL_COLON'=>' : ', +'LBL_IMPORT_LEADS'=>'Import Leads', +'LBL_LEADS_FILE_LIST'=>'Leads File List', +'LBL_INSTRUCTIONS'=>'Instructions', +'LBL_KINDLY_PROVIDE_AN_XLS_FILE'=>'Kindly provide an .xls file alone as input', +'LBL_PROVIDE_ATLEAST_ONE_FILE'=>'Please provide at least one file as input', + +'LBL_NONE'=>'None', +'LBL_ASSIGNED_TO'=>'Assigned To:', +'LBL_SELECT_LEAD'=>'Select Lead', +'LBL_GENERAL_INFORMATION'=>'General Information', +'LBL_DO_NOT_CREATE_NEW_POTENTIAL'=>'Do not create a New Potential upon Conversion', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_NOTE'=>'New Document', +'LBL_NOTE_TITLE'=>'Documents', +'LBL_NEW_ATTACHMENT'=>'New Attachment', +'LBL_ATTACHMENT_TITLE'=>'Attachments', + + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_CONTACTED'=>'Contacted', +'LBL_LOST'=>'Lost', +'LBL_HOT'=>'Hot', +'LBL_COLD'=>'Cold', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Lead Tools', + +'LBL_SELECT_TEMPLATE_TO_MAIL_MERGE'=>'Select template to Mail Merge:', + +//Added for 4GA +'Salutation'=>'Salutation', +'First Name'=>'First Name', +'Phone'=>'Phone', +'Last Name'=>'Last Name', +'Mobile'=>'Mobile', +'Company'=>'Company', +'Fax'=>'Fax', +'Email'=>'Email', +'Lead Source'=>'Lead Source', +'Website'=>'Website', +'Annual Revenue'=>'Annual Revenue', +'Lead Status'=>'Lead Status', +'Industry'=>'Industry', +'Rating'=>'Rating', +'No Of Employees'=>'No Of Employees', +'Assigned To'=>'Assigned To', +'Yahoo Id'=>'Yahoo Id', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Street'=>'Street', +'Postal Code'=>'Postal Code', +'City'=>'City', +'Country'=>'Country', +'State'=>'State', +'Description'=>'Description', +'Po Box'=>'PO Box', +'Campaign Source'=>'Campaign Source', +//Added for CustomView 4.2 Release +'Name'=>'Name', +'LBL_NEW_LEADS'=>'My New Leads', + +//Added for Existing Picklist Entries + +'--None--'=>'--None--', +'Mr.'=>'Mr.', +'Ms.'=>'Ms.', +'Mrs.'=>'Mrs.', +'Dr.'=>'Dr.', +'Prof.'=>'Prof.', + +'Acquired'=>'Acquired', +'Active'=>'Active', +'Market Failed'=>'Market Failed', +'Project Cancelled'=>'Project Cancelled', +'Shutdown'=>'Shutdown', + +'Apparel'=>'Apparel', +'Banking'=>'Banking', +'Biotechnology'=>'Biotechnology', +'Chemicals'=>'Chemicals', +'Communications'=>'Communications', +'Construction'=>'Construction', +'Consulting'=>'Consulting', +'Education'=>'Education', +'Electronics'=>'Electronics', +'Energy'=>'Energy', +'Engineering'=>'Engineering', +'Entertainment'=>'Entertainment', +'Environmental'=>'Environmental', +'Finance'=>'Finance', +'Food & Beverage'=>'Food & Beverage', +'Government'=>'Government', +'Healthcare'=>'Healthcare', +'Hospitality'=>'Hospitality', +'Insurance'=>'Insurance', +'Machinery'=>'Machinery', +'Manufacturing'=>'Manufacturing', +'Media'=>'Media', +'Not For Profit'=>'Not For Profit', +'Recreation'=>'Recreation', +'Retail'=>'Retail', +'Shipping'=>'Shipping', +'Technology'=>'Technology', +'Telecommunications'=>'Telecommunications', +'Transportation'=>'Transportation', +'Utilities'=>'Utilities', +'Other'=>'Other', + +'Cold Call'=>'Cold Call', +'Existing Customer'=>'Existing Customer', +'Self Generated'=>'Self Generated', +'Employee'=>'Employee', +'Partner'=>'Partner', +'Public Relations'=>'Public Relations', +'Direct Mail'=>'Direct Mail', +'Conference'=>'Conference', +'Trade Show'=>'Trade Show', +'Web Site'=>'Web Site', +'Word of mouth'=>'Word of mouth', + +'Attempted to Contact'=>'Attempted to Contact', +'Cold'=>'Cold', +'Contact in Future'=>'Contact in Future', +'Contacted'=>'Contacted', +'Hot'=>'Hot', +'Junk Lead'=>'Junk Lead', +'Lost Lead'=>'Lost Lead', +'Not Contacted'=>'Not Contacted', +'Pre Qualified'=>'Pre Qualified', +'Qualified'=>'Qualified', +'Warm'=>'Warm', + +// Added/Updated for vtiger CRM 5.0.4 + +'Designation'=>'Title', + +// Added after 5.0.4 GA + +//Module Sequence Numbering +'Lead No'=>'Lead No', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Leads/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Leads/language/zh_cn.lang.php new file mode 100644 index 00000000..f101b9a4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/language/zh_cn.lang.php @@ -0,0 +1,243 @@ + '准客户', + 'LBL_DIRECT_REPORTS_FORM_NAME' => '直接输出', + 'LBL_MODULE_TITLE' => '准客户: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻准客户', + 'LBL_LIST_FORM_TITLE' => '准客户列表', + 'LBL_NEW_FORM_TITLE' => '新增准客户', + 'LBL_LEAD_OPP_FORM_TITLE' => '联络人-机会:', + 'LBL_LEAD' => '准客户:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + + 'LBL_LIST_NAME' => '姓名', + 'LBL_LIST_LAST_NAME' => '姓氏', + 'LBL_LIST_COMPANY' => '公司', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_LEAD_NAME' => '准客户名称', + 'LBL_LIST_EMAIL' => '电子邮件', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_LEAD_ROLE' => '职位', + + 'LBL_NAME' => '姓氏:', + 'LBL_LEAD_NAME' => '准客户名称:', + 'LBL_LEAD_INFORMATION' => '准客户信息', + 'LBL_FIRST_NAME' => '姓名:', + 'LBL_PHONE' => '电话:', + 'LBL_COMPANY' => '公司:', +'LBL_DESIGNATION'=>'称号:', +'LBL_PHONE'=>'电话:', +'LBL_LAST_NAME'=>'姓氏:', + 'LBL_MOBILE' => '手机:', + 'LBL_EMAIL' => '电子邮件:', + 'LBL_LEAD_SOURCE' => '准客户来源:', + 'LBL_LEAD_STATUS' => '准客户状态:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_INDUSTRY' => '企业:', + 'LBL_ANNUAL_REVENUE' => '年营业额:', + 'LBL_RATING' => '评价:', + 'LBL_LICENSE_KEY' => '许可证 Key:', + 'LBL_NO_OF_EMPLOYEES' => '员工数:', + 'LBL_YAHOO_ID' => 'Yahoo账号:', + + 'LBL_ADDRESS_STREET' => '街道巷号:', + 'LBL_ADDRESS_POSTAL_CODE' => '邮政编码:', + 'LBL_ADDRESS_CITY' => '乡镇市区:', + 'LBL_ADDRESS_COUNTRY' => '国家:', + 'LBL_ADDRESS_STATE' => '县市:', + 'LBL_ADDRESS' => '地址:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息', + 'LBL_DESCRIPTION' => '描述:', + +'LBL_CONVERT_LEAD' => '转换准客户:', + 'LBL_CONVERT_LEAD_INFORMATION' => '转换准客户信息', + 'LBL_ACCOUNT_NAME' => '客户名称', + 'LBL_POTENTIAL_NAME' => '潜在案件名称', + 'LBL_POTENTIAL_CLOSE_DATE' => '潜在案件结束日期', + 'LBL_POTENTIAL_AMOUNT' => '潜在机会金额', + 'LBL_POTENTIAL_SALES_STAGE' => '潜在机会销售策略', + + + 'NTC_DELETE_CONFIRMATION' => '您确定要删除这笔记录?', + 'NTC_REMOVE_CONFIRMATION' => '您确定要从此案件中删除这位联络人?', + 'NTC_REMOVE_DIRECT_REPORT_CONFIRMATION' => '您确里要在直接输出时移除这笔记录?', + 'NTC_REMOVE_OPP_CONFIRMATION' => '您确定要从这笔潜在案件中移除这笔联络人记录?', + 'ERR_DELETE_RECORD' => '删除这笔联络人记录必须指定记录编号.', + 'NTC_COPY_PRIMARY_ADDRESS' => '复制主要地址到替代地址', + 'NTC_COPY_ALTERNATE_ADDRESS' => '复制替代地址到主要地址', + +// Added vtiger_fields in fetchfile.php, import.php -- crm4-Beta +'LBL_COLON' => ' : ', + 'LBL_IMPORT_LEADS' => '导入准客户', + 'LBL_LEADS_FILE_LIST' => '准客户档案列表', + 'LBL_INSTRUCTIONS' => '讲解', + 'LBL_KINDLY_PROVIDE_AN_XLS_FILE' => '友善的提供输入 .xls 档案', + 'LBL_PROVIDE_ATLEAST_ONE_FILE' => '请至少提供一个档案以利于导入作业', + +'LBL_NONE' => '无', + 'LBL_ASSIGNED_TO' => '负责人:', + 'LBL_SELECT_LEAD' => '选择准客户', + 'LBL_GENERAL_INFORMATION' => '一般信息', + 'LBL_DO_NOT_CREATE_NEW_POTENTIAL' => '在转换时不要改变潜在案件', + +//for v4 release added + 'LBL_NEW_POTENTIAL' => '新增潜在案件', + 'LBL_POTENTIAL_TITLE' => '潜在案件', + + 'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '电子邮件', + 'LBL_NEW_NOTE' => '新增备忘录', + 'LBL_NOTE_TITLE' => '备忘录', + 'LBL_NEW_ATTACHMENT' => '新增附件', + 'LBL_ATTACHMENT_TITLE' => '附件', + + +//Added vtiger_fields after RC1 - Release +'LBL_ALL' => '全部', + 'LBL_CONTACTED' => '已联络', + 'LBL_LOST' => '失去', + 'LBL_HOT' => '热门', + 'LBL_COLD' => '冷淡', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '准客户工具', + + 'LBL_SELECT_TEMPLATE_TO_MAIL_MERGE' => '选择要合并的邮件样版:', + +//Added for 4GA + 'Salutation' => '问候', + 'First Name' => '姓名', + 'Phone' => '电话', + 'Last Name' => '姓氏', + 'Mobile' => '手机', + 'Company' => '公司', + 'Fax' => '传真', + 'Designation' => '任命', + 'Email' => '电子邮件', + 'Lead Source' => '准客户来源', + 'Website' => '网站', + 'Annual Revenue' => '年营业额', + 'Lead Status' => '准客户状态', + 'Industry' => '企业', + 'Rating' => '评价', + 'No Of Employees' => '员工数', + 'Assigned To' => '负责人', + 'Yahoo Id' => 'Yahoo账号', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Street' => '街道巷号', + 'Postal Code' => '邮政编码', + 'City' => '乡镇市区', + 'Country' => '国家', + 'State' => '县市', + 'Description' => '描述', + 'Po Box' => '邮政信箱', + 'Campaign Source' => '活动来源', +//Added for CustomView 4.2 Release +'Name' => '名称', + 'LBL_NEW_LEADS' => '我的新准客户', + +//Added for Existing Picklist Entries + + '--None--' => '-- 无 --', + 'Mr.' => '先生', + 'Ms.' => '小姐', + 'Mrs.' => '太太', + 'Dr.' => '博士', + 'Prof.' => '专家', + + 'Acquired' => '取得', + 'Active' => '启用', + 'Market Failed' => '市场失利', + 'Project Cancelled' => '项目取消', + 'Shutdown' => '关闭', + +'Apparel' => '存在', + 'Banking' => '银行', + 'Biotechnology' => '生物科技', + 'Chemicals' => '化学', + 'Communications' => '交通', + 'Construction' => '建筑', + 'Consulting' => '顾问', + 'Education' => '教育', + 'Electronics' => '电子', + 'Energy' => '能源', + 'Engineering' => '工程', + 'Entertainment' => '娱乐', + 'Environmental' => '环境', + 'Finance' => '财务', + 'Food & Beverage' => '饮食', + 'Government' => '政府', + 'Healthcare' => '健康照护', + 'Hospitality' => '医院', + 'Insurance' => '保险', + 'Machinery' => '机械', + 'Manufacturing' => '工厂', + 'Media' => '媒体', + 'Not For Profit' => '非营利', + 'Recreation' => '娱乐中心', + 'Retail' => '零售', + 'Shipping' => '运输', + 'Technology' => '科技', + 'Telecommunications' => '通讯', + 'Transportation' => '传输', + 'Utilities' => '工具', + 'Other' => '其它', + +'Cold Call' => '陌生拜访', + 'Existing Customer' => '既有客户', + 'Self Generated' => '自动产生', + 'Employee' => '员工', + 'Partner' => '伙伴', + 'Public Relations' => '公开关系', + 'Direct Mail' => '直接发信', + 'Conference' => '研讨会', + 'Trade Show' => '贸易展览', + 'Web Site' => '网站', + 'Word of mouth' => '口耳相传', + +'Attempted to Contact' => '尝试联系', + 'Cold' => '陌生', + 'Contact in Future' => '即将联系', + 'Contacted' => '已联系', + 'Hot' => '热络', + 'Junk Lead' => '没有潜在价值', + 'Lost Lead' => '失去准客户', + 'Not Contacted' => '尚未联系', + 'Pre Qualified' => '已事前确认', + 'Qualified' => '已确认', + 'Warm' => '一般', +// Added/Updated for vtiger CRM 5.0.4 + +'Designation'=>'Title', + +// Added after 5.0.4 GA + +//Module Sequence Numbering +'Lead No'=>'Lead No', +// END +); + +?> diff --git a/oss/vtiger/trunk/modules/Leads/updateRelations.php b/oss/vtiger/trunk/modules/Leads/updateRelations.php new file mode 100644 index 00000000..e7268851 --- /dev/null +++ b/oss/vtiger/trunk/modules/Leads/updateRelations.php @@ -0,0 +1,52 @@ +pquery("insert into vtiger_seproductsrel values (?,?,?)", array($forCRMRecord,$id,$currentModule)); + elseif($dest_mod == 'Campaigns') + $adb->pquery("insert into vtiger_campaignleadrel values(?,?)", array($id,$forCRMRecord)); + elseif($dest_mod == 'Documents') + $adb->pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Meetings/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Meetings/language/zh_cn.lang.php new file mode 100644 index 00000000..d3ab4cb6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Meetings/language/zh_cn.lang.php @@ -0,0 +1,43 @@ + '会议', + 'LBL_MODULE_TITLE' => '会议: 首页', + 'LBL_SEARCH_FORM_TITLE' => '查找会议', + 'LBL_LIST_FORM_TITLE' => '会议列表', + 'LBL_NEW_FORM_TITLE' => '安排会议', + 'LBL_LIST_SUBJECT' => '主题', + 'LBL_LIST_CONTACT' => '联系人', + 'LBL_LIST_RELATED_TO' => '相关对象', + 'LBL_LIST_DATE' => '开始日期', + 'LBL_LIST_TIME' => '开始时间', + 'LBL_LIST_CLOSE' => '完成', + 'LBL_SUBJECT' => '主题: ', + 'LBL_STATUS' => '状态:', + 'LBL_LOCATION' => '位置:', + 'LBL_DATE_TIME' => '开始时间和日期:', + 'LBL_DATE' => '开始日期:', + 'LBL_TIME' => '开始时间:', + 'LBL_DURATION' => '持续时间:', + 'LBL_HOURS_MINS' => '(小时/分钟)', + 'LBL_CONTACT_NAME' => '联系人姓名: ', + 'LBL_MEETING' => '会议:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_COLON' => ':', + 'LBL_DEFAULT_STATUS' => '已计划', + 'LNK_NEW_LEAD' => '新增线索', + 'LNK_NEW_CONTACT' => '新增联系人', + 'LNK_NEW_ACCOUNT' => '新增客户', + 'LNK_NEW_OPPORTUNITY' => '新增商机', + 'LNK_NEW_CASE' => '新增拜访', + 'LNK_NEW_NOTE' => '新增备忘录', + 'LNK_NEW_CALL' => '新增电话', + 'LNK_NEW_EMAIL' => '新增Email', + 'LNK_NEW_MEETING' => '新增会议', + 'LNK_NEW_TASK' => '新增任务', + 'ERR_DELETE_RECORD' => '必须指定记录编号才能删除会议.', + 'NTC_REMOVE_INVITEE' => '你确定要删除这个会议邀请嗎?', + 'LBL_INVITEE' => '受邀者', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/MessageBoard/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/MessageBoard/language/zh_cn.lang.php new file mode 100644 index 00000000..0d956cb3 --- /dev/null +++ b/oss/vtiger/trunk/modules/MessageBoard/language/zh_cn.lang.php @@ -0,0 +1,69 @@ + 'Message Board', + 'LBL_MODULE_TITLE' => 'Message Board: Home', + 'LBL_SEARCH_FORM_TITLE' => '查找主题', + 'LBL_LIST_FORM_TITLE' => '主题列表', + 'LBL_NEW_FORM_TITLE' => '发表新主题', + 'LBL_LEAD' => 'Message Boardx:', + 'LBL_LIST_TOPIC' => '主题', + 'LBL_LIST_LAST_NAME' => '名', + 'LBL_LIST_CATEGORY' => '分类', + 'LBL_LIST_REPLIES' => '回复', + 'LBL_LIST_LEAD_NAME' => '线索名称', + 'LBL_LIST_LAST_POST' => '最新主题', + 'LBL_LIST_AUTHOR' => '作者', + 'LBL_LIST_LEAD_ROLE' => '角色', + 'LBL_NAME' => '名字:', + 'LBL_LEAD_NAME' => '线索名称:', + 'LBL_LEAD_INFORMATION' => '线索信息:', + 'LBL_FIRST_NAME' => '姓:', + 'LBL_PHONE' => '电话:', + 'LBL_COMPANY' => '公司:', + 'LBL_DESIGNATION' => '目的地:', + 'LBL_LAST_NAME' => '名:', + 'LBL_MOBILE' => '手机:', + 'LBL_EMAIL' => 'Email:', + 'LBL_LEAD_SOURCE' => '线索来源:', + 'LBL_LEAD_STATUS' => '线索状态:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_INDUSTRY' => '行业:', + 'LBL_ANNUAL_REVENUE' => '年收入:', + 'LBL_RATING' => '评价:', + 'LBL_LICENSE_KEY' => '许可证Key:', + 'LBL_NO_OF_EMPLOYEES' => '员工数量:', + 'LBL_YAHOO_ID' => 'Yahoo! ID:', + 'LBL_ADDRESS_STREET' => '街道:', + 'LBL_ADDRESS_POSTAL_CODE' => '邮编:', + 'LBL_ADDRESS_CITY' => '城市:', + 'LBL_ADDRESS_COUNTRY' => '国家:', + 'LBL_ADDRESS_STATE' => '省份:', + 'LBL_ADDRESS' => '地址:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息:', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_CONVERT_LEAD' => '转变线索:', + 'LBL_CONVERT_LEAD_INFORMATION' => '转变线索信息', + 'LBL_ACCOUNT_NAME' => '客户姓名', + 'LBL_POTENTIAL_NAME' => '商机名称', + 'LBL_POTENTIAL_CLOSE_DATE' => '商机完成日期', + 'LNK_NEW_LEAD' => '新增线索', + 'LNK_NEW_CONTACT' => '新增联系人', + 'LNK_NEW_ACCOUNT' => '新增客户', + 'LNK_NEW_OPPORTUNITY' => '新增商机', + 'LNK_NEW_CASE' => '新增拜访', + 'LNK_NEW_NOTE' => '新增备忘录', + 'LNK_NEW_CALL' => '新增电话', + 'LNK_NEW_EMAIL' => '撰写新邮件', + 'LNK_NEW_MEETING' => '新增会议', + 'LNK_NEW_TASK' => '新增任务', + 'NTC_DELETE_CONFIRMATION' => '你确认删除这条记录?', + 'NTC_REMOVE_CONFIRMATION' => 'Are you sure you want to remove this contact from this case?', + 'NTC_REMOVE_DIRECT_REPORT_CONFIRMATION' => 'Are you sure you want to remove this record as a direct report?', + 'NTC_REMOVE_OPP_CONFIRMATION' => 'Are you sure you want to remove this contact from this opportunity?', + 'ERR_DELETE_RECORD' => 'en_us A record number must be specified to delete the contact.', + 'NTC_COPY_PRIMARY_ADDRESS' => '将主地址內容复制到备用地址', + 'NTC_COPY_ALTERNATE_ADDRESS' => '将备用地址內容复制到主地址', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/42P2_to_50.php b/oss/vtiger/trunk/modules/Migration/DBChanges/42P2_to_50.php new file mode 100644 index 00000000..814cb6b3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/42P2_to_50.php @@ -0,0 +1,4236 @@ +debug("\n\nDB Changes from 4.2.x to 5.0 GA -------- Starts \n\n"); + +//Added to put prefix vtiger_ in some of the columns in tables which are used for CV and Reports and field -- 23-06-06 +$migrationlog->debug("Going to rename the table names with prefix vtiger_"); +include("modules/Migration/rename_tables.php"); +$migrationlog->debug("Renaming the table names with prefix vtiger_ has been finished"); + + +$migrationlog->debug("Database Modifications for 4.2 Patch2 ==> 5.0(Alpha) Dev 3 Starts here."); + + +//These changes have been made in 4.2.3. The following queries have been included who has run the migration from 4.2 Patch2 +$wordtemp = $conn->getColumnNames("vtiger_wordtemplates"); +if(is_array($wordtemp) && !in_array("templateid",$wordtemp)) +{ + $wordtemplate_query1 = "alter table vtiger_wordtemplates DROP PRIMARY KEY"; + Execute($wordtemplate_query1); + + $wordtemplate_query3 = "alter table vtiger_wordtemplates add column templateid integer(19) unsigned auto_increment primary key FIRST"; + Execute($wordtemplate_query3); +} +//upto this added to modify the wordtemplates table which will be in the case of migrate from 4.2 Path2. + + + +/****************** 5.0(Alpha) dev version 1 Database changes -- Starts*********************/ + + +//Added the vtiger_announcement table creation to avoid the error +$ann_query = "CREATE TABLE vtiger_announcement ( + `creatorid` int(19) NOT NULL, + `announcement` text, + `title` varchar(255) default NULL, + `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, + PRIMARY KEY (`creatorid`), + KEY `announcement_UK01` (`creatorid`) + ) ENGINE=InnoDB"; +Execute($ann_query); + +//Added Primay Keys for the left out tables +$alter_array1 = Array( + "alter table vtiger_activity_reminder ADD PRIMARY KEY (activity_id,recurringid)", + "alter table vtiger_activitygrouprelation ADD PRIMARY KEY (activityid)", + "alter table vtiger_cvadvfilter ADD PRIMARY KEY (cvid,columnindex)", + "alter table vtiger_cvcolumnlist ADD PRIMARY KEY (cvid,columnindex)", + "alter table vtiger_cvstdfilter ADD PRIMARY KEY (cvid)", + "alter table vtiger_def_org_field ADD PRIMARY KEY (fieldid)", + "alter table vtiger_leadgrouprelation ADD PRIMARY KEY (leadid)", + "alter table vtiger_leadgrouprelation drop key leadgrouprelation_IDX0", + "alter table vtiger_profile2field ADD PRIMARY KEY (profileid,fieldid)", + "alter table vtiger_profile2standardpermissions ADD PRIMARY KEY (profileid,tabid,Operation)", + "alter table vtiger_profile2standardpermissions drop index idx_prof2stad", + "alter table vtiger_profile2utility ADD PRIMARY KEY (profileid,tabid,activityid)", + "alter table vtiger_profile2utility drop index idx_prof2utility", + "alter table vtiger_relcriteria ADD PRIMARY KEY (queryid,columnindex)", + "alter table vtiger_reportdatefilter ADD PRIMARY KEY (datefilterid)", + "alter table vtiger_reportdatefilter DROP INDEX reportdatefilter_IDX0", + "alter table vtiger_reportsortcol ADD PRIMARY KEY (sortcolid,reportid)", + "alter table vtiger_reportsummary ADD PRIMARY KEY (reportsummaryid,summarytype,columnname)", + "drop table vtiger_role2action", + "drop table vtiger_role2tab", + "alter table vtiger_selectcolumn ADD PRIMARY KEY (queryid,columnindex)", + "alter table vtiger_ticketgrouprelation ADD PRIMARY KEY (ticketid)", + "alter table vtiger_ticketstracktime ADD PRIMARY KEY (ticket_id)", + "alter table vtiger_users2group ADD PRIMARY KEY (groupname,userid)", + "alter table vtiger_users2group DROP INDEX idx_users2group", + ); +foreach($alter_array1 as $query) +{ + Execute($query); +} + +//Tables vtiger_profile2globalpermissions, vtiger_actionmapping creation + +$create_sql1 ="CREATE TABLE vtiger_profile2globalpermissions (`profileid` int(19) NOT NULL, `globalactionid` int(19) NOT NULL, `globalactionpermission` int(19) default NULL, PRIMARY KEY (`profileid`,`globalactionid`), KEY `idx_profile2globalpermissions` (`profileid`,`globalactionid`)) ENGINE=InnoDB"; + +Execute($create_sql1); + +$create_sql2 = "CREATE TABLE vtiger_actionmapping (`actionid` int(19) NOT NULL, `actionname` varchar(200) NOT NULL, `securitycheck` int(19) default NULL, PRIMARY KEY (`actionid`,`actionname`)) TYPE=InnoDB"; +Execute($create_sql2); + +//For all Profiles, insert the following entries into vtiger_profile2global permissions table: +$sql = 'select * from vtiger_profile'; +$res = $conn->query($sql); +$noofprofiles = $conn->num_rows($res); + +for($i=0;$i<$noofprofiles;$i++) +{ + $profile_id = $conn->query_result($res,$i,'profileid'); + + $sql1 = "insert into vtiger_profile2globalpermissions values ($profile_id,1,1)"; + $sql2 = "insert into vtiger_profile2globalpermissions values ($profile_id,2,1)"; + + Execute($sql1); + Execute($sql2); +} + + +//Removing entries for Dashboard and Home module from vtiger_profile2standardpermissions table +$del_query1 = "delete from vtiger_profile2standardpermissions where tabid in(1,3)"; +Execute($del_query1); + +//For all Profile do the following insert into vtiger_profile2utility table: +$sql = 'select * from vtiger_profile'; +$res = $conn->query($sql); +$noofprofiles = $conn->num_rows($res); + +/* Commented by Don. Handled below +for($i=0;$i<$noofprofiles;$i++) +{ + $profile_id = $conn->query_result($res,$i,'profileid'); + + $sql1 = "insert into vtiger_profile2utility values ($profile_id,4,7,0)"; + $sql2 = "insert into vtiger_profile2utility values ($profile_id,7,9,0)"; + + Execute($sql1); + Execute($sql2); +} +*/ + +//Insert Values into action mapping table: +$actionmapping_array = Array( + "insert into vtiger_actionmapping values(0,'Save',0)", + "insert into vtiger_actionmapping values(1,'EditView',0)", + "insert into vtiger_actionmapping values(2,'Delete',0)", + "insert into vtiger_actionmapping values(3,'index',0)", + "insert into vtiger_actionmapping values(4,'DetailView',0)", + "insert into vtiger_actionmapping values(5,'Import',0)", + "insert into vtiger_actionmapping values(6,'Export',0)", + "insert into vtiger_actionmapping values(8,'Merge',0)", + "insert into vtiger_actionmapping values(1,'VendorEditView',1)", + "insert into vtiger_actionmapping values(4,'VendorDetailView',1)", + "insert into vtiger_actionmapping values(0,'SaveVendor',1)", + "insert into vtiger_actionmapping values(2,'DeleteVendor',1)", + "insert into vtiger_actionmapping values(1,'PriceBookEditView',1)", + "insert into vtiger_actionmapping values(4,'PriceBookDetailView',1)", + "insert into vtiger_actionmapping values(0,'SavePriceBook',1)", + "insert into vtiger_actionmapping values(2,'DeletePriceBook',1)", + "insert into vtiger_actionmapping values(1,'SalesOrderEditView',1)", + "insert into vtiger_actionmapping values(4,'SalesOrderDetailView',1)", + "insert into vtiger_actionmapping values(0,'SaveSalesOrder',1)", + "insert into vtiger_actionmapping values(2,'DeleteSalesOrder',1)", + "insert into vtiger_actionmapping values(9,'ConvertLead',0)", + "insert into vtiger_actionmapping values(1,'DetailViewAjax',1)", + "insert into vtiger_actionmapping values(1,'QuickCreate',1)", + "insert into vtiger_actionmapping values(4,'TagCloud',1)" + ); +foreach($actionmapping_array as $query) +{ + Execute($query); +} + + +//Added two columns in vtiger_field table to construct the quickcreate form dynamically +$alter_array2 = Array( + "ALTER TABLE vtiger_field ADD column quickcreate int(10) after typeofdata", + "ALTER TABLE vtiger_field ADD column quickcreatesequence int(19) after quickcreate", + ); +foreach($alter_array2 as $query) +{ + Execute($query); +} + +$update_array1 = Array( + "UPDATE vtiger_field SET quickcreate = 1,quickcreatesequence = 0", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 2 and fieldlabel = 'Potential Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 2 and fieldlabel = 'Account Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 2 and fieldlabel = 'Expected Close Date'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 4 WHERE tabid = 2 and fieldlabel = 'Sales Stage'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 5 WHERE tabid = 2 and fieldlabel = 'Amount'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 4 and fieldlabel = 'First Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 4 and fieldlabel = 'Last Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 4 and fieldlabel = 'Account Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 4 WHERE tabid = 4 and fieldlabel = 'Office Phone'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 5 WHERE tabid = 4 and fieldlabel = 'Email'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 6 and fieldlabel = 'Account Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 6 and fieldlabel = 'Phone'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 6 and fieldlabel = 'Website'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 7 and fieldlabel = 'First Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 7 and fieldlabel = 'Last Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 7 and fieldlabel = 'Company'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 4 WHERE tabid = 7 and fieldlabel = 'Phone'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 5 WHERE tabid = 7 and fieldlabel = 'Email'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 8 and fieldlabel = 'Subject'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 9 and fieldlabel = 'Subject'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 9 and fieldlabel = 'Start Date & Time'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 10 and fieldlabel = 'Subject'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 10 and fieldlabel = 'Date & Time Sent'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 13 and fieldlabel = 'Title'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 13 and fieldlabel = 'Description'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 13 and fieldlabel = 'Priority'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 14 and fieldlabel = 'Product Name'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 14 and fieldlabel = 'Product Code'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 14 and fieldlabel = 'Product Category'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 16 and fieldlabel = 'Subject'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 16 and fieldlabel = 'Start Date & Time'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 16 and fieldlabel = 'Activity Type'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 4 WHERE tabid = 16 and fieldlabel = 'Duration'", + ); +foreach($update_array1 as $query) +{ + Execute($query); +} + +//Added for the "Color By User in Calendar " which has been contributed by Cesar +$alter_query1 = "ALTER TABLE vtiger_users ADD cal_color VARCHAR(25) DEFAULT '#E6FAD8' AFTER user_hash"; +Execute($alter_query1); + +//code contributed by Fredy for color vtiger_priority +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query1 = "insert into vtiger_field values (16,".$newfieldid.",'priority','activity',1,15,'taskpriority','Priority',1,0,0,100,17,1,1,'V~O',1,'')"; +Execute($insert_query1); + +//Added on 23-12-2005 which is missed from Fredy's contribution for Color vtiger_priority +populateFieldForSecurity('16',$newfieldid); +$activity_cols = $conn->getColumnNames("vtiger_activity"); +if(is_array($activity_cols) && !in_array("priority",$activity_cols)) +{ + $activity_alter_query = "alter table vtiger_activity add column priority varchar(150) default NULL"; + Execute($activity_alter_query); +} +//Code contributed by Raju for better emailing +/* +$insert_array1 = Array( + "insert into vtiger_field values (10,".$conn->getUniqueID("vtiger_field").",'crmid','seactivityrel',1,'357','parent_id','Related To',1,0,0,100,1,2,1,'I~O',1,'')", + "insert into vtiger_field values (10,".$conn->getUniqueID("vtiger_field").",'subject','activity',1,'2','subject','Subject',1,0,0,100,1,3,1,'V~M',0,1)", + "insert into vtiger_field values (10,".$conn->getUniqueID("vtiger_field").",'filename','emails',1,'61','filename','Attachment',1,0,0,100,1,4,1,'V~O',1,'')", + "insert into vtiger_field values (10,".$conn->getUniqueID("vtiger_field").",'description','emails',1,'19','description','Description',1,0,0,100,1,5,1,'V~O',1,'')", + ); +*/ +//commented the above array as that queries are wrong queries -- changed on 23-12-2005 +$insert_array1 = array( + "update vtiger_field set uitype='357' where tabid=10 and fieldname='parent_id' and tablename='vtiger_seactivityrel'", + "update vtiger_field set sequence=1 where tabid=10 and fieldname in ('parent_id','subject','filename','description')", + "update vtiger_field set block=2 where tabid=10 and fieldname='parent_id'", + "update vtiger_field set block=3 where tabid=10 and fieldname='subject'", + "update vtiger_field set block=4 where tabid=10 and fieldname='filename'", + "update vtiger_field set block=5 where tabid=10 and fieldname='description'", + ); +foreach($insert_array1 as $query) +{ + Execute($query); +} + +//code contributed by mike to rearrange the home page +$alter_query2 = "alter table vtiger_users add column homeorder varchar(255) default 'ALVT,PLVT,QLTQ,CVLVT,HLT,OLV,GRT,OLTSO,ILTI' after date_format"; +Execute($alter_query2); + +//Added one column in vtiger_invoice table to include 'Contact Name' vtiger_field in Invoice module +$alter_query3 = "ALTER TABLE vtiger_invoice ADD column contactid int(19) after customerno"; +Execute($alter_query3); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query2 = "insert into vtiger_field values (23,".$newfieldid.",'contactid','invoice',1,'57','contact_id','Contact Name',1,0,0,100,4,1,1,'I~O',1,'')"; +Execute($insert_query2); +//Added on 23-12-2005 because we must populate vtiger_field entries in vtiger_profile2field and vtiger_def_org_field if we add a vtiger_field in vtiger_field table +populateFieldForSecurity('23',$newfieldid); + +//changes made to fix the bug in Address Information block of Accounts and Contacs module +$update_array2 = Array( + "UPDATE vtiger_field SET fieldlabel='Billing City', sequence=5 WHERE tabid=6 and fieldname='bill_city'", + "UPDATE vtiger_field SET fieldlabel='Billing State', sequence=7 WHERE tabid=6 and fieldname='bill_state'", + "UPDATE vtiger_field SET fieldlabel='Billing Code', sequence=9 WHERE tabid=6 and fieldname='bill_code'", + "UPDATE vtiger_field SET fieldlabel='Billing Country', sequence=11 WHERE tabid=6 and fieldname='bill_country'", + + "UPDATE vtiger_field SET fieldlabel='Shipping City', sequence=6 WHERE tabid=6 and fieldname='ship_city'", + "UPDATE vtiger_field SET fieldlabel='Shipping State', sequence=8 WHERE tabid=6 and fieldname='ship_state'", + "UPDATE vtiger_field SET fieldlabel='Shipping Code', sequence=10 WHERE tabid=6 and fieldname='ship_code'", + "UPDATE vtiger_field SET fieldlabel='Shipping Country', sequence=12 WHERE tabid=6 and fieldname='ship_country'", + + "UPDATE vtiger_field SET fieldlabel='Mailing City', sequence=5 WHERE tabid=4 and fieldname='mailingcity'", + "UPDATE vtiger_field SET fieldlabel='Mailing State', sequence=7 WHERE tabid=4 and fieldname='mailingstate'", + "UPDATE vtiger_field SET fieldlabel='Mailing Zip', sequence=9 WHERE tabid=4 and fieldname='mailingzip'", + "UPDATE vtiger_field SET fieldlabel='Mailing Country', sequence=11 WHERE tabid=4 and fieldname='mailingcountry'", + + "UPDATE vtiger_field SET fieldlabel='Other City', sequence=6 WHERE tabid=4 and fieldname='othercity'", + "UPDATE vtiger_field SET fieldlabel='Other State', sequence=8 WHERE tabid=4 and fieldname='otherstate'", + "UPDATE vtiger_field SET fieldlabel='Other Zip', sequence=10 WHERE tabid=4 and fieldname='otherzip'", + "UPDATE vtiger_field SET fieldlabel='Other Country', sequence=12 WHERE tabid=4 and fieldname='othercountry'", + ); +foreach($update_array2 as $query) +{ + Execute($query); +} + + +//Added vtiger_field emailoptout in vtiger_account table +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query3 = "insert into vtiger_field values (6,".$newfieldid.",'emailoptout','account',1,'56','emailoptout','Email Opt Out',1,0,0,100,17,1,1,'C~O',1,'')"; +Execute($insert_query3); + +//Added on 23-12-2005 because we must populate vtiger_field entries in vtiger_profile2field and vtiger_def_org_field if we add a vtiger_field in vtiger_field table +populateFieldForSecurity('6',$newfieldid); + +//Added on 22-12-2005 +$alter_query4 = "alter table vtiger_account add column emailoptout varchar(3) default 0"; +Execute($alter_query4); + +$update_array3 = Array( + "update vtiger_field set sequence=18 where tabid=6 and fieldname ='assigned_user_id'", + "update vtiger_field set sequence=19 where tabid=6 and fieldname ='createdtime'", + "update vtiger_field set sequence=19 where tabid=6 and fieldname ='modifiedtime'", + ); +foreach($update_array3 as $query) +{ + Execute($query); +} + + +//create table vtiger_moduleowners to assign the module and corresponding owners +$create_query2 = "CREATE TABLE vtiger_moduleowners ( + `tabid` int(19) NOT NULL default '0', + `user_id` varchar(11) NOT NULL, + PRIMARY KEY (`tabid`), + KEY `moduleowners_tabid_user_id_idx` (`tabid`,`user_id`) + ) ENGINE=InnoDB"; + +/* +$create_query2 = "CREATE TABLE vtiger_moduleowners +( + `tabid` int(19) NOT NULL default '0', + `user_id` varchar(11) NOT NULL default '', + PRIMARY KEY (`tabid`), + CONSTRAINT `fk_ModuleOwners` FOREIGN KEY (`tabid`) REFERENCES `vtiger_tab` (`tabid`) ON DELETE CASCADE +) TYPE=InnoDB"; +*/ +Execute($create_query2); + +//Populated the default entries for vtiger_moduleowners which is created newly +$module_array = Array( + 'Potentials', + 'Contacts', + 'Accounts', + 'Leads', + 'Notes', + 'Activities', + 'Emails', + 'HelpDesk', + 'Products', + 'Faq', + 'Vendor', + 'PriceBook', + 'Quotes', + 'Orders', + 'SalesOrder', + 'Invoice', + 'Reports' + ); +foreach($module_array as $mod) +{ + $query = "insert into vtiger_moduleowners values(".$this->localGetTabID($mod).",1)"; + Execute($query); +} + + +//Changes made to include status vtiger_field in Activity Quickcreate Form +$update_array4 = Array( + "UPDATE vtiger_field SET quickcreate=0,quickcreatesequence=3 WHERE tabid=16 and fieldname='eventstatus'", + "UPDATE vtiger_field SET quickcreate=0,quickcreatesequence=4 WHERE tabid=16 and fieldname='activitytype'", + "UPDATE vtiger_field SET quickcreate=0,quickcreatesequence=5 WHERE tabid=16 and fieldname='duration_hours'", + + "UPDATE vtiger_field SET quickcreate=0,quickcreatesequence=3 WHERE tabid=9 and fieldname='taskstatus'", + ); +foreach($update_array4 as $query) +{ + Execute($query); +} + + + +//Table 'inventory_tandc' added newly to include Inventory Terms &Conditions +$create_query1 = "CREATE TABLE vtiger_inventory_tandc(id INT(19),type VARCHAR(30) NOT NULL,tandc LONGTEXT default NULL,PRIMARY KEY(id))"; +Execute($create_query1); + +$insert_query4 = "insert into vtiger_inventory_tandc values('".$conn->getUniqueID('vtiger_inventory_tandc')."','Inventory',' ')"; +Execute($insert_query4); + +/****************** 5.0(Alpha) dev version 1 Database changes -- Ends*********************/ + + + + + + + + + + +/****************** 5.0(Alpha) dev version 2 Database changes -- Starts*********************/ + +$query1 = "ALTER TABLE vtiger_leadaddress change lane lane varchar(250)"; +Execute($query1); + +$rename_table_array1 = Array( + "update vtiger_field set tablename='vtiger_customerdetails' where tabid=4 and fieldname in ('portal','support_start_date','support_end_date')", + "alter table vtiger_PortalInfo drop foreign key fk_PortalInfo", + "rename table vtiger_PortalInfo to vtiger_portalinfo", + "alter table vtiger_portalinfo add CONSTRAINT `fk_portalinfo` FOREIGN KEY (`id`) REFERENCES `vtiger_contactdetails` (`contactid`) ON DELETE CASCADE", + "alter table vtiger_CustomerDetails drop foreign key fk_CustomerDetails", + "rename table vtiger_CustomerDetails to vtiger_customerdetails", + "alter table vtiger_customerdetails add CONSTRAINT `fk_customerdetails` FOREIGN KEY (`customerid`) REFERENCES `vtiger_contactdetails` (`contactid`) ON DELETE CASCADE" + ); +foreach($rename_table_array1 as $query) +{ + Execute($query); +} + + +$query2 = "create table vtiger_ownernotify(crmid int(19),smownerid int(19),flag int(3))"; +Execute($query2); + + +//Form the vtiger_role_map_array as vtiger_roleid=>name mapping array +$sql = "select * from vtiger_role"; +$res = $conn->query($sql); +$role_map_array = Array(); +for($i=0;$i<$conn->num_rows($res);$i++) +{ + $roleid = $conn->query_result($res,$i,'roleid'); + $name = $conn->query_result($res,$i,'name'); + $role_map_array[$roleid] = $name; +} +$conn->println("List of Roles (roleid => name) ==> ");$conn->println($role_map_array); +//echo '
     List of vtiger_roles :';print_r($role_map_array);echo '
    '; + +//Before delete the vtiger_role take a backup array for the table vtiger_user2role +$sql = "select * from vtiger_user2role"; +$res = $conn->query($sql); +$user2role_array = array(); +for($i=0;$i<$conn->num_rows($res);$i++) +{ + $userid = $conn->query_result($res,$i,'userid'); + $roleid = $conn->query_result($res,$i,'roleid'); + $user2role_array[$userid] = $roleid; +} +$conn->println("Users 2 Roles (userid => roleid) ==> ");$conn->println($user2role_array); +//echo '
     List of vtiger_user2role : (userid => vtiger_roleid)';print_r($user2role_array);echo '
    '; + +//Delete the vtiger_role entries +$sql = "truncate vtiger_role"; +Execute($sql); + + +$query3 = "alter table vtiger_user2role drop FOREIGN KEY fk_user2role2"; +Execute($query3); + +//4,5 th are the Extra added queries +$alter_query_array1 = Array( + "alter table vtiger_user2role change roleid roleid varchar(255)", + "alter table vtiger_role2profile change roleid roleid varchar(255)", + "alter table vtiger_role CHANGE roleid roleid varchar(255)", + "alter table vtiger_role2profile drop PRIMARY KEY", + "alter table vtiger_role2profile ADD PRIMARY KEY (roleid,profileid)" + ); +foreach($alter_query_array1 as $query) +{ + Execute($query); +} + + +$query4 = "ALTER TABLE vtiger_user2role ADD CONSTRAINT fk_user2role2 FOREIGN KEY (roleid) REFERENCES vtiger_role(roleid) ON DELETE CASCADE"; +Execute($query4); + +$alter_query_array2 = Array( + "alter table vtiger_role CHANGE name rolename varchar(200)", + "alter table vtiger_role DROP description", + "alter table vtiger_role add parentrole varchar(255)", + "alter table vtiger_role add depth int(19)" + ); +foreach($alter_query_array2 as $query) +{ + Execute($query); +} + + + +$query5 = "insert into vtiger_role values('H1','Organisation','H1',0)"; +Execute($query5); + +//include("include/utils/UserInfoUtil.php"); +//Create vtiger_role based on vtiger_role_map_array values and form the new_role_map_array with old vtiger_roleid and new vtiger_roleid +foreach($role_map_array as $roleid => $rolename) +{ + $parentRole = 'H1'; + if($rolename == 'standard_user') + { + $rs = $conn->query("select * from vtiger_role where rolename='administrator'"); + $parentRole = $conn->query_result($rs,0,'roleid'); + } + $empty_array = array(""=>""); + $new_role_id = localcreateRole($rolename,$parentRole,$empty_array); + $new_role_map_array[$roleid] = $new_role_id; +} +$conn->println("Roles (oldroleid => newroleid) ==> ");$conn->println($new_role_map_array); + +//Before insert the new entry we should remove the old entries -- added on 06-06-06 +$user2role_del = "truncate vtiger_user2role"; +Execute($user2role_del); + +//First we will insert the old values from vtiger_user2role_array to vtiger_user2role table and then update the new vtiger_role id +foreach($user2role_array as $userid => $roleid) +{ + $sql = "insert into vtiger_user2role (userid, roleid) values(".$userid.",'".$new_role_map_array[$roleid]."')"; + Execute($sql); +} +//Commented the following loop as we have backup the vtiger_user2role and insert the entries with the new rold id using new_role_map_array above +//Update the vtiger_user2role table with new vtiger_roleid +/* + foreach($new_role_map_array as $old_roleid => $new_roleid) + { + $update_user2role = "update vtiger_user2role set vtiger_roleid='".$new_roleid."' where vtiger_roleid=".$old_roleid; + Execute($update_user2role); + } + */ +//Update the vtiger_role2profile table with new vtiger_roleid +foreach($new_role_map_array as $old_roleid => $new_roleid) +{ + $update_role2profile = "update vtiger_role2profile set roleid='".$new_roleid."' where roleid=".$old_roleid; + Execute($update_role2profile); +} + + + +//Group Migration: +//Step 1 : form and group_map_array as groupname => description from vtiger_groups table +//Step 2 : form an vtiger_users2group_map_array array as userid => groupname from vtiger_users2group table +//Step 3 : delete all entries from vtiger_groups table and enter new values from group_map_array +//Step 4 : drop the table vtiger_users2group and create new table +//Step 5 : put entries to vtiger_users2group table based on vtiger_users2group_map_array. Here get the groupid from vtiger_groups table based on groupname + +//Step 1 : Form the group_map_array as groupname => description +$sql = "select * from vtiger_groups"; +$res = $conn->query($sql); +$group_map_array = Array(); +for($i=0;$i<$conn->num_rows($res);$i++) +{ + $name = $conn->query_result($res,$i,'name'); + $desc = $conn->query_result($res,$i,'description'); + $group_map_array[$name] = $desc; +} +$conn->println("List of Groups (name => description) ==> ");$conn->println($group_map_array); +//echo '
    List of Groups : ';print_r($group_map_array);echo '
    '; + + +//Step 2 : form an vtiger_users2group_map_array array as userid => groupname from vtiger_users2group table +$sql = "select * from vtiger_users2group"; +$res = $conn->query($sql); +$users2group_map_array = Array(); +for($i=0;$i<$conn->num_rows($res);$i++) +{ + $groupname = $conn->query_result($res,$i,'groupname'); + $userid = $conn->query_result($res,$i,'userid'); + $users2group_map_array[$userid] = $groupname; +} +$conn->println("Users 2 Groups (userid => groupname) ==> ");$conn->println($users2group_map_array); +//echo '
    List of vtiger_users2group : ';print_r($users2group_map_array);echo '
    '; + +//Step 3 : delete all entries from vtiger_groups table +$sql = "truncate vtiger_groups"; +Execute($sql); + +$alter_query_array3 = Array( + "alter table vtiger_users2group drop FOREIGN KEY fk_users2group", + "alter table vtiger_leadgrouprelation drop FOREIGN KEY fk_leadgrouprelation2", + "alter table vtiger_activitygrouprelation drop FOREIGN KEY fk_activitygrouprelation2", + "alter table vtiger_ticketgrouprelation drop FOREIGN KEY fk_ticketgrouprelation2", + "alter table vtiger_groups drop PRIMARY KEY" + ); +foreach($alter_query_array3 as $query) +{ + Execute($query); +} + +//2 nd query is the Extra added query +//Adding columns in group table: +$alter_query_array4 = Array( + "alter table vtiger_groups add column groupid int(19) FIRST", + "alter table vtiger_groups change name groupname varchar(100)", + "alter table vtiger_groups ADD PRIMARY KEY (groupid)", + "alter table vtiger_groups add index (groupname)" + ); +foreach($alter_query_array4 as $query) +{ + Execute($query); +} + + +//Moved the create table queries for vtiger_group2grouprel, vtiger_group2role, vtiger_group2rs from the end of this block +//Added on 06-06-06 +$query8 = "CREATE TABLE vtiger_group2grouprel ( + `groupid` int(19) NOT NULL, + `containsgroupid` int(19) NOT NULL, + PRIMARY KEY (`groupid`,`containsgroupid`) + ) ENGINE=InnoDB"; + /* +$query8 = "CREATE TABLE vtiger_group2grouprel +( + `groupid` int(19) NOT NULL default '0', + `containsgroupid` int(19) NOT NULL default '0', + PRIMARY KEY (`groupid`,`containsgroupid`), + CONSTRAINT `fk_group2grouprel1` FOREIGN KEY (`groupid`) REFERENCES `vtiger_groups` (`groupid`) ON DELETE CASCADE +) TYPE=InnoDB"; +*/ +Execute($query8); + +//Added on 06-06-06 +$query9 = "CREATE TABLE vtiger_group2role ( + `groupid` int(19) NOT NULL, + `roleid` varchar(255) NOT NULL, + PRIMARY KEY (`groupid`,`roleid`) + ) ENGINE=InnoDB"; +/* +$query9 = "CREATE TABLE vtiger_group2role +( + `groupid` int(19) NOT NULL default '0', + `roleid` varchar(255) NOT NULL default '', + PRIMARY KEY (`groupid`,`roleid`), + CONSTRAINT `fk_group2role1` FOREIGN KEY (`groupid`) REFERENCES `vtiger_groups` (`groupid`) ON DELETE CASCADE +) TYPE=InnoDB"; +*/ +Execute($query9); + +//Added on 06-06-06 +$query10 = "CREATE TABLE vtiger_group2rs ( + `groupid` int(19) NOT NULL, + `roleandsubid` varchar(255) NOT NULL, + PRIMARY KEY (`groupid`,`roleandsubid`) + ) ENGINE=InnoDB"; +/* +$query10 = "CREATE TABLE vtiger_group2rs +( + `groupid` int(19) NOT NULL default '0', + `roleandsubid` varchar(255) NOT NULL default '', + PRIMARY KEY (`groupid`,`roleandsubid`), + CONSTRAINT `fk_group2rs1` FOREIGN KEY (`groupid`) REFERENCES `vtiger_groups` (`groupid`) ON DELETE CASCADE +) TYPE=InnoDB"; +*/ +Execute($query10); + +//Insert all the retrieved old values to the new vtiger_groups table ie., create new vtiger_groups +foreach($group_map_array as $groupname => $description) +{ + $empty_array = array( + "groups" => array(""=>""), + "roles" => array(""=>""), + "rs" => array(""=>""), + "users" => array(""=>"") + ); + $groupid = createGroup($groupname,$empty_array,$description); + $group_name_id_mapping[$groupname] = $groupid; +} +$conn->println("List of Groups Created (groupname => groupid) ==> ");$conn->println($group_name_id_mapping); + + +//Copy all mappings in a user2grop table in a array; + +//Step 4 : Drop and again create users2group +$query6 = "drop table vtiger_users2group"; +Execute($query6); + +//Added on 06-06-06 +$query7 = "CREATE TABLE vtiger_users2group ( + `groupid` int(19) NOT NULL, + `userid` int(19) NOT NULL, + PRIMARY KEY (`groupid`,`userid`), + KEY `users2group_groupname_uerid_idx` (`groupid`,`userid`) + ) ENGINE=InnoDB"; +/* +$query7 = "CREATE TABLE vtiger_users2group +( + `groupid` int(19) NOT NULL default '0', + `userid` int(19) NOT NULL default '0', + PRIMARY KEY (`groupid`,`userid`), + CONSTRAINT `fk_users2group1` FOREIGN KEY (`groupid`) REFERENCES `groups` (`groupid`) ON DELETE CASCADE +) TYPE=InnoDB"; +*/ +Execute($query7); + +//Step 5 : put entries to vtiger_users2group table based on vtiger_users2group_map_array. Here get the groupid from vtiger_groups table based on groupname +foreach($users2group_map_array as $userid => $groupname) +{ + //$groupid = $conn->query_result($conn->query("select * from vtiger_groups where groupname='".$groupname."'"),0,'groupid'); + $sql = "insert into vtiger_users2group (groupid,userid) values(".$group_name_id_mapping[$groupname].",".$userid.")"; + Execute($sql); +} + + +$alter_query_array5 = Array( + "alter table vtiger_leadgrouprelation ADD CONSTRAINT fk_leadgrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE", + "ALTER TABLE vtiger_activitygrouprelation ADD CONSTRAINT fk_activitygrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE", + "ALTER TABLE vtiger_ticketgrouprelation ADD CONSTRAINT fk_ticketgrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array5 as $query) +{ + Execute($query); +} +//Moved the create table queries for vtiger_group2grouprel, vtiger_group2role, vtiger_group2rs to before creatinf the Group ie., before call the createGroup + + +/***Added to include decimal places for amount vtiger_field in vtiger_potential table --by Mangai 15-Nov-2005***/ + +$query11 = "ALTER TABLE vtiger_potential change amount amount decimal(10,2)"; +Execute($query11); + +/****************** 5.0(Alpha) dev version 2 Database changes -- Ends*********************/ + + + + + + + + + + + + +/****************** 5.0(Alpha) dev version 3 Database changes -- Starts*********************/ + +//Drop the column company_name from vtiger_vendor table ---- modified by Mickie on 18-11-2005 +$altersql1 = "alter table vtiger_vendor drop column company_name"; +Execute($altersql1); +$altersql2 = "alter table vtiger_vendor change column name vendorname varchar(100) default NULL"; +$conn->query($altersql2); +Execute("update vtiger_field set fieldname='vendorname', columnname='vendorname' where tabid=18 and fieldname='name'"); +//TODO (check): Remove this company_name entry from the vtiger_field table if it already exists + +//Migration for Default Organisation Share -- Added by Don on 20-11-2005 + +$query1 = "CREATE TABLE vtiger_org_share_action_mapping ( +`share_action_id` int(19) NOT NULL default '0', + `share_action_name` varchar(200) NOT NULL default '', +PRIMARY KEY (`share_action_id`,`share_action_name`) + ) TYPE=InnoDB "; +Execute($query1); + +$query2 = "CREATE TABLE vtiger_org_share_action2tab ( + `share_action_id` int(19) NOT NULL default '0', + `tabid` int(19) NOT NULL default '0', + PRIMARY KEY (`share_action_id`,`tabid`), + CONSTRAINT `fk_org_share_action2tab` FOREIGN KEY (`share_action_id`) REFERENCES `vtiger_org_share_action_mapping` (`share_action_id`) ON DELETE CASCADE + ) TYPE=InnoDB"; +Execute($query2); + + +$query3 = "alter table vtiger_def_org_share add column editstatus int(19)"; +Execute($query3); + +$query4 = "delete from vtiger_def_org_share where tabid in(8,14,15,18,19)"; +Execute($query4); + + + +//Inserting values into org share action mapping +$insert_query_array1 = Array( + "insert into vtiger_org_share_action_mapping values(0,'Public: Read Only')", + "insert into vtiger_org_share_action_mapping values(1,'Public:Read,Create/Edit')", + "insert into vtiger_org_share_action_mapping values(2,'Public: Read, Create/Edit, Delete')", + "insert into vtiger_org_share_action_mapping values(3,'Private')", + "insert into vtiger_org_share_action_mapping values(4,'Hide Details')", + "insert into vtiger_org_share_action_mapping values(5,'Hide Details and Add Events')", + "insert into vtiger_org_share_action_mapping values(6,'Show Details')", + "insert into vtiger_org_share_action_mapping values(7,'Show Details and Add Events')" + ); +foreach($insert_query_array1 as $query) +{ + Execute($query); +} + + +//Inserting for all vtiger_tabs +$def_org_tabid=Array(2,4,6,7,9,10,13,16,20,21,22,23,26); +foreach($def_org_tabid as $def_tabid) +{ + $insert_query_array2 = Array( + "insert into vtiger_org_share_action2tab values(0,".$def_tabid.")", + "insert into vtiger_org_share_action2tab values(1,".$def_tabid.")", + "insert into vtiger_org_share_action2tab values(2,".$def_tabid.")", + "insert into vtiger_org_share_action2tab values(3,".$def_tabid.")" + ); + foreach($insert_query_array2 as $query) + { + Execute($query); + } +} + +$insert_query_array3 = Array( + "insert into vtiger_org_share_action2tab values(4,17)", + "insert into vtiger_org_share_action2tab values(5,17)", + "insert into vtiger_org_share_action2tab values(6,17)", + "insert into vtiger_org_share_action2tab values(7,17)" + ); +foreach($insert_query_array3 as $query) +{ + Execute($query); +} + +$query_array1 = Array( + "insert into vtiger_def_org_share values(9,17,7,0)", + "update vtiger_def_org_share set editstatus=0", + "update vtiger_def_org_share set editstatus=2 where tabid=4", + "update vtiger_def_org_share set editstatus=1 where tabid=9", + "update vtiger_def_org_share set editstatus=2 where tabid=16" + ); +foreach($query_array1 as $query) +{ + Execute($query); +} + +/****************** 5.0(Alpha) dev version 3 Database changes -- Ends*********************/ + + + +$migrationlog->debug("Database Modifications for 5.0(Alpha) Dev 3 ==> 5.0 Alpha starts here."); +//echo "

    Database Modifications for 5.0(Alpha) Dev3 ==> 5.0 Alpha starts here.....
    "; +$alter_query_array6 = Array( + "ALTER TABLE vtiger_users ADD column activity_view VARCHAR(25) DEFAULT 'Today' AFTER homeorder", + "ALTER TABLE vtiger_activity ADD column notime VARCHAR(3) NOT NULL DEFAULT '0' AFTER location" + ); +foreach($alter_query_array6 as $query) +{ + Execute($query); +} + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (9,".$newfieldid.",'notime','activity',1,56,'notime','No Time',1,0,0,100,20,1,3,'C~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('9',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (16,".$newfieldid.",'notime','activity',1,56,'notime','No Time',1,0,0,100,18,1,1,'C~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('16',$newfieldid); + +$alter_query_array7 = Array( + "alter table vtiger_vendor add column pobox varchar(30) after state", + "alter table vtiger_leadaddress add column pobox varchar(30) after state", + "alter table vtiger_accountbillads add column pobox varchar(30) after state", + "alter table vtiger_accountshipads add column pobox varchar(30) after state", + "alter table vtiger_contactaddress add column mailingpobox varchar(30) after mailingstate", + "alter table vtiger_contactaddress add column otherpobox varchar(30) after otherstate", + "alter table vtiger_quotesbillads add column bill_pobox varchar(30) after bill_street", + "alter table vtiger_quotesshipads add column ship_pobox varchar(30) after ship_street", + "alter table vtiger_pobillads add column bill_pobox varchar(30) after bill_street", + "alter table vtiger_poshipads add column ship_pobox varchar(30) after ship_street", + "alter table vtiger_sobillads add column bill_pobox varchar(30) after bill_street", + "alter table vtiger_soshipads add column ship_pobox varchar(30) after ship_street", + "alter table vtiger_invoicebillads add column bill_pobox varchar(30) after bill_street", + "alter table vtiger_invoiceshipads add column ship_pobox varchar(30) after ship_street" + ); +foreach($alter_query_array7 as $query) +{ + Execute($query); +} + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (23,".$newfieldid.",'bill_pobox','invoicebillads',1,'1','bill_pobox','Billing Po Box',1,0,0,100,3,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('23',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (23,".$newfieldid.",'ship_pobox','invoiceshipads',1,'1','ship_pobox','Shipping Po Box',1,0,0,100,4,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('23',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (6,".$newfieldid.",'pobox','accountbillads',1,'1','bill_pobox','Billing Po Box',1,0,0,100,3,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('6',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (6,".$newfieldid.",'pobox','accountshipads',1,'1','ship_pobox','Shipping Po Box',1,0,0,100,4,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('6',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (7,".$newfieldid.",'pobox','leadaddress',1,'1','pobox','Po Box',1,0,0,100,2,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('7',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (4,".$newfieldid.",'mailingpobox','contactaddress',1,'1','mailingpobox','Mailing Po Box',1,0,0,100,3,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('4',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (4,".$newfieldid.",'otherpobox','contactaddress',1,'1','otherpobox','Other Po Box',1,0,0,100,4,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('4',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (18,".$newfieldid.",'pobox','vendor',1,'1','pobox','Po Box',1,0,0,100,2,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('18',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (20,".$newfieldid.",'bill_pobox','quotesbillads',1,'1','bill_pobox','Billing Po Box',1,0,0,100,3,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('20',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (20,".$newfieldid.",'ship_pobox','quotesshipads',1,'1','ship_pobox','Shipping Po Box',1,0,0,100,4,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('20',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (21,".$newfieldid.",'bill_pobox','pobillads',1,'1','bill_pobox','Billing Po Box',1,0,0,100,3,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('21',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (21,".$newfieldid.",'ship_pobox','poshipads',1,'1','ship_pobox','Shipping Po Box',1,0,0,100,4,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('21',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (22,".$newfieldid.",'bill_pobox','sobillads',1,'1','bill_pobox','Billing Po Box',1,0,0,100,3,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('22',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (22,".$newfieldid.",'ship_pobox','soshipads',1,'1','ship_pobox','Shipping Po Box',1,0,0,100,4,2,1,'V~O',1,'')"; +Execute($insert_query); +populateFieldForSecurity('22',$newfieldid); + + +$fieldname =array('bill_city','bill_state','bill_code','bill_country','ship_city','ship_state','ship_code','ship_country'); +$tablename = array('accountbillads','quotesbillads','pobillads','sobillads','invoicebillads','accountshipads','quotesshipads','poshipads','soshipads','invoiceshipads'); +$sequence = array(5,7,9,11,6,8,10,12); +$k = 0; +$n = 0; +for($j = 0;$j < 8;$j++) +{ + if($j == 4) + $n = $n+5; + for($i = 0;$i < 5;$i++) + { + $query1 = "update vtiger_field set sequence=".$sequence[$j]." where tablename='".$tablename[$n+$i]."' && fieldname='".$fieldname[$j]."'"; + Execute($query1); + } +} + +$fieldname = array('code','city','country','state'); +$tablename = 'leadaddress'; +$sequence = array(3,4,5,6); +for($i = 0;$i < 4;$i++) +{ + $query2 = "update vtiger_field set sequence=".$sequence[$i]." where tablename='".$tablename."' && fieldname='".$fieldname[$i]."'"; + Execute($query2); +} + +$fieldname = array('city','state','postalcode','country'); +$tablename = 'vendor'; +$sequence = array(3,4,5,6); + +for($i = 0;$i < 4;$i++) +{ + $query3 = "update vtiger_field set sequence=".$sequence[$i]." where tablename='".$tablename."' && fieldname='".$fieldname[$i]."'"; + Execute($query3); +} + +$fieldname = array('mailingcity','othercity','mailingstate','otherstate','mailingzip','otherzip','mailingcountry','othercountry'); +$tablename = 'contactaddress'; +$sequence = array(5,6,7,8,9,10,11,12); + +for($i = 0;$i < 8;$i++) +{ + $query = "update vtiger_field set sequence=".$sequence[$i]." where tablename='".$tablename."' && fieldname='".$fieldname[$i]."'"; + Execute($query); +} + +$query_array1 = Array( + "update vtiger_field set tablename='vtiger_crmentity' where tabid=10 and fieldname='description'", + "update vtiger_field set tablename='vtiger_attachments' where tabid=10 and fieldname='filename'", + "drop table vtiger_emails", + + "alter table vtiger_activity drop column description", + "update vtiger_field set tablename='vtiger_crmentity' where tabid in (9,16) and fieldname='description'", + + "update vtiger_tab set name='PurchaseOrder',tablabel='PurchaseOrder' where tabid=21", + "update vtiger_tab set presence=0 where tabid=22 and name='SalesOrder'", + + "delete from vtiger_actionmapping where actionname='SalesOrderDetailView'", + "delete from vtiger_actionmapping where actionname='SalesOrderEditView'", + "delete from vtiger_actionmapping where actionname='SaveSalesOrder'", + "delete from vtiger_actionmapping where actionname='DeleteSalesOrder'", + + //"insert into vtiger_field values (13,".$conn->getUniqueID("vtiger_field").",'filename','vtiger_attachments',1,'61','filename','Attachment',1,0,0,100,12,2,1,'V~O',0,1)", + + "alter table vtiger_troubletickets add column filename varchar(50) default NULL after title" + ); +foreach($query_array1 as $query) +{ + Execute($query); +} + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (13,".$newfieldid.",'filename','vtiger_attachments',1,'61','filename','Attachment',1,0,0,100,12,2,1,'V~O',0,1)"; +Execute($insert_query); +populateFieldForSecurity('13',$newfieldid); + + +$create_query3 = "create table vtiger_parenttab(parenttabid int(19) not null, parenttab_label varchar(100) not null, sequence int(10) not null, visible int(2) not null default '0', Primary Key(parenttabid))"; +Execute($create_query3); +$create_query4 = "create table vtiger_parenttabrel(parenttabid int(3) not null, tabid int(3) not null,sequence int(3) not null)"; +Execute($create_query4); + +$insert_query_array4 = Array( + "insert into vtiger_parenttab values(1,'My Home Page',1,0),(2,'Marketing',2,0),(3,'Sales',3,0),(4,'Support',4,0),(5,'Analytics',5,0),(6,'Inventory',6,0), (7,'Tools',7,0),(8,'Settings',8,0)", + "insert into vtiger_parenttabrel values(1,9,2),(1,17,3),(1,10,4),(1,3,1),(3,7,1),(3,6,2),(3,4,3),(3,2,4),(3,20,5),(3,22,6),(3,23,7),(3,14,8),(3,19,9),(3,8,10),(4,13,1),(4,15,2),(4,6,3),(4,4,4),(4,14,5),(4,8,6),(5,1,1),(5,25,2),(6,14,1), (6,18,2), (6,19,3), (6,21,4), (6,22,5), (6,20,6), (6,23,7), (7,24,1), (7,27,2), (7,8,3), (2,6,2), (2,4,3) " + ); +foreach($insert_query_array4 as $query) +{ + Execute($query); +} + + +$create_query5 = "CREATE TABLE vtiger_blocks ( blockid int(19) NOT NULL, tabid int(19) NOT NULL, blocklabel varchar(100) NOT NULL, sequence int(19) NOT NULL, show_title int(2) NOT NULL, visible int(2) NOT NULL DEFAULT 0, create_view int(2) NOT NULL DEFAULT 0, edit_view int(2) NOT NULL DEFAULT 0, detail_view int(2) NOT NULL DEFAULT 0, PRIMARY KEY (blockid))"; +Execute($create_query5); + +$update_query_array1 = Array( + "update vtiger_field set block=2 where tabid=2 and block=5", + "update vtiger_field set block=3 where tabid=2 and block=2", + + //"update vtiger_field set block=4 where tabid=4 and block=1", + "update vtiger_field set block=5 where tabid=4 and block=5", + "update vtiger_field set block=6 where tabid=4 and block=4",//Modified on 24-04-06 + "update vtiger_field set block=4 where tabid=4 and block=1", + "update vtiger_field set block=7 where tabid=4 and block=2", + "update vtiger_field set block=8 where tabid=4 and block=3", + + "update vtiger_field set block=9 where tabid=6 and block=1", + "update vtiger_field set block=10 where tabid=6 and block=5", + "update vtiger_field set block=11 where tabid=6 and block=2", + "update vtiger_field set block=12 where tabid=6 and block=3", + + "update vtiger_field set block=13 where tabid=7 and block=1", + "update vtiger_field set block=14 where tabid=7 and block=5", + "update vtiger_field set block=15 where tabid=7 and block=2", + "update vtiger_field set block=16 where tabid=7 and block=3", + + "update vtiger_field set block=17 where tabid=8 and block=1", + "update vtiger_field set block=17 where tabid=8 and block=2", + "update vtiger_field set block=18 where tabid=8 and block=3", + + "update vtiger_field set block=19 where tabid=9 and block=1", + "update vtiger_field set block=19 where tabid=9 and block=7", + "update vtiger_field set block=20 where tabid=9 and block=2", + + "update vtiger_field set block=21 where tabid=10 and block=1", + "update vtiger_field set block=22 where tabid=10 and block=2", + "update vtiger_field set block=23 where tabid=10 and block=3", + "update vtiger_field set block=23 where tabid=10 and block=4", + "update vtiger_field set block=24 where tabid=10 and block=5", + + "update vtiger_field set block=25 where tabid=13 and block=1", + "update vtiger_field set block=26 where tabid=13 and block=2", + "update vtiger_field set block=27 where tabid=13 and block=5", + "update vtiger_field set block=28 where tabid=13 and block=3", + "update vtiger_field set block=29 where tabid=13 and block=4", + "update vtiger_field set block=30 where tabid=13 and block=6", + + "update vtiger_field set block=31 where tabid=14 and block=1", + "update vtiger_field set block=32 where tabid=14 and block=2", + "update vtiger_field set block=33 where tabid=14 and block=3", + "update vtiger_field set block=34 where tabid=14 and block=5", + "update vtiger_field set block=35 where tabid=14 and block=6", + "update vtiger_field set block=36 where tabid=14 and block=4", + + "update vtiger_field set block=37 where tabid=15 and block=1", + "update vtiger_field set block=38 where tabid=15 and block=2", + "update vtiger_field set block=39 where tabid=15 and block=3", + "update vtiger_field set block=40 where tabid=15 and block=4", + + "update vtiger_field set block=41 where tabid=16 and block=1", + "update vtiger_field set block=42 where tabid=16 and block=7", + "update vtiger_field set block=43 where tabid=16 and block=2", + + "update vtiger_field set block=44 where tabid=18 and block=1", + "update vtiger_field set block=45 where tabid=18 and block=5", + "update vtiger_field set block=36 where tabid=18 and block=2", + "update vtiger_field set block=47 where tabid=18 and block=3", + + "update vtiger_field set block=48 where tabid=19 and block=1", + "update vtiger_field set block=49 where tabid=19 and block=5", + "update vtiger_field set block=50 where tabid=19 and block=2", + + "update vtiger_field set block=51 where tabid=20 and block=1", + "update vtiger_field set block=52 where tabid=20 and block=5", + "update vtiger_field set block=53 where tabid=20 and block=2", + "update vtiger_field set block=55 where tabid=20 and block=6", + "update vtiger_field set block=56 where tabid=20 and block=3", + + "update vtiger_field set block=57 where tabid=21 and block=1", + "update vtiger_field set block=58 where tabid=21 and block=5", + "update vtiger_field set block=59 where tabid=21 and block=2", + "update vtiger_field set block=61 where tabid=21 and block=6", + "update vtiger_field set block=62 where tabid=21 and block=3", + + "update vtiger_field set block=63 where tabid=22 and block=1", + "update vtiger_field set block=64 where tabid=22 and block=5", + "update vtiger_field set block=65 where tabid=22 and block=2", + "update vtiger_field set block=67 where tabid=22 and block=6", + "update vtiger_field set block=68 where tabid=22 and block=3", + + + "update vtiger_field set block=69 where tabid=23 and block=1", + "update vtiger_field set block=70 where tabid=23 and block=5", + "update vtiger_field set block=71 where tabid=23 and block=2", + "update vtiger_field set block=73 where tabid=23 and block=6", + "update vtiger_field set block=74 where tabid=23 and block=3", + ); +foreach($update_query_array1 as $query) +{ + Execute($query); +} + +$insert_query_array5 = Array( + "insert into vtiger_blocks values (1,2,'LBL_OPPORTUNITY_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (2,2,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (3,2,'LBL_DESCRIPTION_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (4,4,'LBL_CONTACT_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (5,4,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (6,4,'LBL_CUSTOMER_PORTAL_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (7,4,'LBL_ADDRESS_INFORMATION',4,0,0,0,0,0)", + "insert into vtiger_blocks values (8,4,'LBL_DESCRIPTION_INFORMATION',5,0,0,0,0,0)", + "insert into vtiger_blocks values (9,6,'LBL_ACCOUNT_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (10,6,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (11,6,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (12,6,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0)", + "insert into vtiger_blocks values (13,7,'LBL_LEAD_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (14,7,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (15,7,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (16,7,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0)", + "insert into vtiger_blocks values (17,8,'LBL_NOTE_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (18,8,'',2,1,0,0,0,0)", + "insert into vtiger_blocks values (19,9,'LBL_TASK_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (20,9,'',2,1,0,0,0,0)", + "insert into vtiger_blocks values (21,10,'LBL_EMAIL_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (22,10,'',2,1,0,0,0,0)", + "insert into vtiger_blocks values (23,10,'',3,1,0,0,0,0)", + "insert into vtiger_blocks values (24,10,'',4,1,0,0,0,0)", + "insert into vtiger_blocks values (25,13,'LBL_TICKET_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (26,13,'',2,1,0,0,0,0)", + "insert into vtiger_blocks values (27,13,'LBL_CUSTOM_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (28,13,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0)", + "insert into vtiger_blocks values (29,13,'LBL_TICKET_RESOLUTION',5,0,0,1,0,0)", + "insert into vtiger_blocks values (30,13,'LBL_COMMENTS',6,0,0,1,0,0)", + "insert into vtiger_blocks values (31,14,'LBL_PRODUCT_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (32,14,'LBL_PRICING_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (33,14,'LBL_STOCK_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (34,14,'LBL_CUSTOM_INFORMATION',4,0,0,0,0,0)", + "insert into vtiger_blocks values (35,14,'LBL_IMAGE_INFORMATION',5,0,0,0,0,0)", + "insert into vtiger_blocks values (36,14,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0)", + "insert into vtiger_blocks values (37,15,'LBL_FAQ_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (38,15,'',2,1,0,0,0,0)", + "insert into vtiger_blocks values (39,15,'',3,1,0,0,0,0)", + "insert into vtiger_blocks values (40,15,'LBL_COMMENT_INFORMATION',4,0,0,1,0,0)", + "insert into vtiger_blocks values (41,16,'LBL_EVENT_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (42,16,'',2,1,0,0,0,0)", + "insert into vtiger_blocks values (43,16,'',3,1,0,0,0,0)", + "insert into vtiger_blocks values (44,18,'LBL_VENDOR_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (45,18,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (46,18,'LBL_VENDOR_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (47,18,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0)", + "insert into vtiger_blocks values (48,19,'LBL_PRICEBOOK_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (49,19,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (50,19,'LBL_DESCRIPTION_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (51,20,'LBL_QUOTE_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (52,20,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (53,20,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (54,20,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0)", + "insert into vtiger_blocks values (55,20,'LBL_TERMS_INFORMATION',5,0,0,0,0,0)", + "insert into vtiger_blocks values (56,20,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0)", + "insert into vtiger_blocks values (57,21,'LBL_PO_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (58,21,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (59,21,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (60,21,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0)", + "insert into vtiger_blocks values (61,21,'LBL_TERMS_INFORMATION',5,0,0,0,0,0)", + "insert into vtiger_blocks values (62,21,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0)", + "insert into vtiger_blocks values (63,22,'LBL_SO_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (64,22,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (65,22,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (66,22,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0)", + "insert into vtiger_blocks values (67,22,'LBL_TERMS_INFORMATION',5,0,0,0,0,0)", + "insert into vtiger_blocks values (68,22,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0)", + "insert into vtiger_blocks values (69,23,'LBL_INVOICE_INFORMATION',1,0,0,0,0,0)", + "insert into vtiger_blocks values (70,23,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)", + "insert into vtiger_blocks values (71,23,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + "insert into vtiger_blocks values (72,23,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0)", + "insert into vtiger_blocks values (73,23,'LBL_TERMS_INFORMATION',5,0,0,0,0,0)", + "insert into vtiger_blocks values (74,23,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0)" + ); +foreach($insert_query_array5 as $query) +{ + Execute($query); +} + +$update_query_array2 = Array( + "update vtiger_tab set name='Vendors', tablabel='Vendors' where tabid=18", + "update vtiger_tab set name='PriceBooks', tablabel='PriceBooks' where tabid=19", + "update vtiger_tab set presence=0 where tabid in(18,19)", + "update vtiger_relatedlists set label='PriceBooks' where tabid=14 and related_tabid=19" + ); +foreach($update_query_array2 as $query) +{ + Execute($query); +} + +$delete_query1 = "delete from vtiger_actionmapping where actionname in ('SavePriceBook','SaveVendor','PriceBookEditView','VendorEditView','DeletePriceBook','DeleteVendor','PriceBookDetailView','VendorDetailView')"; +Execute($delete_query1); + +$insert_query_array6 = Array( + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Leads')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Accounts')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Contacts')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Potentials')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'HelpDesk')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Quotes')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Activities')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Emails')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Invoice')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Notes')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'PriceBooks')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Products')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'PurchaseOrder')", + + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'SalesOrder')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Vendors')", + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$conn->getUniqueID('vtiger_customview').",'All',1,0,'Faq')" + ); +foreach($insert_query_array6 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Leads'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array7 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_leaddetails:lastname:lastname:Leads_Last_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_leaddetails:firstname:firstname:Leads_First_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_leaddetails:company:company:Leads_Company:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_leadaddress:phone:phone:Leads_Phone:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_leadsubdetails:website:website:Leads_Website:V')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_leaddetails:email:email:Leads_Email:V')", + "insert into vtiger_cvcolumnlist values ($cvid,6,'vtiger_crmentity:smownerid:assigned_user_id:Leads_Assigned_To:V')" + ); +foreach($insert_query_array7 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Accounts'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array8 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_account:accountname:accountname:Accounts_Account_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_accountbillads:city:bill_city:Accounts_City:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_account:website:website:Accounts_Website:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_account:phone:phone:Accounts_Phone:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_crmentity:smownerid:assigned_user_id:Accounts_Assigned_To:V')" + ); +foreach($insert_query_array8 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Contacts'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array9 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_contactdetails:firstname:firstname:Contacts_First_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_contactdetails:lastname:lastname:Contacts_Last_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_contactdetails:title:title:Contacts_Title:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_account:accountname:accountname:Contacts_Account_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_contactdetails:email:email:Contacts_Email:V')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_contactdetails:phone:phone:Contacts_Office_Phone:V')", + "insert into vtiger_cvcolumnlist values ($cvid,6,'vtiger_crmentity:smownerid:assigned_user_id:Contacts_Assigned_To:V')" + ); +foreach($insert_query_array9 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Potentials'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array10 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_potential:potentialname:potentialname:Potentials_Potential_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_account:accountname:accountname:Potentials_Account_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_potential:amount:amount:Potentials_Amount:N')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_potential:closingdate:closingdate:Potentials_Expected_Close_Date:D')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_crmentity:smownerid:assigned_user_id:Potentials_Assigned_To:V')" + ); +foreach($insert_query_array10 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='HelpDesk'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array11 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_crmentity:crmid::HelpDesk_Ticket_ID:I')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_troubletickets:title:ticket_title:HelpDesk_Title:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_to:I')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_troubletickets:status:ticketstatus:HelpDesk_Status:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_troubletickets:priority:ticketpriorities:HelpDesk_Priority:V')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_crmentity:smownerid:assigned_user_id:HelpDesk_Assigned_To:V')" + ); +foreach($insert_query_array11 as $query) +{ + Execute($query); +} + + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Quotes'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array12 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_crmentity:crmid::Quotes_Quote_ID:I')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_quotes:subject:subject:Quotes_Subject:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_quotes:quotestage:quotestage:Quotes_Quote_Stage:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_quotes:potentialid:potential_id:Quotes_Potential_Name:I')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_account:accountname:accountname:Quotes_Account_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_quotes:total:hdnGrandTotal:Quotes_Total:I')", + "insert into vtiger_cvcolumnlist values ($cvid,6,'vtiger_crmentity:smownerid:assigned_user_id:Quotes_Assigned_To:V')" + ); +foreach($insert_query_array12 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Activities'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array13 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_activity:status:taskstatus:Activities_Status:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_activity:activitytype:activitytype:Activities_Type:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_activity:subject:subject:Activities_Subject:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_contactdetails:lastname:lastname:Activities_Contact_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_seactivityrel:crmid:parent_id:Activities_Related_To:V')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_activity:date_start:date_start:Activities_Start_Date:D')", + "insert into vtiger_cvcolumnlist values ($cvid,6,'vtiger_activity:due_date:due_date:Activities_End_Date:D')", + "insert into vtiger_cvcolumnlist values ($cvid,7,'vtiger_crmentity:smownerid:assigned_user_id:Activities_Assigned_To:V')" + ); +foreach($insert_query_array13 as $query) +{ + Execute($query); +} + + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Emails'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array14 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_activity:subject:subject:Emails_Subject:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_seactivityrel:crmid:parent_id:Emails_Related_To:I')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_activity:date_start:date_start:Emails_Date_Sent:D')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_crmentity:smownerid:assigned_user_id:Emails_Assigned_To:V')" + ); +foreach($insert_query_array14 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Invoice'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array15 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_crmentity:crmid::Invoice_Invoice_Id:I')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_invoice:subject:subject:Invoice_Subject:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_invoice:invoicestatus:invoicestatus:Invoice_Status:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_invoice:total:hdnGrandTotal:Invoice_Total:I')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_crmentity:smownerid:assigned_user_id:Invoice_Assigned_To:V')" + ); +foreach($insert_query_array15 as $query) +{ + Execute($query); +} + + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Notes'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array16 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_notes:title:title:Notes_Title:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_notes:contact_id:contact_id:Notes_Contact_Name:I')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_senotesrel:crmid:parent_id:Notes_Related_to:I')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_notes:filename:filename:Notes_File:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_crmentity:modifiedtime:modifiedtime:Notes_Modified_Time:V')" + ); +foreach($insert_query_array16 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='PriceBooks'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array17 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_pricebook:bookname:bookname:PriceBooks_Price_Book_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_pricebook:active:active:PriceBooks_Active:V')" + ); +foreach($insert_query_array17 as $query) +{ + Execute($query); +} + + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Products'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array18 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_products:productname:productname:Products_Product_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_products:productcode:productcode:Products_Product_Code:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_products:commissionrate:commissionrate:Products_Commission_Rate:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_products:qty_per_unit:qty_per_unit:Products_Qty/Unit:V')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_products:unit_price:unit_price:Products_Unit_Price:V')" + ); +foreach($insert_query_array18 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='PurchaseOrder'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array19 = Array( + "insert into vtiger_cvcolumnlist values($cvid,0,'vtiger_crmentity:crmid::PurchaseOrder_Order_Id:I')", + "insert into vtiger_cvcolumnlist values($cvid,1,'vtiger_purchaseorder:subject:subject:PurchaseOrder_Subject:V')", + "insert into vtiger_cvcolumnlist values($cvid,2,'vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:I')", + "insert into vtiger_cvcolumnlist values($cvid,3,'vtiger_purchaseorder:tracking_no:tracking_no:PurchaseOrder_Tracking_Number:V')", + "insert into vtiger_cvcolumnlist values($cvid,4,'vtiger_crmentity:smownerid:assigned_user_id:PurchaseOrder_Assigned_To:V')" + ); +foreach($insert_query_array19 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='SalesOrder'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array20 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_crmentity:crmid::SalesOrder_Order_Id:I')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_salesorder:subject:subject:SalesOrder_Subject:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_account:accountname:accountname:SalesOrder_Account_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_quotes:quoteid:quote_id:SalesOrder_Quote_Name:I')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_salesorder:total:hdnGrandTotal:SalesOrder_Total:V')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_crmentity:smownerid:assigned_user_id:SalesOrder_Assigned_To:V')" + ); +foreach($insert_query_array20 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Vendors'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array21 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_vendor:vendorname:vendorname:Vendors_Vendor_Name:V')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_vendor:phone:phone:Vendors_Phone:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_vendor:email:email:Vendors_Email:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_vendor:category:category:Vendors_Category:V')" + ); +foreach($insert_query_array21 as $query) +{ + Execute($query); +} + +$res=$conn->query("select cvid from vtiger_customview where viewname='All' and entitytype='Faq'"); +$cvid = $conn->query_result($res,0,"cvid"); + +$insert_query_array22 = Array( + "insert into vtiger_cvcolumnlist values ($cvid,0,'vtiger_faq:id::Faq_FAQ_Id:I')", + "insert into vtiger_cvcolumnlist values ($cvid,1,'vtiger_faq:question:question:Faq_Question:V')", + "insert into vtiger_cvcolumnlist values ($cvid,2,'vtiger_faq:category:faqcategories:Faq_Category:V')", + "insert into vtiger_cvcolumnlist values ($cvid,3,'vtiger_faq:product_id:product_id:Faq_Product_Name:I')", + "insert into vtiger_cvcolumnlist values ($cvid,4,'vtiger_crmentity:createdtime:createdtime:Faq_Created_Time:D')", + "insert into vtiger_cvcolumnlist values ($cvid,5,'vtiger_crmentity:modifiedtime:modifiedtime:Faq_Modified_Time:D')" + ); +foreach($insert_query_array22 as $query) +{ + Execute($query); +} + + +$update_query_array3 = Array( + "update vtiger_field set uitype=53 where tabid=2 and columnname='smownerid'", + "update vtiger_field set uitype=53 where tabid=4 and columnname='smownerid'", + "update vtiger_field set uitype=53 where tabid=20 and columnname='smownerid'", + "update vtiger_field set uitype=53 where tabid=22 and columnname='smownerid'", + "update vtiger_field set uitype=53 where tabid=23 and columnname='smownerid'" + ); +foreach($update_query_array3 as $query) +{ + Execute($query); +} + +//Added on 26-06-06 - we cannot add foreign key in type MyISAM, so we have to change the type to InnoDB +$alter_tables_array = Array("vtiger_groups","vtiger_potential","vtiger_quotes","vtiger_salesorder","vtiger_invoice","vtiger_purchaseorder","vtiger_products","vtiger_account","vtiger_contactdetails","vtiger_vendor","vtiger_users","vtiger_attachments","vtiger_profile"); +foreach($alter_tables_array as $tablename) +{ + Execute("alter table $tablename type=InnoDB"); +} + + +$create_query6 = "CREATE TABLE vtiger_accountgrouprelation ( accountid int(19) NOT NULL, groupname varchar(100) default NULL, PRIMARY KEY (`accountid`)) ENGINE=InnoDB"; +Execute($create_query6); + +$alter_query_array8 = Array( + "alter table vtiger_accountgrouprelation ADD CONSTRAINT fk_1_vtiger_accountgrouprelation FOREIGN KEY (accountid) REFERENCES vtiger_account(accountid) ON DELETE CASCADE", + "alter table vtiger_accountgrouprelation ADD CONSTRAINT fk_2_vtiger_accountgrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE", + "ALTER TABLE `vtiger_accountgrouprelation` ADD KEY accountgrouprelation_groupname_idx (groupname)", + ); +foreach($alter_query_array8 as $query) +{ + Execute($query); +} + +$create_query7 = "CREATE TABLE vtiger_contactgrouprelation ( contactid int(19) NOT NULL default '0', groupname varchar(100) default NULL, PRIMARY KEY (`contactid`))"; +Execute($create_query7); + +$alter_query_array9 = Array( + "alter table vtiger_contactgrouprelation ADD CONSTRAINT fk_contactgrouprelation FOREIGN KEY (contactid) REFERENCES vtiger_contactdetails(contactid) ON DELETE CASCADE", + "alter table vtiger_contactgrouprelation ADD CONSTRAINT fk_contactgrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array9 as $query) +{ + Execute($query); +} + + +$create_query10 = "CREATE TABLE vtiger_potentialgrouprelation ( potentialid int(19) NOT NULL default '0', groupname varchar(100) default NULL, PRIMARY KEY (`potentialid`))"; +Execute($create_query10); + +$alter_query_array10 = Array( + "alter table vtiger_potentialgrouprelation ADD CONSTRAINT fk_potentialgrouprelation FOREIGN KEY (potentialid) REFERENCES vtiger_potential(potentialid) ON DELETE CASCADE", + "alter table vtiger_potentialgrouprelation ADD CONSTRAINT fk_potentialgrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array10 as $query) +{ + Execute($query); +} + +$create_query11 = "CREATE TABLE vtiger_quotegrouprelation ( quoteid int(19) NOT NULL default '0', groupname varchar(100) default NULL, PRIMARY KEY (`quoteid`) )"; +Execute($create_query11); + +$alter_query_array11 = Array( + "alter table vtiger_quotegrouprelation ADD CONSTRAINT fk_quotegrouprelation FOREIGN KEY (quoteid) REFERENCES vtiger_quotes(quoteid) ON DELETE CASCADE", + "alter table vtiger_quotegrouprelation ADD CONSTRAINT fk_quotegrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array11 as $query) +{ + Execute($query); +} + +$create_query12 = "CREATE TABLE vtiger_sogrouprelation ( salesorderid int(19) NOT NULL default '0', groupname varchar(100) default NULL, PRIMARY KEY (`salesorderid`) )"; +Execute($create_query12); + +$alter_query_array12 = Array( + "alter table vtiger_sogrouprelation ADD CONSTRAINT fk_sogrouprelation FOREIGN KEY (salesorderid) REFERENCES vtiger_salesorder(salesorderid) ON DELETE CASCADE", + "alter table vtiger_sogrouprelation ADD CONSTRAINT fk_sogrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array12 as $query) +{ + Execute($query); +} + +$create_query13 = "CREATE TABLE vtiger_invoicegrouprelation ( invoiceid int(19) NOT NULL default '0', groupname varchar(100) default NULL, PRIMARY KEY (`invoiceid`))"; +Execute($create_query13); + +$alter_query_array13 = Array( + "alter table vtiger_invoicegrouprelation ADD CONSTRAINT fk_invoicegrouprelation FOREIGN KEY (invoiceid) REFERENCES vtiger_invoice(invoiceid) ON DELETE CASCADE", + "alter table vtiger_invoicegrouprelation ADD CONSTRAINT fk_invoicegrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array13 as $query) +{ + Execute($query); +} + +$create_query14 = "CREATE TABLE vtiger_pogrouprelation ( purchaseorderid int(19) NOT NULL default '0', groupname varchar(100) default NULL, PRIMARY KEY (`purchaseorderid`))"; +Execute($create_query14); + +$alter_query_array14 = Array( + "alter table vtiger_pogrouprelation ADD CONSTRAINT fk_pogrouprelation FOREIGN KEY (purchaseorderid) REFERENCES vtiger_purchaseorder(purchaseorderid) ON DELETE CASCADE", + "alter table vtiger_pogrouprelation ADD CONSTRAINT fk_productgrouprelation2 FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON DELETE CASCADE" + ); +foreach($alter_query_array14 as $query) +{ + Execute($query); +} + +$alter_query1 = "ALTER TABLE vtiger_users ADD column lead_view VARCHAR(25) DEFAULT 'Today' AFTER homeorder"; +Execute($alter_query1); + +$update_query1 = "update vtiger_users set homeorder = 'ALVT,PLVT,QLTQ,CVLVT,HLT,OLV,GRT,OLTSO,ILTI,MNL'"; +Execute($update_query1); + +$alter_query2 = "ALTER TABLE vtiger_products change column imagename imagename text"; +Execute($alter_query2); + +$alter_query3 = "alter table vtiger_systems modify server varchar(50), modify server_username varchar(50), modify server_password varchar(50), add column smtp_auth char(5)"; +Execute($alter_query3); + +$alter_query_array15 = Array( + "alter table vtiger_users add column imagename varchar(250)", + "alter table vtiger_users add column tagcloud varchar(250)" + ); +foreach($alter_query_array15 as $query) +{ + Execute($query); +} + +$alter_query_array16 = Array( + "alter table vtiger_systems change column server server varchar(80) default NULL", + "alter table vtiger_systems change column server_username server_username varchar(80) default NULL" + ); +foreach($alter_query_array16 as $query) +{ + Execute($query); +} + + +$create_query15 = "create table vtiger_portal(portalid int(19), portalname varchar(255) NOT NULL, portalurl varchar(255) NOT NULL,sequence int(3) NOT NULL, PRIMARY KEY (portalid))"; +Execute($create_query15); + +$alter_query = "ALTER TABLE vtiger_field ADD column info_type varchar(20) default NULL after quickcreatesequence"; +Execute($alter_query); + +//$update_query2 = "UPDATE vtiger_field SET fieldlabel = 'Reference' WHERE tabid = 4 and tablename = 'contactdetails' and fieldname='reference'"; +//changed in 24-04-06 because the reference has not been entered into the vtiger_field table. +$newfieldid = $conn->getUniqueID("vtiger_field"); +$update_query2 = "insert into vtiger_field values (4,".$newfieldid.",'reference','contactdetails',1,'56','reference','Reference',1,0,0,10,23,4,1,'C~O',1,null,'ADV')"; +Execute($update_query2); +populateFieldForSecurity('4',$newfieldid); + +$update_query_array4 = Array( + "UPDATE vtiger_field SET info_type = 'BAS'", + + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 7 and fieldlabel = 'Website'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 7 and fieldlabel = 'Industry'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 7 and fieldlabel = 'Annual Revenue'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 7 and fieldlabel = 'No Of Employees'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 7 and fieldlabel = 'Yahoo Id'", + + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Ticker Symbol'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Other Phone'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Member Of'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Employees'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Other Email'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Ownership'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Rating'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'industry'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'SIC Code'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Type'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Annual Revenue'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 6 and fieldlabel = 'Email Opt Out'", + + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Home Phone'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Department'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Birthdate'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Email'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Reports To'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Assistant'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Yahoo Id'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Assistant Phone'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Do Not Call'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Email Opt Out'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Reference'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Portal User'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Support Start Date'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Support End Date'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 4 and fieldlabel = 'Contact Image'", + + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Usage Unit'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Qty/Unit'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Qty In Stock'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Reorder Level'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Handler'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Qty In Demand'", + "UPDATE vtiger_field SET info_type = 'ADV' WHERE tabid = 14 and fieldlabel = 'Product Image'" + ); +foreach($update_query_array4 as $query) +{ + Execute($query); +} + + +$create_query16 = "CREATE TABLE vtiger_chat_msg ( `id` bigint(20) NOT NULL auto_increment, `chat_from` bigint(20) NOT NULL default '0', `chat_to` bigint(20) NOT NULL default '0', `born` timestamp NULL default '0000-00-00 00:00:00', `msg` varchar(255) NOT NULL, PRIMARY KEY (`id`), KEY `chat_to` (`chat_to`), KEY `chat_from` (`chat_from`), KEY `born` (`born`)) ENGINE=InnoDB"; +Execute($create_query16); +$create_query17 = "CREATE TABLE vtiger_chat_pchat ( `id` bigint(20) NOT NULL auto_increment, `msg` bigint(20) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `msg` (`msg`)) ENGINE=InnoDB"; +Execute($create_query17); + +$create_query18 = "CREATE TABLE vtiger_chat_pvchat ( `id` bigint(20) NOT NULL auto_increment, `msg` bigint(20) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `msg` (`msg`)) ENGINE=InnoDB"; +Execute($create_query18); + +$create_query19 = "CREATE TABLE vtiger_chat_users ( `id` bigint(20) NOT NULL auto_increment, `nick` varchar(50) NOT NULL, `session` varchar(50) NOT NULL, `ip` varchar(20) NOT NULL default '000.000.000.000', `ping` timestamp NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `session` (`session`), UNIQUE KEY `nick` (`nick`), KEY `ping` (`ping`)) ENGINE=InnoDB"; +Execute($create_query19); + +$alter_query_array17 = Array( + "ALTER TABLE `vtiger_chat_msg` ADD CONSTRAINT `chat_msg_ibfk_1` FOREIGN KEY (`chat_from`) REFERENCES `vtiger_chat_users` (`id`) ON DELETE CASCADE", + + "ALTER TABLE `vtiger_chat_pchat` ADD CONSTRAINT `chat_pchat_ibfk_1` FOREIGN KEY (`msg`) REFERENCES `vtiger_chat_msg` (`id`) ON DELETE CASCADE", + + "ALTER TABLE `vtiger_chat_pvchat` ADD CONSTRAINT `chat_pvchat_ibfk_1` FOREIGN KEY (`msg`) REFERENCES `vtiger_chat_msg` (`id`) ON DELETE CASCADE" + ); +foreach($alter_query_array17 as $query) +{ + Execute($query); +} + +$create_query20 = "CREATE TABLE vtiger_freetags ( id int(19) NOT NULL, tag varchar(50) NOT NULL default '', raw_tag varchar(50) NOT NULL default '', PRIMARY KEY (id)) TYPE=InnoDB"; +Execute($create_query20); + +$create_query21 = "CREATE TABLE vtiger_freetagged_objects ( tag_id int(20) NOT NULL default '0', tagger_id int(20) NOT NULL default '0', object_id int(20) NOT NULL default '0', tagged_on timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, module varchar(50) NOT NULL default '', PRIMARY KEY (`tag_id`,`tagger_id`,`object_id`), KEY `freetagged_objects_tag_id_tagger_id_object_id_idx` (`tag_id`,`tagger_id`,`object_id`)) TYPE=InnoDB"; +Execute($create_query21); + +$alter_query4 = "alter table vtiger_profile add column description text"; +Execute($alter_query4); + +$alter_query5 = "alter table vtiger_contactdetails add column imagename varchar(250) after currency"; +Execute($alter_query5); + +$alter_query = "ALTER TABLE vtiger_contactdetails ADD column reference varchar(3) default NULL after imagename"; +Execute($alter_query); + +Execute("insert into vtiger_blocks values(75,4,'LBL_IMAGE_INFORMATION',5,0,0,0,0,0)"); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (4,".$newfieldid.",'imagename','contactdetails',1,'69','imagename','Contact Image',1,0,0,100,1,75,1,'V~O',1,null,'ADV')"; +Execute($insert_query); +populateFieldForSecurity('4',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (9,".$newfieldid.",'visibility','activity',1,15,'visibility','Visibility',1,0,0,100,17,19,3,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('9',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (16,".$newfieldid.",'visibility','activity',1,15,'visibility','Visibility',1,0,0,100,19,41,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('16',$newfieldid); + + +$alter_query6 = "ALTER TABLE vtiger_activity ADD COLUMN visibility varchar(50) NOT NULL DEFAULT 'all' after notime"; +Execute($alter_query6); + +$create_query22 = "CREATE TABLE vtiger_visibility ( `visibilityid` int(19) NOT NULL auto_increment, `visibility` varchar(200) NOT NULL default '', `sortorderid` int(19) NOT NULL default '0', `presence` int(1) NOT NULL default '1', PRIMARY KEY (`visibilityid`), UNIQUE KEY `Visibility_VLY` (`visibility`)) ENGINE=InnoDB"; +Execute($create_query22); + + +$create_query23 = "CREATE TABLE vtiger_sharedcalendar ( `userid` int(19) NOT NULL default '0', `sharedid` int(19) NOT NULL default '0', PRIMARY KEY (`userid`,`sharedid`)) ENGINE=InnoDB"; +Execute($create_query23); + +$insert_query6 = "INSERT INTO vtiger_tab VALUES(26,'Campaigns',0,23,'Campaigns',null,null,1)"; +Execute($insert_query6); +$insert_query7 = "INSERT INTO vtiger_parenttabrel VALUES(2,26,1)"; +Execute($insert_query7); + +$insert_query8 = "insert into vtiger_blocks values(76,26,'LBL_CAMPAIGN_INFORMATION',1,0,0,0,0,0)"; +Execute($insert_query8); +$insert_query8 = "insert into vtiger_blocks values (77,26,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0)"; +Execute($insert_query8); +$insert_query9 = "insert into vtiger_blocks values(78,26,'LBL_DESCRIPTION_INFORMATION',3,0,0,0,0,0)"; +Execute($insert_query9); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'campaignname','campaign',1,'2','campaignname','Campaign Name',1,0,0,100,1,76,1,'V~M',0,1,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'campaigntype','campaign',1,15,'campaigntype','Campaign Type',1,0,0,100,2,76,1,'V~O',0,5,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid,'product_id','campaign',1,59,'product_id','Product',1,0,0,100,3,76,1,'I~O',0,5,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid,'campaignstatus','campaign',1,15,'campaignstatus','Campaign Status',1,0,0,100,4,76,1,'V~O',0,5,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'closingdate','campaign',1,'23','closingdate','Expected Close Date',1,0,0,100,5,76,1,'D~M',0,3,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'expectedrevenue','campaign',1,'1','expectedrevenue','Expected Revenue',1,0,0,100,6,76,1,'I~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'budgetcost','campaign',1,'1','budgetcost','Budget Cost',1,0,0,100,7,76,1,'I~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'actualcost','campaign',1,'1','actualcost','Actual Cost',1,0,0,100,8,76,1,'I~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'expectedresponse','campaign',1,'15','expectedresponse','Expected Response',1,0,0,100,9,76,1,'V~O',0,4,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'smownerid','crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,10,76,1,'V~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'numsent','campaign',1,'9','numsent','Num Sent',1,0,0,100,11,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'sponsor','campaign',1,'1','sponsor','Sponsor',1,0,0,100,12,76,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'targetaudience','campaign',1,'1','targetaudience','Target Audience',1,0,0,100,13,76,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'targetsize','campaign',1,'1','targetsize','TargetSize',1,0,0,100,14,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'expectedresponsecount','campaign',1,'1','expectedresponsecount','Expected Response Count',1,0,0,100,17,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'expectedsalescount','campaign',1,'1','expectedsalescount','Expected Sales Count',1,0,0,100,15,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'expectedroi','campaign',1,'1','expectedroi','Expected ROI',1,0,0,100,19,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'actualresponsecount','campaign',1,'1','actualresponsecount','Actual Response Count',1,0,0,100,18,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'actualsalescount','campaign',1,'1','actualsalescount','Actual Sales Count',1,0,0,100,16,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'actualroi','campaign',1,'1','actualroi','Actual ROI',1,0,0,100,20,76,1,'N~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'createdtime','crmentity',1,'70','createdtime','Created Time',1,0,0,100,15,76,2,'T~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'modifiedtime','crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,16,76,2,'T~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (26, $newfieldid, 'description','crmentity',1,'19','description','Description',1,0,0,100,1,82,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('26',$newfieldid); + +/* +//add all field entries to def_org_field and profile2field tables for Campaigns +$field_res = $conn->query("select fieldid from vtiger_field where tabid=26"); +for($i=0;$i<$conn->num_rows($field_res);$i++) +{ + $fieldid = $conn->query_result($field_res,$i,'fieldid'); + + populateFieldForSecurity('26',$fieldid); +} +*/ + +$insert_query_array25 = Array( + "insert into vtiger_relatedlists values (".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",".getTabid("Contacts").",'get_contacts',1,'Contacts',0)", + "insert into vtiger_relatedlists values (".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",".getTabid("Leads").",'get_leads',2,'Leads',0)" + ); +foreach($insert_query_array25 as $query) +{ + Execute($query); +} + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (7, $newfieldid, 'campaignid','leaddetails',1,'51','campaignid','Campaign Name',1,0,0,100,6,13,3,'I~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('7',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (4, $newfieldid, 'campaignid','contactdetails',1,'51','campaignid','Campaign Name',1,0,0,100,6,4,3,'I~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('4',$newfieldid); + + +$create_query24 = " +CREATE TABLE vtiger_campaign ( + `campaignname` varchar(255) default NULL, + `campaigntype` varchar(255) default NULL, + `campaignstatus` varchar(255) default NULL, + `expectedrevenue` int(19) default NULL, + `budgetcost` int(19) default NULL, + `actualcost` int(19) default NULL, + `expectedresponse` varchar(255) default NULL, + `numsent` decimal(11,0) default NULL, + `product_id` int(19) default NULL, + `sponsor` varchar(255) default NULL, + `targetaudience` varchar(255) default NULL, + `targetsize` int(19) default NULL, + `expectedresponsecount` int(19) default NULL, + `expectedsalescount` int(19) default NULL, + `expectedroi` int(19) default NULL, + `actualresponsecount` int(19) default NULL, + `actualsalescount` int(19) default NULL, + `actualroi` int(19) default NULL, + `campaignid` int(19) NOT NULL, + `closingdate` date default NULL, + PRIMARY KEY (`campaignid`), + KEY `idx_campaignstatus` (`campaignstatus`), + KEY `idx_campaignname` (`campaignname`), + KEY `idx_campaignid` (`campaignid`) +) ENGINE=InnoDB + "; +Execute($create_query24); + + +//Added on 06-06-06 +$create_query25 = "CREATE TABLE vtiger_campaigncontrel ( + `campaignid` int(19) NOT NULL default '0', + `contactid` int(19) NOT NULL default '0', + PRIMARY KEY (`campaignid`), + KEY `campaigncontrel_contractid_idx` (`contactid`) + ) ENGINE=InnoDB"; +/* +$create_query25 = "CREATE TABLE vtiger_campaigncontrel ( + `campaignid` int(19) NOT NULL default '0', + `contactid` int(19) NOT NULL default '0', + PRIMARY KEY (`campaignid`), + KEY `CampaignContRel_IDX1` (`contactid`), + CONSTRAINT `fk_CampaignContRel2` FOREIGN KEY (`contactid`) REFERENCES `vtiger_contactdetails` (`contactid`) ON DELETE CASCADE, + CONSTRAINT `fk_CampaignContRel1` FOREIGN KEY (`campaignid`) REFERENCES `vtiger_campaign` (`campaignid`) ON DELETE CASCADE +) ENGINE=InnoDB"; +*/ +Execute($create_query25); + +//Added on 06-06-06 +$create_table_query = "CREATE TABLE vtiger_campaigngrouprelation ( + `campaignid` int(19) NOT NULL, + `groupname` varchar(100) default NULL, + PRIMARY KEY (`campaignid`), + KEY `campaigngrouprelation_IDX1` (`groupname`) + ) ENGINE=InnoDB"; +/* +$create_table_query = " +CREATE TABLE vtiger_campaigngrouprelation ( + `campaignid` int(19) NOT NULL, + `groupname` varchar(100) default NULL, + PRIMARY KEY (`campaignid`), + KEY `campaigngrouprelation_IDX1` (`groupname`), + CONSTRAINT `fk_campaigngrouprelation2` FOREIGN KEY (`groupname`) REFERENCES `vtiger_groups` (`groupname`) ON DELETE CASCADE, + CONSTRAINT `fk_campaigngrouprelation1` FOREIGN KEY (`campaignid`) REFERENCES `vtiger_campaign` (`campaignid`) ON DELETE CASCADE +) ENGINE=InnoDB"; +*/ +Execute($create_table_query); + + +//Added on 06-06-06 +$create_query26 = "CREATE TABLE vtiger_campaignleadrel ( + `campaignid` int(19) NOT NULL default '0', + `leadid` int(19) NOT NULL default '0', + PRIMARY KEY (`campaignid`), + KEY `campaignleadrel_leadid_campaignid_idx` (`leadid`,`campaignid`) + ) ENGINE=InnoDB"; +/* +$create_query26 = "CREATE TABLE vtiger_campaignleadrel ( + `campaignid` int(19) NOT NULL default '0', + `leadid` int(19) NOT NULL default '0', + PRIMARY KEY (`campaignid`), + KEY `CampaignLeadRel_IDX1` (`leadid`,`campaignid`), + CONSTRAINT `fk_CampaignLeadRel1234` FOREIGN KEY (`campaignid`) REFERENCES `vtiger_campaign` (`campaignid`) ON DELETE CASCADE, + CONSTRAINT `fk_CampaignLeadRel2423` FOREIGN KEY (`leadid`) REFERENCES `vtiger_leaddetails` (`leadid`) ON DELETE CASCADE +) ENGINE=InnoDB"; +*/ +Execute($create_query26); + +$create_table_query1 = "CREATE TABLE vtiger_campaignscf ( + `campaignid` int(19) NOT NULL default '0', + PRIMARY KEY (`campaignid`), + CONSTRAINT `fk_CampaignsCF` FOREIGN KEY (`campaignid`) REFERENCES `vtiger_campaign` (`campaignid`) ON DELETE CASCADE +) ENGINE=InnoDB"; +Execute($create_table_query1); + +$alter_query_array18 = Array( + "alter table vtiger_potential add column campaignid int(19) default NULL after probability", + "alter table vtiger_potential drop column campaignsource", + //"alter table vtiger_notes drop PRIMARY KEY contact_id", + "alter table vtiger_notes drop PRIMARY KEY , add primary key(notesid)", + "update vtiger_field set uitype=99 where fieldname='update_log' and tabid=13" + ); +foreach($alter_query_array18 as $query) +{ + Execute($query); +} + + +//Added on 09-08-2006 +//In the next array we have add constraint for tables purchaseorder, salesorder, quotes and invoice where as the corresponding entity ids should not be 0 they should be NULL. so that this change has been done +Execute("update vtiger_purchaseorder set contactid=NULL where contactid=0"); +Execute("update vtiger_salesorder set contactid=NULL where contactid=0"); +Execute("update vtiger_quotes set contactid=NULL where contactid=0"); +Execute("update vtiger_quotes set potentialid=NULL where potentialid=0"); +Execute("update vtiger_invoice set salesorderid=NULL where salesorderid=0"); + + +//echo "

    Database Modifications for Indexing and some missded tables starts here.....
    "; +//Added queries which are for indexing and the missing tables - Mickie - on 06-04-2006 + +$create_table_query_array = Array( + + +"CREATE TABLE vtiger_actualcost ( + `actualcostid` int(19) NOT NULL auto_increment, + `actualcost` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`actualcostid`), + UNIQUE KEY `CampaignActCst_UK01` (`actualcost`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_campaignstatus ( + `campaignstatusid` int(19) NOT NULL auto_increment, + `campaignstatus` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`campaignstatusid`), + KEY `Campaignstatus_UK01` (`campaignstatus`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_campaigntype ( + `campaigntypeid` int(19) NOT NULL auto_increment, + `campaigntype` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`campaigntypeid`), + UNIQUE KEY `Campaigntype_UK01` (`campaigntype`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_module_rel ( + `shareid` int(19) NOT NULL, + `tabid` int(19) NOT NULL, + `relationtype` varchar(200) default NULL, + PRIMARY KEY (`shareid`), + KEY `idx_datashare_module_rel_tabid` (`tabid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_grp2grp ( + `shareid` int(19) NOT NULL, + `share_groupid` int(19) default NULL, + `to_groupid` int(19) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_grp2grp_share_groupid_idx` (`share_groupid`), + KEY `datashare_grp2grp_to_groupid_idx` (`to_groupid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_grp2role ( + `shareid` int(19) NOT NULL, + `share_groupid` int(19) default NULL, + `to_roleid` varchar(255) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `idx_datashare_grp2role_share_groupid` (`share_groupid`), + KEY `idx_datashare_grp2role_to_roleid` (`to_roleid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_grp2rs ( + `shareid` int(19) NOT NULL, + `share_groupid` int(19) default NULL, + `to_roleandsubid` varchar(255) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_grp2rs_share_groupid_idx` (`share_groupid`), + KEY `datashare_grp2rs_to_roleandsubid_idx` (`to_roleandsubid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_relatedmodule_permission ( + `shareid` int(19) NOT NULL, + `datashare_relatedmodule_id` int(19) NOT NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`,`datashare_relatedmodule_id`), + KEY `datashare_relatedmodule_permission_UK1` (`shareid`,`permission`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_relatedmodules ( + `datashare_relatedmodule_id` int(19) NOT NULL, + `tabid` int(19) default NULL, + `relatedto_tabid` int(19) default NULL, + PRIMARY KEY (`datashare_relatedmodule_id`), + KEY `datashare_relatedmodules_tabid_idx` (`tabid`), + KEY `datashare_relatedmodules_relatedto_tabid_idx` (`relatedto_tabid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_relatedmodules_seq ( + `id` int(11) NOT NULL +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_role2group ( + `shareid` int(19) NOT NULL, + `share_roleid` varchar(255) default NULL, + `to_groupid` int(19) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `idx_datashare_role2group_share_roleid` (`share_roleid`), + KEY `idx_datashare_role2group_to_groupid` (`to_groupid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_role2role ( + `shareid` int(19) NOT NULL, + `share_roleid` varchar(255) default NULL, + `to_roleid` varchar(255) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_role2role_share_roleid_idx` (`share_roleid`), + KEY `datashare_role2role_to_roleid_idx` (`to_roleid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_role2rs ( + `shareid` int(19) NOT NULL, + `share_roleid` varchar(255) default NULL, + `to_roleandsubid` varchar(255) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_role2s_share_roleid_idx` (`share_roleid`), + KEY `datashare_role2s_to_roleandsubid_idx` (`to_roleandsubid`) + ) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_rs2grp ( + `shareid` int(19) NOT NULL, + `share_roleandsubid` varchar(255) default NULL, + `to_groupid` int(19) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_rs2grp_share_roleandsubid_idx` (`share_roleandsubid`), + KEY `datashare_rs2grp_to_groupid_idx` (`to_groupid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_rs2role ( + `shareid` int(19) NOT NULL, + `share_roleandsubid` varchar(255) default NULL, + `to_roleid` varchar(255) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_rs2role_share_roleandsubid_idx` (`share_roleandsubid`), + KEY `datashare_rs2role_to_roleid_idx` (`to_roleid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_datashare_rs2rs ( + `shareid` int(19) NOT NULL, + `share_roleandsubid` varchar(255) default NULL, + `to_roleandsubid` varchar(255) default NULL, + `permission` int(19) default NULL, + PRIMARY KEY (`shareid`), + KEY `datashare_rs2rs_share_roleandsubid_idx` (`share_roleandsubid`), + KEY `idx_datashare_rs2rs_to_roleandsubid_idx` (`to_roleandsubid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_expectedresponse ( + `expectedresponseid` int(19) NOT NULL auto_increment, + `expectedresponse` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`expectedresponseid`), + UNIQUE KEY `CampaignExpRes_UK01` (`expectedresponse`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_expectedrevenue ( + `expectedrevenueid` int(19) NOT NULL auto_increment, + `expectedrevenue` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`expectedrevenueid`), + UNIQUE KEY `CampaignExpRev_UK01` (`expectedrevenue`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_read_group_rel_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `relatedtabid` int(11) NOT NULL, + `sharedgroupid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`relatedtabid`,`sharedgroupid`), + KEY `tmp_read_group_rel_sharing_per_userid_sharedgroupid_tabid` (`userid`,`sharedgroupid`,`tabid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_read_group_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `sharedgroupid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`sharedgroupid`), + KEY `tmp_read_group_sharing_per_userid_sharedgroupid_idx` (`userid`,`sharedgroupid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_read_user_rel_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `relatedtabid` int(11) NOT NULL, + `shareduserid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`relatedtabid`,`shareduserid`), + KEY `tmp_read_user_rel_sharing_per_userid_shared_reltabid_idx` (`userid`,`shareduserid`,`relatedtabid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_read_user_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `shareduserid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`shareduserid`), + KEY `tmp_read_user_sharing_per_userid_shareduserid_idx` (`userid`,`shareduserid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_write_group_rel_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `relatedtabid` int(11) NOT NULL, + `sharedgroupid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`relatedtabid`,`sharedgroupid`), + KEY `tmp_write_group_rel_sharing_per_userid_sharedgroupid_tabid_idx` (`userid`,`sharedgroupid`,`tabid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_write_group_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `sharedgroupid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`sharedgroupid`), + KEY `tmp_write_group_sharing_per_UK1` (`userid`,`sharedgroupid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_write_user_rel_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `relatedtabid` int(11) NOT NULL, + `shareduserid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`relatedtabid`,`shareduserid`), + KEY `tmp_write_user_rel_sharing_per_userid_sharduserid_tabid_idx` (`userid`,`shareduserid`,`tabid`) +) ENGINE=InnoDB", + +"CREATE TABLE vtiger_tmp_write_user_sharing_per ( + `userid` int(11) NOT NULL, + `tabid` int(11) NOT NULL, + `shareduserid` int(11) NOT NULL, + PRIMARY KEY (`userid`,`tabid`,`shareduserid`), + KEY `tmp_write_user_sharing_per_userid_shareduserid_idx` (`userid`,`shareduserid`) +) ENGINE=InnoDB", + + + ); + +foreach($create_table_query_array as $query) +{ + Execute($query); +} + +$query_array = Array( + +//"ALTER TABLE `vtiger_activity` DROP INDEX `status`", +//"ALTER TABLE `vtiger_contactgrouprelation` DROP INDEX `fk_contactgrouprelation2`", +//"ALTER TABLE `vtiger_customview` DROP INDEX `customview`", +//"ALTER TABLE `vtiger_def_org_field` DROP INDEX `tabid`", +//"ALTER TABLE `vtiger_field` DROP INDEX `tabid`", +//"ALTER TABLE `vtiger_groups` DROP INDEX `groupname`", +//"ALTER TABLE `vtiger_invoicegrouprelation` DROP INDEX `fk_invoicegrouprelation2`", +//"ALTER TABLE `vtiger_pogrouprelation` DROP INDEX `fk_productgrouprelation2`", +//"ALTER TABLE `vtiger_potential` DROP INDEX `potentialid`", +//"ALTER TABLE `vtiger_potentialgrouprelation` DROP INDEX `fk_potentialgrouprelation2`", +//"ALTER TABLE `vtiger_profile2field` DROP INDEX `tabid`", +"ALTER TABLE `vtiger_profile2tab` DROP INDEX `idx_profile2tab`", +"ALTER TABLE `vtiger_profile2tab` ADD KEY `profile2tab_profileid_tabid_idx` (`profileid`, `tabid`)", +//"ALTER TABLE `vtiger_quotegrouprelation` DROP INDEX `fk_quotegrouprelation2`", +"ALTER TABLE `vtiger_reportmodules` DROP INDEX `reportmodules_IDX0`", +"ALTER TABLE `vtiger_reportmodules` MODIFY COLUMN `reportmodulesid` INTEGER(19) NOT NULL", + +"ALTER TABLE `vtiger_reportsortcol` DROP INDEX `reportsortcol_IDX0`", +"ALTER TABLE `vtiger_reportsortcol` ADD KEY `fk_1_vtiger_reportsortcol` (`reportid`)", +"ALTER TABLE `vtiger_reportsortcol` MODIFY COLUMN `sortcolid` INTEGER(19) NOT NULL", +"ALTER TABLE `vtiger_reportsortcol` MODIFY COLUMN `reportid` INTEGER(19) NOT NULL", + +"ALTER TABLE `vtiger_reportsummary` DROP INDEX `reportsummary_IDX0`", +"ALTER TABLE `vtiger_reportsummary` ADD KEY `reportsummary_reportsummaryid_idx` (`reportsummaryid`)", +"ALTER TABLE `vtiger_reportsummary` MODIFY COLUMN `reportsummaryid` INTEGER(19) NOT NULL", +"ALTER TABLE `vtiger_reportsummary` MODIFY COLUMN `summarytype` INTEGER(19) NOT NULL", + +//"ALTER TABLE `vtiger_seattachmentsrel` DROP INDEX `attachmentsid`", +//"ALTER TABLE `vtiger_sogrouprelation` DROP INDEX `fk_sogrouprelation2`", +//"ALTER TABLE `vtiger_tab` DROP INDEX `tabid`", +//"ALTER TABLE `vtiger_troubletickets` DROP INDEX `status`", +"ALTER TABLE `vtiger_activity_reminder` TYPE=InnoDB", +"ALTER TABLE `vtiger_activsubtype` TYPE=InnoDB", +"ALTER TABLE `vtiger_contactgrouprelation` TYPE=InnoDB", +//"ALTER TABLE `vtiger_customerdetails` TYPE=InnoDB", +"ALTER TABLE `vtiger_customview_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_def_org_field` TYPE=InnoDB", +"ALTER TABLE `vtiger_def_org_share` TYPE=InnoDB", +"ALTER TABLE `vtiger_def_org_share_seq` TYPE=InnoDB", +//"ALTER TABLE `vtiger_defaultcv` TYPE=InnoDB", +"ALTER TABLE `vtiger_durationhrs` TYPE=InnoDB", +"ALTER TABLE `vtiger_durationmins` TYPE=InnoDB", +"ALTER TABLE `vtiger_emailtemplates` TYPE=InnoDB", +//"ALTER TABLE `vtiger_emailtemplates_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_faqcategories` TYPE=InnoDB", +"ALTER TABLE `vtiger_faqstatus` TYPE=InnoDB", +"ALTER TABLE `vtiger_field_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_files` TYPE=InnoDB", +"ALTER TABLE `vtiger_group2grouprel` TYPE=InnoDB", +"ALTER TABLE `vtiger_group2role` TYPE=InnoDB", +"ALTER TABLE `vtiger_group2rs` TYPE=InnoDB", +//"DROP TABLE `groups_seq`", +"ALTER TABLE `vtiger_headers` TYPE=InnoDB", +"ALTER TABLE `vtiger_import_maps` TYPE=InnoDB", +"ALTER TABLE `vtiger_inventorynotification_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_invoicegrouprelation` TYPE=InnoDB", +"ALTER TABLE `vtiger_loginhistory` TYPE=InnoDB", +"ALTER TABLE `vtiger_mail_accounts` TYPE=InnoDB", +"ALTER TABLE `vtiger_notificationscheduler_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_ownernotify` TYPE=InnoDB", +"ALTER TABLE `vtiger_parenttabrel` TYPE=InnoDB", +"ALTER TABLE `vtiger_pogrouprelation` TYPE=InnoDB", +"ALTER TABLE `vtiger_portal` TYPE=InnoDB", +"ALTER TABLE `vtiger_portalinfo` TYPE=InnoDB", +"ALTER TABLE `vtiger_potentialgrouprelation` TYPE=InnoDB", +"ALTER TABLE `vtiger_profile2field` TYPE=InnoDB", +"ALTER TABLE `vtiger_reportmodules` TYPE=InnoDB", +"ALTER TABLE `vtiger_profile2globalpermissions` TYPE=InnoDB", +"ALTER TABLE `vtiger_profile2standardpermissions` TYPE=InnoDB", +"ALTER TABLE `vtiger_profile2tab` TYPE=InnoDB", +"ALTER TABLE `vtiger_profile2utility` TYPE=InnoDB", +"ALTER TABLE `vtiger_profile_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_quotegrouprelation` TYPE=InnoDB", +"ALTER TABLE `vtiger_rating` TYPE=InnoDB", +"ALTER TABLE `vtiger_relatedlists` TYPE=InnoDB", +"ALTER TABLE `vtiger_relatedlists_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_role2profile` TYPE=InnoDB", +"ALTER TABLE `vtiger_role_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_rss` TYPE=InnoDB", +"ALTER TABLE `vtiger_sales_stage` TYPE=InnoDB", +"ALTER TABLE `vtiger_salutationtype` TYPE=InnoDB", +"ALTER TABLE `vtiger_selectquery_seq` TYPE=InnoDB", +"ALTER TABLE `vtiger_sogrouprelation` TYPE=InnoDB", +"ALTER TABLE `vtiger_systems` TYPE=InnoDB", +"ALTER TABLE `vtiger_taskpriority` TYPE=InnoDB", +"ALTER TABLE `vtiger_taskstatus` TYPE=InnoDB", +"ALTER TABLE `vtiger_ticketcategories` TYPE=InnoDB", +"ALTER TABLE `vtiger_ticketpriorities` TYPE=InnoDB", +"ALTER TABLE `vtiger_ticketseverities` TYPE=InnoDB", +"ALTER TABLE `vtiger_ticketstatus` TYPE=InnoDB", +"ALTER TABLE `vtiger_ticketstracktime` TYPE=InnoDB", +"ALTER TABLE `vtiger_tracker` TYPE=InnoDB", +"ALTER TABLE `vtiger_users2group` TYPE=InnoDB", +"ALTER TABLE `vtiger_users_last_import` TYPE=InnoDB", +"ALTER TABLE `vtiger_users_seq` TYPE=InnoDB", +//"ALTER TABLE `vtiger_wordtemplates` TYPE=InnoDB", + +//Create table queries are moved from here to above this array + +"ALTER TABLE `vtiger_account` MODIFY COLUMN `website` VARCHAR(100) DEFAULT NULL", +//"ALTER TABLE `vtiger_activity` MODIFY COLUMN `date_start` DATE NOT NULL UNIQUE", +"ALTER TABLE `vtiger_activity` MODIFY COLUMN `sendnotification` VARCHAR(3) NOT NULL DEFAULT '0'", +"ALTER TABLE `vtiger_activity` MODIFY COLUMN `duration_hours` VARCHAR(2) DEFAULT NULL", +"ALTER TABLE `vtiger_activity` MODIFY COLUMN `duration_minutes` VARCHAR(2) DEFAULT NULL", +"ALTER TABLE `vtiger_activity_reminder` MODIFY COLUMN `reminder_time` INTEGER(11) NOT NULL", +"ALTER TABLE `vtiger_activity_reminder` MODIFY COLUMN `reminder_sent` INTEGER(2) NOT NULL", +//"ALTER TABLE `vtiger_blocks` MODIFY COLUMN `tabid` INTEGER(19) NOT NULL UNIQUE", +"ALTER TABLE `vtiger_blocks` MODIFY COLUMN `sequence` INTEGER(10) DEFAULT NULL", +"ALTER TABLE `vtiger_blocks` MODIFY COLUMN `show_title` INTEGER(2) DEFAULT NULL", + +//HANDLE HERE - MICKIE - Check the following queries + +"ALTER TABLE `vtiger_contactdetails` MODIFY COLUMN `donotcall` VARCHAR(3) DEFAULT NULL", +"ALTER TABLE `vtiger_contactdetails` MODIFY COLUMN `emailoptout` VARCHAR(3) DEFAULT '0'", +"ALTER TABLE `vtiger_contactdetails` MODIFY COLUMN `imagename` VARCHAR(150) DEFAULT NULL", +"ALTER TABLE `vtiger_contactdetails` MODIFY COLUMN `reference` VARCHAR(3) DEFAULT NULL", +//"ALTER TABLE `vtiger_contactgrouprelation` MODIFY COLUMN `contactid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_convertleadmapping` MODIFY COLUMN `leadfid` INTEGER(19) NOT NULL", +//"ALTER TABLE `vtiger_crmentity` MODIFY COLUMN `crmid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_crmentity` MODIFY COLUMN `description` TEXT", +"ALTER TABLE `vtiger_crmentity` MODIFY COLUMN `createdtime` DATETIME NOT NULL", +"ALTER TABLE `vtiger_crmentity` MODIFY COLUMN `modifiedtime` DATETIME NOT NULL", +"ALTER TABLE `vtiger_customaction` MODIFY COLUMN `cvid` INTEGER(19) NOT NULL UNIQUE", +"ALTER TABLE `vtiger_customaction` MODIFY COLUMN `content` TEXT", +//"ALTER TABLE `vtiger_customerdetails` MODIFY COLUMN `customerid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_customerdetails` MODIFY COLUMN `portal` VARCHAR(3) DEFAULT NULL", +//"ALTER TABLE `vtiger_customview` MODIFY COLUMN `cvid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_customview_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_cvadvfilter` MODIFY COLUMN `cvid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_cvadvfilter` MODIFY COLUMN `columnindex` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_cvcolumnlist` MODIFY COLUMN `cvid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_cvcolumnlist` MODIFY COLUMN `columnindex` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_cvstdfilter` MODIFY COLUMN `cvid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_dealintimation` MODIFY COLUMN `dealprobability` DECIMAL(3,2) NOT NULL DEFAULT '0.00'", +//"ALTER TABLE `vtiger_def_org_field` MODIFY COLUMN `fieldid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_def_org_share` MODIFY COLUMN `tabid` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_def_org_share` MODIFY COLUMN `permission` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_def_org_share_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_defaultcv` MODIFY COLUMN `tabid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_defaultcv` MODIFY COLUMN `query` TEXT", +"ALTER TABLE `vtiger_emailtemplates` MODIFY COLUMN `description` TEXT", +"ALTER TABLE `vtiger_emailtemplates` MODIFY COLUMN `body` TEXT", +//"ALTER TABLE `vtiger_emailtemplates_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +"ALTER TABLE `vtiger_faq` MODIFY COLUMN `question` TEXT", +"ALTER TABLE `vtiger_faq` MODIFY COLUMN `answer` TEXT", +"ALTER TABLE `vtiger_faqcomments` MODIFY COLUMN `comments` TEXT", +"ALTER TABLE `vtiger_faqcomments` MODIFY COLUMN `createdtime` DATETIME NOT NULL", +//"ALTER TABLE `vtiger_field` MODIFY COLUMN `tabid` INTEGER(19) NOT NULL UNIQUE", +"ALTER TABLE `vtiger_field` MODIFY COLUMN `readonly` INTEGER(1) NOT NULL", +"ALTER TABLE `vtiger_field` MODIFY COLUMN `selected` INTEGER(1) NOT NULL", +//"ALTER TABLE `vtiger_field` MODIFY COLUMN `block` INTEGER(19) DEFAULT NULL UNIQUE", +//"ALTER TABLE `vtiger_field` MODIFY COLUMN `displaytype` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_field` MODIFY COLUMN `quickcreate` INTEGER(10) NOT NULL DEFAULT '1'", +"ALTER TABLE `vtiger_field_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_group2grouprel` MODIFY COLUMN `groupid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_group2grouprel` MODIFY COLUMN `containsgroupid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_group2role` MODIFY COLUMN `groupid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_group2rs` MODIFY COLUMN `groupid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_groups` MODIFY COLUMN `groupid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_groups` MODIFY COLUMN `description` TEXT", +"ALTER TABLE `vtiger_import_maps` MODIFY COLUMN `is_published` VARCHAR(3) NOT NULL DEFAULT 'no'", +//"ALTER TABLE `vtiger_inventory_tandc` MODIFY COLUMN `id` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_inventory_tandc` MODIFY COLUMN `tandc` TEXT", +"ALTER TABLE `vtiger_inventory_tandc_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +"ALTER TABLE `vtiger_inventorynotification` MODIFY COLUMN `notificationbody` TEXT", +"ALTER TABLE `vtiger_inventorynotification_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_invoice` MODIFY COLUMN `salesorderid` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_invoice` MODIFY COLUMN `terms_conditions` TEXT", +//"ALTER TABLE `vtiger_invoicegrouprelation` MODIFY COLUMN `invoiceid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_lar` MODIFY COLUMN `createdon` DATE NOT NULL", +//"ALTER TABLE `vtiger_leaddetails` MODIFY COLUMN `leadid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_leaddetails` MODIFY COLUMN `comments` TEXT", +//"ALTER TABLE `vtiger_leadgrouprelation` MODIFY COLUMN `leadid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_mail_accounts` MODIFY COLUMN `account_id` INTEGER(11) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_mail_accounts` MODIFY COLUMN `user_id` INTEGER(11) NOT NULL", +"ALTER TABLE `vtiger_mail_accounts` ADD COLUMN `box_refresh` INTEGER(10) DEFAULT NULL", +"ALTER TABLE `vtiger_mail_accounts` ADD COLUMN `mails_per_page` INTEGER(10) DEFAULT NULL", +"ALTER TABLE `vtiger_mail_accounts` ADD COLUMN `ssltype` VARCHAR(50) DEFAULT NULL", +"ALTER TABLE `vtiger_mail_accounts` ADD COLUMN `sslmeth` VARCHAR(50) DEFAULT NULL", +"ALTER TABLE `vtiger_mail_accounts` ADD COLUMN `showbody` VARCHAR(10) DEFAULT NULL", +"ALTER TABLE `vtiger_notes` MODIFY COLUMN `contact_id` INTEGER(19) DEFAULT '0'", +"ALTER TABLE `vtiger_notes` MODIFY COLUMN `notecontent` TEXT", +"ALTER TABLE `vtiger_notificationscheduler` MODIFY COLUMN `notificationbody` TEXT", +"ALTER TABLE `vtiger_notificationscheduler_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +"ALTER TABLE `vtiger_opportunitystage` MODIFY COLUMN `probability` DECIMAL(3,2) DEFAULT '0.00'", +//"ALTER TABLE `vtiger_org_share_action2tab` MODIFY COLUMN `share_action_id` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_org_share_action2tab` MODIFY COLUMN `tabid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_org_share_action_mapping` MODIFY COLUMN `share_action_id` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_organizationdetails` MODIFY COLUMN `website` VARCHAR(100) DEFAULT NULL", +"ALTER TABLE `vtiger_organizationdetails` MODIFY COLUMN `logo` TEXT", +"ALTER TABLE `vtiger_ownernotify` MODIFY COLUMN `crmid` INTEGER(19) DEFAULT NULL UNIQUE", +//"ALTER TABLE `vtiger_parenttab` MODIFY COLUMN `parenttabid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_parenttab` MODIFY COLUMN `sequence` INTEGER(10) NOT NULL", +"ALTER TABLE `vtiger_parenttabrel` MODIFY COLUMN `parenttabid` INTEGER(3) NOT NULL", +//"ALTER TABLE `vtiger_parenttabrel` MODIFY COLUMN `tabid` INTEGER(3) NOT NULL UNIQUE", +"ALTER TABLE `vtiger_parenttabrel` MODIFY COLUMN `sequence` INTEGER(3) NOT NULL", +//"ALTER TABLE `vtiger_pogrouprelation` MODIFY COLUMN `purchaseorderid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_portal` MODIFY COLUMN `portalid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_portal` MODIFY COLUMN `portalname` VARCHAR(200) NOT NULL UNIQUE", +"ALTER TABLE `vtiger_portal` MODIFY COLUMN `sequence` INTEGER(3) NOT NULL", +//"ALTER TABLE `vtiger_portalinfo` MODIFY COLUMN `id` INTEGER(11) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_portalinfo` MODIFY COLUMN `last_login_time` DATETIME NOT NULL", +"ALTER TABLE `vtiger_portalinfo` MODIFY COLUMN `login_time` DATETIME NOT NULL", +"ALTER TABLE `vtiger_portalinfo` MODIFY COLUMN `logout_time` DATETIME NOT NULL", +//"ALTER TABLE `vtiger_potcompetitorrel` MODIFY COLUMN `potentialid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_potcompetitorrel` MODIFY COLUMN `competitorid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_potential` MODIFY COLUMN `amount` DECIMAL(10,2) DEFAULT '0.00'", +"ALTER TABLE `vtiger_potential` MODIFY COLUMN `description` TEXT", +//"ALTER TABLE `vtiger_potentialgrouprelation` MODIFY COLUMN `potentialid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_potstagehistory` MODIFY COLUMN `potentialid` INTEGER(19) NOT NULL", +"ALTER TABLE `vtiger_potstagehistory` MODIFY COLUMN `probability` DECIMAL(7,3) DEFAULT NULL", +"ALTER TABLE `vtiger_potstagehistory` MODIFY COLUMN `lastmodified` DATETIME default NULL", +"ALTER TABLE `vtiger_pricebook` MODIFY COLUMN `description` TEXT", +//"ALTER TABLE `vtiger_pricebookproductrel` MODIFY COLUMN `pricebookid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_pricebookproductrel` MODIFY COLUMN `productid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_productcollaterals` MODIFY COLUMN `productid` INTEGER(11) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_productcollaterals` MODIFY COLUMN `description` TEXT", +//"ALTER TABLE `vtiger_products` MODIFY COLUMN `productid` INTEGER(11) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_products` MODIFY COLUMN `product_description` TEXT", +"ALTER TABLE `vtiger_products` MODIFY COLUMN `commissionrate` DECIMAL(3,3) DEFAULT NULL", +//"ALTER TABLE `vtiger_profile2field` MODIFY COLUMN `profileid` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2field` MODIFY COLUMN `fieldid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2globalpermissions` MODIFY COLUMN `profileid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2globalpermissions` MODIFY COLUMN `globalactionid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2standardpermissions` MODIFY COLUMN `profileid` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2standardpermissions` MODIFY COLUMN `tabid` INTEGER(10) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2standardpermissions` MODIFY COLUMN `Operation` INTEGER(10) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2utility` MODIFY COLUMN `profileid` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2utility` MODIFY COLUMN `tabid` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_profile2utility` MODIFY COLUMN `activityid` INTEGER(11) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_profile_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_purchaseorder` MODIFY COLUMN `quoteid` INTEGER(19) DEFAULT NULL UNIQUE", +//"ALTER TABLE `vtiger_purchaseorder` MODIFY COLUMN `vendorid` INTEGER(19) DEFAULT NULL UNIQUE", +//"ALTER TABLE `vtiger_purchaseorder` MODIFY COLUMN `contactid` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_purchaseorder` MODIFY COLUMN `terms_conditions` TEXT", +//"ALTER TABLE `vtiger_quotegrouprelation` MODIFY COLUMN `quoteid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_quotes` MODIFY COLUMN `potentialid` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_quotes` MODIFY COLUMN `quotestage` VARCHAR(200) DEFAULT NULL", +//"ALTER TABLE `vtiger_quotes` MODIFY COLUMN `contactid` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_quotes` MODIFY COLUMN `terms_conditions` TEXT", +"ALTER TABLE `vtiger_recurringevents` MODIFY COLUMN `activityid` INTEGER(19) NOT NULL", +//"ALTER TABLE `vtiger_relatedlists` MODIFY COLUMN `relation_id` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_relatedlists_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_relcriteria` MODIFY COLUMN `queryid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_relcriteria` MODIFY COLUMN `columnindex` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_report` MODIFY COLUMN `reportid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_report` MODIFY COLUMN `folderid` INTEGER(19) NOT NULL UNIQUE", +//"ALTER TABLE `vtiger_reportdatefilter` MODIFY COLUMN `datefilterid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_role2profile` MODIFY COLUMN `profileid` INTEGER(11) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_role_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_rss` MODIFY COLUMN `rssid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_salesorder` MODIFY COLUMN `contactid` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_salesorder` MODIFY COLUMN `vendorid` INTEGER(19) DEFAULT NULL UNIQUE", +"ALTER TABLE `vtiger_salesorder` MODIFY COLUMN `terms_conditions` TEXT", +//"ALTER TABLE `vtiger_seactivityrel` MODIFY COLUMN `crmid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_seactivityrel` MODIFY COLUMN `activityid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_selectcolumn` MODIFY COLUMN `queryid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_selectquery` MODIFY COLUMN `queryid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_selectquery_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +//"ALTER TABLE `vtiger_sharedcalendar` MODIFY COLUMN `userid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_sharedcalendar` MODIFY COLUMN `sharedid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_sogrouprelation` MODIFY COLUMN `salesorderid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_systems` MODIFY COLUMN `id` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_systems` MODIFY COLUMN `server` VARCHAR(30) DEFAULT NULL", +"ALTER TABLE `vtiger_systems` MODIFY COLUMN `server_username` VARCHAR(30) DEFAULT NULL", +"ALTER TABLE `vtiger_systems` MODIFY COLUMN `server_password` VARCHAR(30) DEFAULT NULL", +"ALTER TABLE `vtiger_ticketcomments` MODIFY COLUMN `comments` TEXT", +"ALTER TABLE `vtiger_ticketcomments` MODIFY COLUMN `createdtime` DATETIME NOT NULL", +//"ALTER TABLE `vtiger_ticketgrouprelation` MODIFY COLUMN `ticketid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_troubletickets` MODIFY COLUMN `ticketid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_troubletickets` MODIFY COLUMN `description` TEXT", +"ALTER TABLE `vtiger_troubletickets` MODIFY COLUMN `solution` TEXT", +"ALTER TABLE `vtiger_troubletickets` MODIFY COLUMN `update_log` TEXT", +//"ALTER TABLE `vtiger_user2role` MODIFY COLUMN `userid` INTEGER(11) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_user2role` MODIFY COLUMN `roleid` VARCHAR(255) NOT NULL UNIQUE", +"ALTER TABLE `vtiger_users` MODIFY COLUMN `is_admin` VARCHAR(3) DEFAULT '0'", +"ALTER TABLE `vtiger_users` MODIFY COLUMN `description` TEXT", +"ALTER TABLE `vtiger_users` MODIFY COLUMN `user_preferences` TEXT", +"ALTER TABLE `vtiger_users` MODIFY COLUMN `homeorder` VARCHAR(255) DEFAULT 'ALVT,PLVT,QLTQ,CVLVT,HLT,OLV,GRT,OLTSO,ILTI,MNL'", +"ALTER TABLE `vtiger_users` ADD COLUMN `currency_id` INTEGER(19) NOT NULL DEFAULT '1'", +"ALTER TABLE `vtiger_users` ADD COLUMN `defhomeview` VARCHAR(100) DEFAULT 'home_metrics'", +//"ALTER TABLE `vtiger_users2group` MODIFY COLUMN `groupid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_users2group` MODIFY COLUMN `userid` INTEGER(19) NOT NULL PRIMARY KEY", +"ALTER TABLE `vtiger_users_seq` MODIFY COLUMN `id` INTEGER(11) NOT NULL", +"ALTER TABLE `vtiger_vendor` MODIFY COLUMN `street` TEXT", +"ALTER TABLE `vtiger_vendor` MODIFY COLUMN `description` TEXT", +//"ALTER TABLE `vtiger_wordtemplates` MODIFY COLUMN `templateid` INTEGER(19) NOT NULL PRIMARY KEY", +//"ALTER TABLE `vtiger_wordtemplates` MODIFY COLUMN `description` TEXT", +"ALTER TABLE `vtiger_activity` ADD KEY `status1` (`status`, `eventstatus`)", +"ALTER TABLE `vtiger_attachments` ADD KEY `attachmentsid1` (`attachmentsid`)", +"ALTER TABLE `vtiger_blocks` ADD KEY `block_tabid` (`tabid`)", +"ALTER TABLE `vtiger_carrier` DROP INDEX `carrier_UK0`", +"ALTER TABLE `vtiger_carrier` ADD UNIQUE KEY `carrier_carrier_idx` (`carrier`)", +"ALTER TABLE `vtiger_contactgrouprelation` ADD KEY `contactgrouprelation_IDX1` (`groupname`)", +"ALTER TABLE `vtiger_def_org_field` ADD KEY `tabid4` (`tabid`)", +"ALTER TABLE `vtiger_def_org_share` ADD KEY `fk_def_org_share23` (`permission`)", +"ALTER TABLE `vtiger_field` ADD KEY `tabid2` (`tabid`)", +"ALTER TABLE `vtiger_field` ADD KEY `blockid` (`block`)", +"ALTER TABLE `vtiger_field` ADD KEY `displaytypeid` (`displaytype`)", +"ALTER TABLE `vtiger_group2grouprel` ADD KEY `fk_group2grouprel2` (`containsgroupid`)", +"ALTER TABLE `vtiger_group2role` ADD KEY `fk_group2role2` (`roleid`)", +"ALTER TABLE `vtiger_group2rs` ADD KEY `fk_group2rs2` (`roleandsubid`)", +"ALTER TABLE `vtiger_groups` ADD KEY `idx_groups_123group` (`groupname`)", +"ALTER TABLE `vtiger_invoice` ADD KEY `SoPo_IDX` (`invoiceid`)", +"ALTER TABLE `vtiger_invoice` ADD KEY `fk_Invoice2` (`salesorderid`)", +"ALTER TABLE `vtiger_invoicegrouprelation` ADD KEY `invoicegrouprelation_IDX1` (`groupname`, `invoiceid`)", +"ALTER TABLE `vtiger_leadgrouprelation` ADD KEY `leadgrouprelation_IDX0` (`leadid`)", +"ALTER TABLE `vtiger_moduleowners` ADD KEY `moduleowners_UK11` (`tabid`, `user_id`)", +//"ALTER TABLE `vtiger_org_share_action2tab` ADD KEY `fk_org_share_action2tab12345` (`tabid`)", +"ALTER TABLE `vtiger_ownernotify` ADD KEY `ownernotify_UK1` (`crmid`, `flag`)", +"ALTER TABLE `vtiger_parenttab` ADD KEY `parenttab_UK1` (`parenttabid`, `parenttab_label`, `visible`)", +"ALTER TABLE `vtiger_parenttabrel` ADD KEY `parenttabrelUK01` (`tabid`, `parenttabid`)", +"ALTER TABLE `vtiger_pogrouprelation` ADD KEY `pogrouprelation_IDX1` (`groupname`, `purchaseorderid`)", +"ALTER TABLE `vtiger_portal` ADD KEY `portal_UK01` (`portalname`)", +"ALTER TABLE `vtiger_potential` ADD KEY `potentialid1` (`potentialid`)", +"ALTER TABLE `vtiger_potentialgrouprelation` ADD KEY `potentialgrouprelation_IDX1` (`groupname`)", +"ALTER TABLE `vtiger_potstagehistory` DROP INDEX PotStageHistory_IDX1", +"ALTER TABLE `vtiger_potstagehistory` ADD INDEX `PotStageHistory_IDX1` (`historyid`)", +"ALTER TABLE `vtiger_potstagehistory` ADD KEY `fk_PotStageHistory` (`potentialid`)", +"ALTER TABLE `vtiger_profile2field` ADD KEY `tabid3` (`tabid`, `profileid`)", +//"ALTER TABLE `vtiger_profile2globalpermissions` ADD KEY `idx_profile2globalpermissions` (`profileid`, `globalactionid`)", +"ALTER TABLE `vtiger_profile2standardpermissions` ADD KEY `idx_prof2stad` (`profileid`, `tabid`, `Operation`)", +"ALTER TABLE `vtiger_profile2utility` ADD KEY `idx_prof2utility` (`profileid`, `tabid`, `activityid`)", +"ALTER TABLE `vtiger_purchaseorder` ADD KEY `PO_Vend_IDX` (`vendorid`)", +"ALTER TABLE `vtiger_purchaseorder` ADD KEY `PO_Quote_IDX` (`quoteid`)", +"ALTER TABLE `vtiger_purchaseorder` ADD KEY `PO_Contact_IDX` (`contactid`)", +"ALTER TABLE `vtiger_quotegrouprelation` ADD KEY `quotegrouprelation_IDX1` (`groupname`)", +//"ALTER TABLE `vtiger_quotes` DROP INDEX vtiger_quotestage", +"ALTER TABLE `vtiger_quotes` ADD INDEX `quotestage` (`quoteid`)", +"ALTER TABLE `vtiger_quotes` ADD KEY `potentialid2` (`potentialid`)", +"ALTER TABLE `vtiger_quotes` ADD KEY `contactid` (`contactid`)", +"ALTER TABLE `vtiger_recurringtype` ADD UNIQUE KEY `RecurringEvent_UK0` (`recurringtype`)", +"ALTER TABLE `vtiger_role2profile` ADD KEY `idx_role2profileid1` (`roleid`, `profileid`)", +"ALTER TABLE `vtiger_salesorder` ADD KEY `SoVend_IDX` (`vendorid`)", +"ALTER TABLE `vtiger_salesorder` ADD KEY `SoContact_IDX` (`contactid`)", +"ALTER TABLE `vtiger_seattachmentsrel` ADD KEY `attachmentsid2` (`attachmentsid`, `crmid`)", +"ALTER TABLE `vtiger_selectquery` ADD KEY `selectquery_IDX0` (`queryid`)", +"ALTER TABLE `vtiger_sogrouprelation` ADD KEY `sogrouprelation_IDX1` (`groupname`)", +"ALTER TABLE `vtiger_tab` ADD KEY `tabid1` (`tabid`)", +"ALTER TABLE `vtiger_taxclass` ADD UNIQUE KEY `taxclass_carrier_idx` (`taxclass`)", +"ALTER TABLE `vtiger_troubletickets` ADD KEY `status2` (`status`)", +"ALTER TABLE `vtiger_users2group` ADD KEY `idx_users2group` (`groupid`, `userid`)", +"ALTER TABLE `vtiger_users2group` ADD KEY `fk_users2group2` (`userid`)", +"ALTER TABLE `vtiger_customaction` ADD CONSTRAINT `customaction_FK1` FOREIGN KEY (`cvid`) REFERENCES `vtiger_customview` (`cvid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_profile2globalpermissions` ADD CONSTRAINT `fk_profile2globalpermissions57` FOREIGN KEY (`profileid`) REFERENCES `vtiger_profile` (`profileid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_invoice` ADD CONSTRAINT `fk_Invoice2` FOREIGN KEY (`salesorderid`) REFERENCES `vtiger_salesorder` (`salesorderid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_purchaseorder` ADD CONSTRAINT `fk_PO3` FOREIGN KEY (`contactid`) REFERENCES `vtiger_contactdetails` (`contactid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_purchaseorder` ADD CONSTRAINT `fk_PO2` FOREIGN KEY (`vendorid`) REFERENCES `vtiger_vendor` (`vendorid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_purchaseorder` ADD CONSTRAINT `fk_PO2345` FOREIGN KEY (`quoteid`) REFERENCES `vtiger_quotes` (`quoteid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_quotes` ADD CONSTRAINT `fk_Quotes3` FOREIGN KEY (`contactid`) REFERENCES `vtiger_contactdetails` (`contactid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_quotes` ADD CONSTRAINT `fk_Quotes2` FOREIGN KEY (`potentialid`) REFERENCES `vtiger_potential` (`potentialid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_salesorder` ADD CONSTRAINT `fk_SO4` FOREIGN KEY (`contactid`) REFERENCES `vtiger_contactdetails` (`contactid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_salesorder` ADD CONSTRAINT `fk_SO2` FOREIGN KEY (`vendorid`) REFERENCES `vtiger_vendor` (`vendorid`) ON DELETE CASCADE", +"ALTER TABLE `vtiger_vendorcontactrel` ADD CONSTRAINT `fk_VendorContactRel45` FOREIGN KEY (`vendorid`) REFERENCES `vtiger_vendor` (`vendorid`) ON DELETE CASCADE" + ); +foreach($query_array as $query) +{ + //Execute($query); + //These above array queries will not make any problems if failed to execute. whereas the user get confused if it fails. so we are not goiong to display these queries if it is executed successfully or not + $conn->query($query); +} + +//First check whether this table is exist and the proceed +$currency_columns = $conn->getColumnNames("vtiger_currency_info"); +if(!is_array($currency_columns)) +{ + $currency_query = "CREATE TABLE `vtiger_currency_info` ( + `id` int(11) NOT NULL auto_increment, + `currency_name` varchar(100) default NULL, + `currency_code` varchar(100) default NULL, + `currency_symbol` varchar(30) default NULL, + `conversion_rate` decimal(10,3) default NULL, + `currency_status` varchar(25) default NULL, + `defaultid` varchar(10) NOT NULL default '0', + PRIMARY KEY (`id`) + ) ENGINE=InnoDB"; + Execute($currency_query); +} +elseif(!in_array("id",$currency_columns)) +{ + $currency_query_array = Array( + "alter table vtiger_currency_info drop primary key", + "alter table vtiger_currency_info add column id int(11) NOT NULL auto_increment primary key FIRST", + "alter table vtiger_currency_info add column conversion_rate decimal(10,3) default NULL", + "alter table vtiger_currency_info add column currency_status varchar(25) default NULL", + "alter table vtiger_currency_info add column defaultid varchar(10) NOT NULL default '0'", + ); + foreach($currency_query_array as $query) + { + Execute($query); + } +} + +$migrationlog->debug("Database Modifications for 5.0(Alpha) Dev 3 ==> 5.0 Alpha (5) ends here."); + + +/************************* The following changes have been made after 5.0 Alpha 5 *************************/ +$migrationlog->debug("Database Modifications after 5.0(Alpha 5) starts here."); + + +//Added on 22-04-06 - to add the Notify Owner vtiger_field in Contacts and Accounts +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (4, $newfieldid, 'notify_owner','contactdetails',1,56,'notify_owner','Notify Owner',1,0,0,10,24,4,1,'C~O',1,NULL,'ADV')"; +Execute($insert_query); +populateFieldForSecurity('4',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (6, $newfieldid, 'notify_owner','account',1,56,'notify_owner','Notify Owner',1,0,0,10,18,9,1,'C~O',1,NULL,'ADV')"; +Execute($insert_query); +populateFieldForSecurity('6',$newfieldid); + +$notify_owner_array = Array( + "update vtiger_field set sequence=26 where tabid=4 and fieldname='modifiedtime'", + "update vtiger_field set sequence=25 where tabid=4 and fieldname='createdtime'", + + //"insert into vtiger_field values(4,".$conn->getUniqueID("vtiger_field").",'notify_owner','contactdetails',1,56,'notify_owner','Notify Owner',1,0,0,10,24,4,1,'C~O',1,NULL,'ADV')", + "alter table vtiger_contactdetails add column notify_owner varchar(3) default 0 after reference", + + "update vtiger_field set sequence=21 where tabid=6 and fieldname='modifiedtime'", + "update vtiger_field set sequence=20 where tabid=6 and fieldname='createdtime'", + "update vtiger_field set sequence=19 where tabid=6 and fieldname='assigned_user_id'", + + //"insert into vtiger_field values(6,".$conn->getUniqueID("vtiger_field").",'notify_owner','account',1,56,'notify_owner','Notify Owner',1,0,0,10,18,9,1,'C~O',1,NULL,'ADV')", + "alter table vtiger_account add column notify_owner varchar(3) default 0 after emailoptout" + ); +foreach($notify_owner_array as $query) +{ + Execute($query); +} + +//Added for RSS entries +$newfieldid = $conn->getUniqueID("vtiger_field"); +$rss_insert_query = "insert into vtiger_field values (24, $newfieldid, 'rsscategory','rss',1,'15','rsscategory','rsscategory',1,0,0,255,13,null,1,'V~O',1,null,'BAS')"; +Execute($rss_insert_query); +populateFieldForSecurity('24',$newfieldid); + +//Quick Create Feature added for Vendor & PriceBook +$quickcreate_query = Array( + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 18 and fieldname = 'vendorname'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 18 and fieldname = 'phone'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 3 WHERE tabid = 18 and fieldname = 'email'", + + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 1 WHERE tabid = 19 and fieldname = 'bookname'", + "UPDATE vtiger_field SET quickcreate = 0,quickcreatesequence = 2 WHERE tabid = 19 and fieldname = 'active'" + ); +foreach($quickcreate_query as $query) +{ + Execute($query); +} + + +//Added on 24-04-06 to populate vtiger_customview All for Campaign and webmails modules +$cvid1 = $conn->getUniqueID("vtiger_customview"); +$cvid2 = $conn->getUniqueID("vtiger_customview"); +$customview_query_array = Array( + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$cvid1.",'All',1,0,'Campaigns')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid1.",0,'vtiger_campaign:campaignname:campaignname:Campaigns_Campaign_Name:V')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid1.",1,'vtiger_campaign:campaigntype:campaigntype:Campaigns_Campaign_Type:N')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid1.",2,'vtiger_campaign:campaignstatus:campaignstatus:Campaigns_Campaign_Status:N')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid1.",3,'vtiger_campaign:expectedrevenue:expectedrevenue:Campaigns_Expected_Revenue:V')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid1.",4,'vtiger_campaign:closingdate:closingdate:Campaigns_Expected_Close_Date:D')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid1.",5,'vtiger_crmentity:smownerid:assigned_user_id:Campaigns_Assigned_To:V')", + + + "insert into vtiger_customview(cvid,viewname,setdefault,setmetrics,entitytype) values(".$cvid2.",'All',1,0,'Webmails')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid2.",0,'subject:subject:subject:Subject:V')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid2.",1,'from:fromname:fromname:From:N')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid2.",2,'to:tpname:toname:To:N')", + "insert into vtiger_cvcolumnlist (cvid,columnindex,columnname) values (".$cvid2.",3,'body:body:body:Body:V')" + + ); +foreach($customview_query_array as $query) +{ + Execute($query); +} + + +$query_array2 = Array( + //"INSERT INTO vtiger_parenttabrel VALUES(2,4,2)", + //"INSERT INTO vtiger_parenttabrel VALUES(2,6,3)", + "update vtiger_cvcolumnlist set columnname ='vtiger_crmentity:smownerid:assigned_user_id:Emails_Sender:V' where columnname='vtiger_crmentity:smownerid:assigned_user_id:Emails_Assigned_To:V'", + "update vtiger_field set sequence = 2 where columnname='filename' and tablename = 'vtiger_attachments'", + "delete from vtiger_cvcolumnlist where columnname = 'vtiger_seactivityrel:crmid:parent_id:Emails_Related_To:I'", + //"update vtiger_cvcolumnlist set columnindex = 1 where cvid=20 and columnindex=3", + "update vtiger_field set info_type='ADV' where tabid=18 and columnname in ('street','pobox','city','state','postalcode','country','description')", + "update vtiger_field set info_type='ADV' where tabid in (20,21,22,23) and columnname in ('description','terms_conditions')", + + "create table vtiger_inventorytaxinfo (taxid int(3) NOT NULL, taxname varchar(50) default NULL, taxlabel varchar(50) default NULL, percentage decimal(7,3) default NULL, deleted int(1) default 0, PRIMARY KEY (taxid), KEY vtiger_inventorytaxinfo_taxname_idx (taxname))", + "create table vtiger_producttaxrel ( productid int(11) NOT NULL, taxid int(3) NOT NULL, taxpercentage decimal(7,3) default NULL, KEY vtiger_producttaxrel_productid_idx (productid), KEY vtiger_producttaxrel_taxid_idx (taxid))", + "alter table vtiger_producttaxrel ADD CONSTRAINT fk_1_vtiger_producttaxrel FOREIGN KEY (productid) REFERENCES vtiger_products(productid) ON DELETE CASCADE", + + "update vtiger_field set uitype=83, tablename='vtiger_producttaxrel' where tabid=14 and fieldname='taxclass'", + "insert into vtiger_moduleowners values(".$this->localGetTabID('Campaigns').",1)", + + "alter table vtiger_attachments add column path varchar(255) default NULL" + ); + +foreach($query_array2 as $query) +{ + Execute($query); +} + +//This code will retrieve all the attachments from db and write it in a file +$attach_query_result = $conn->query("select vtiger_crmentity.createdtime, vtiger_attachments.* from vtiger_attachments inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_attachments.attachmentsid"); +$noof_attachments = $conn->num_rows($attach_query_result); +for($attach_count = 0;$attach_count < $noof_attachments ;$attach_count++) +{ + $attach_id = $conn->query_result($attach_query_result,$attach_count,'attachmentsid'); + $attach_name = $conn->query_result($attach_query_result,$attach_count,'name'); + $attach_data = $conn->query_result($attach_query_result,$attach_count,'attachmentcontents'); + + $created_time = $conn->query_result($attach_query_result,$attach_count,'createdtime'); + //$filepath = decideFilePath(); + + //Added to set the file path where to store the file based on the created time + $date = explode(" ",$created_time); + $date_details = explode("-",$date[0]); + + $year = $date_details[0]; + $month = $date_details[1]; + $day = $date_details[2]; + + //this is used to convert the month from number to string ie., 03 - March, 04 - April, etc., + $month = date("F", mktime(0, 0, 0, $month, $day, $year)); + + $week_no = floor(($day-1)/7)+1;//decide the week ie., 1-7 = week1, 8-14=week2, 15-21=week3, etc., + $week = "week".$week_no; + + $filepath = 'storage/'; + + if(!is_dir($filepath.$year)) + mkdir($filepath.$year); + if(!is_dir($filepath.$year."/".$month)) + mkdir($filepath."$year/$month"); + if(!is_dir($filepath.$year."/".$month."/".$week)) + mkdir($filepath."$year/$month/$week"); + + $filepath = $filepath.$year."/".$month."/".$week."/"; + $migrationlog->debug("File Path = $filepath"); + //upto this added to set the file path based on attachment created time + + //In this file name (attachmentid_filename) the file will be stored in the harddisk + $moved_filename = $attach_id."_".$attach_name; + //write the contents in the file + $handle = @fopen($filepath.$moved_filename,'w'); + fputs($handle, base64_decode($attach_data)); + fclose($handle); + + //update the path in the db + $update_attach = Execute("update vtiger_attachments set path='".$filepath."' where attachmentsid=$attach_id"); +} + +//Before drop these fields we had read the contents of the file from db and wrote it in a file. +$alter_query_array = Array( + "alter table vtiger_attachments drop column attachmentsize", + "alter table vtiger_attachments drop column attachmentcontents" + ); +foreach($alter_query_array as $query) +{ + Execute($query); +} + + +//To populate the comboStrings for Campaigns module which are added newly +require_once('include/ComboStrings.php'); +global $combo_strings; + +$comboTables = Array('campaigntype','campaignstatus','expectedresponse'); +foreach ($comboTables as $tablename) +{ + $values = $combo_strings[$tablename."_dom"]; + $i=0; + foreach ($values as $val => $cal) + { + if($val != '') + { + $conn->query("insert into vtiger_".$tablename. " values(null,'".$val."',".$i.",1)"); + } + else + { + $conn->query("insert into vtiger_".$tablename. " values(null,'--None--',".$i.",1)"); + } + $i++; + } + +} + +$update_query3 = "update vtiger_currency_info set conversion_rate=1, currency_status='Active', defaultid='-11' where id=1"; +Execute($update_query3); + +$update_query4 = "update vtiger_relatedlists set label='Purchase Order' where tabid=18 and name='get_purchase_orders'"; +Execute($update_query4); + + + +//Added on 27-05-06 + +$create_query27 = "CREATE TABLE vtiger_invitees (activityid int(19) NOT NULL, inviteeid int(19) NOT NULL, PRIMARY KEY (activityid,inviteeid))"; +Execute($create_query27); + +$alter_query_array17 = Array( + "ALTER TABLE vtiger_users ADD column hour_format varchar(30) default 'am/pm' AFTER date_format", + "ALTER TABLE vtiger_users ADD column start_hour varchar(30) default '10:00' AFTER hour_format", + "ALTER TABLE vtiger_users ADD column end_hour varchar(30) default '23:00' AFTER start_hour" + ); +foreach($alter_query_array17 as $query) +{ + Execute($query); +} + +$create_query28 = "CREATE TABLE vtiger_emaildetails ( + emailid int(19) NOT NULL, + from_email varchar(50) NOT NULL default '', + to_email text, + cc_email text, + bcc_email text, + assigned_user_email varchar(50) NOT NULL default '', + idlists varchar(50) NOT NULL default '', + email_flag varchar(50) NOT NULL default '', + PRIMARY KEY (`emailid`) + )"; +Execute($create_query28); + + +$obj_array = Array('Leads'=>'vtiger_leaddetails','Contacts'=>'vtiger_contactdetails'); +$leadfieldid = $conn->query_result($conn->query("select fieldid from vtiger_field where tabid=7 and fieldname='email'"),0,'fieldid'); +$contactfieldid = $conn->query_result($conn->query("select fieldid from vtiger_field where tabid=4 and fieldname='email'"),0,'fieldid'); +$fieldid_array = Array("Leads"=>"$leadfieldid","Contacts"=>"$contactfieldid"); +$idname_array = Array("Leads"=>"leadid","Contacts"=>"contactid"); + +$query = 'select * from vtiger_seactivityrel where activityid in (select activityid from vtiger_activity where activitytype="Emails") group by activityid'; +$result = $conn->query($query); +$numofrows = $conn->num_rows($result); + +for($i=0;$i<$numofrows;$i++) +{ + $toemail = ""; + $idlists = ''; + + $emailid = $conn->query_result($result,$i,'activityid'); + + $result1 = $conn->query("select * from vtiger_seactivityrel where activityid = $emailid"); + while($row = $conn->fetch_array($result1)) + { + $result2 = $conn->query("select setype from vtiger_crmentity where crmid=".$row['crmid']); + $module = $conn->query_result($result2,0,'setype'); + $idlists .= $row['crmid']."@$fieldid_array[$module]|"; + + if($module == 'Leads' || $module == 'Contacts') + { + $result3 = $conn->query("select lastname, firstname, email from $obj_array[$module] where $idname_array[$module] = ".$row['crmid']); + + $toemail .= $conn->query_result($result3,0,'lastname')." ".$conn->query_result($result3,0,'firstname')."<".$conn->query_result($result3,0,'email').">###"; + } + else + { + //the parent is not a Lead or Contact. so we have avoided the insert query + } + } + + //insert this idlists and toemail values in vtiger_emaildetails table + $sql = "insert into vtiger_emaildetails values ($emailid,'',\"$toemail\",'','','',\"$idlists\",'SAVE')"; + Execute($sql); +} + + +$update_query5 = "update vtiger_field set quickcreate=1, quickcreatesequence=NULL where tabid in (10,14)"; +Execute($update_query5); + + + +//Security vtiger_profile and vtiger_tab table handling by DON starts +$sql_sec="select profileid from vtiger_profile"; +$result_sec=$conn->query($sql_sec); +$num_rows=$conn->num_rows($result_sec); +for($i=0;$i<$num_rows;$i++) +{ + $prof_id=$conn->query_result($result_sec,$i,'profileid'); + $sql1_sec="insert into vtiger_profile2utility values(".$prof_id.",13,8,0)"; + Execute($sql1_sec); + + $sql2_sec="insert into vtiger_profile2utility values(".$prof_id.",7,9,0)"; + Execute($sql2_sec); + + $sql3_sec="insert into vtiger_profile2tab values(".$prof_id.",26,0)"; + Execute($sql3_sec); + + $sql4_sec="insert into vtiger_profile2tab values(".$prof_id.",27,0)"; + Execute($sql4_sec); + + $sql7_sec="insert into vtiger_profile2standardpermissions values(".$prof_id.",26,0,0)"; + Execute($sql7_sec); + + $sql8_sec="insert into vtiger_profile2standardpermissions values(".$prof_id.",26,1,0)"; + Execute($sql8_sec); + + $sql9_sec="insert into vtiger_profile2standardpermissions values(".$prof_id.",26,2,0)"; + Execute($sql9_sec); + + $sql10_sec="insert into vtiger_profile2standardpermissions values(".$prof_id.",26,3,0)"; + Execute($sql10_sec); + + $sql11_sec="insert into vtiger_profile2standardpermissions values(".$prof_id.",26,4,0)"; + Execute($sql11_sec); + +} + +//Inserting into vtiger_tab tables +$sec2="INSERT INTO vtiger_tab VALUES (27,'Portal',0,24,'Portal',null,null,1)"; +$sec3="INSERT INTO vtiger_tab VALUES (28,'Webmails',0,25,'Webmails',null,null,1)"; + +//Insert into vtiger_def_org_share tables +$sec4="insert into vtiger_def_org_share values (".$conn->getUniqueID('vtiger_def_org_share').",26,2,0)"; + +Execute($sec2); +Execute($sec3); +Execute($sec4); + +//Inserting into datashare related modules table + +Execute("insert into vtiger_datashare_relatedmodules_seq values(1)"); + +//Lead Related Module +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",7,10)"); + +//Account Related Module +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",6,2)"); +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",6,13)"); +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",6,20)"); +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",6,22)"); +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",6,23)"); +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",6,10)"); + + +//Potential Related Module +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",2,20)"); +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",2,22)"); + +//Quote Related Module +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",20,22)"); + +//SO Related Module +Execute("insert into vtiger_datashare_relatedmodules values (".$conn->getUniqueID('vtiger_datashare_relatedmodules').",22,23)"); + + +//By Don Ends + +//Added the vtiger_tabel vtiger_mail_accounts which has been added by mmbrich +$alter_query18 = "alter table vtiger_mail_accounts add column int_mailer int(1) default '0'"; +Execute($alter_query18); + +$update_query_array5 = Array( + "update vtiger_field set info_type='BAS' where tabid=6 and fieldname in ('tickersymbol','account_id')", + "update vtiger_relatedlists set label = 'Activity History' where tabid in (4,6,7,20,21,22,23) and label = 'History'", + "update vtiger_relatedlists set label = 'Products' where tabid=2 and name='get_products' and label='History'", + "update vtiger_relatedlists set label = 'Activity History' where tabid=2 and name='get_history' and label='History'" + ); +foreach($update_query_array5 as $query) +{ + Execute($query); +} + +$insert_query_array27 = Array( + "insert into vtiger_relatedlists values(".$conn->getUniqueID('vtiger_relatedlists').",13,0,'get_ticket_history',3,'Ticket History',0)", + "insert into vtiger_parenttabrel values (2,10,4)", + "insert into vtiger_parenttabrel values (4,10,7)" + ); +foreach($insert_query_array27 as $query) +{ + Execute($query); +} + + +//User fields added in field table +$user_query_array = Array( + +"alter table vtiger_users add column confirm_password varchar(50)", +"insert into vtiger_tab values (29,'Users',0,26,'Users',null,null,1)", + +"insert into vtiger_blocks values (79,29,'LBL_USERLOGIN_ROLE',1,0,0,0,0,0)", +"insert into vtiger_blocks values (80,29,'LBL_MORE_INFORMATION',2,0,0,0,0,0)", +"insert into vtiger_blocks values (81,29,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0)", + ); +foreach($user_query_array as $query) +{ + Execute($query); +} + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid, 'user_name','vtiger_users',1,'106','user_name','User Name',1,0,0,11,1,79,1,'V~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid, 'is_admin','vtiger_users',1,'156','is_admin','Admin',1,0,0,3,2,79,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid, 'user_password','vtiger_users',1,'99','user_password','Password',1,0,0,30,3,79,4,'P~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid, 'confirm_password','vtiger_users',1,'99','confirm_password','Confirm Password',1,0,0,30,4,79,4,'P~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'first_name','vtiger_users',1,'1','first_name','First Name',1,0,0,30,5,79,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'last_name','vtiger_users',1,'2','last_name','Last Name',1,0,0,30,6,79,1,'V~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'roleid','vtiger_user2role',1,'98','roleid','Role',1,0,0,200,7,79,1,'V~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'email1','vtiger_users',1,'104','email1','Email',1,0,0,100,9,79,1,'E~M',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'status','vtiger_users',1,'115','status','Status',1,0,0,100,10,79,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'activity_view','vtiger_users',1,'15','activity_view','Default Activity View',1,0,0,100,13,79,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'lead_view','vtiger_users',1,'15','lead_view','Default Lead View',1,0,0,100,12,79,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'currency_id','vtiger_users',1,'116','currency_id','Currency',1,0,0,100,11,79,1,'I~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'title','vtiger_users',1,'1','title','Title',1,0,0,50,1,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'phone_work','vtiger_users',1,'1','phone_work','Office Phone',1,0,0,50,2,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'department','vtiger_users',1,'1','department','Department',1,0,0,50,3,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'phone_mobile','vtiger_users',1,'1','phone_mobile','Mobile',1,0,0,50,4,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'reports_to_id','vtiger_users',1,'101','reports_to_id','Reports To',1,0,0,50,5,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'phone_other','vtiger_users',1,'1','phone_other','Other Phone',1,0,0,50,5,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'email2','vtiger_users',1,'13','email2','Other Email',1,0,0,100,6,80,1,'E~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'phone_fax','vtiger_users',1,'1','phone_fax','Fax',1,0,0,50,7,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'yahoo_id','vtiger_users',1,'13','yahoo_id','Yahoo id',1,0,0,100,7,80,1,'E~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'phone_home','vtiger_users',1,'1','phone_home','Home Phone',1,0,0,50,8,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'imagename','vtiger_users',1,'105','imagename','User Image',1,0,0,250,9,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'date_format','vtiger_users',1,'15','date_format','Date Format',1,0,0,30,10,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'tagcloud','vtiger_users',1,'103','tagcloud','Tag Cloud',1,0,0,250,13,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'signature','vtiger_users',1,'21','signature','Signature',1,0,0,250,11,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'description','vtiger_users',1,'21','description','Notes',1,0,0,250,12,80,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'address_street','vtiger_users',1,'21','address_street','Street Address',1,0,0,250,1,81,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'address_city','vtiger_users',1,'1','address_city','City',1,0,0,100,2,81,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'address_state','vtiger_users',1,'1','address_state','State',1,0,0,100,3,81,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'address_postalcode','vtiger_users',1,'1','address_postalcode','Postal Code',1,0,0,100,4,81,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$insert_query = "insert into vtiger_field values (29, $newfieldid,'address_country','vtiger_users',1,'1','address_country','Country',1,0,0,100,5,81,1,'V~O',1,null,'BAS')"; +Execute($insert_query); +populateFieldForSecurity('29',$newfieldid); + + +$create_query29 = "CREATE TABLE vtiger_status ( + `statusid` int(19) NOT NULL auto_increment, + `status` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`statusid`) + )"; +Execute($create_query29); + +Execute("insert into vtiger_status values (1,'Active',0,1)"); +Execute("insert into vtiger_status values (2,'Inactive',1,1)"); + +$create_query30 = "CREATE TABLE vtiger_activity_view ( + `activity_viewid` int(19) NOT NULL auto_increment, + `activity_view` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`activity_viewid`) + )"; +Execute($create_query30); + +Execute("insert into vtiger_activity_view values (1,'Today',0,1)"); +Execute("insert into vtiger_activity_view values (2,'This Week',1,1)"); +Execute("insert into vtiger_activity_view values (3,'This Month',2,1)"); +Execute("insert into vtiger_activity_view values (4,'This Year',3,1)"); + + +$create_query31 = "CREATE TABLE vtiger_lead_view ( + `lead_viewid` int(19) NOT NULL auto_increment, + `lead_view` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`lead_viewid`) + )"; +Execute($create_query31); + +Execute("insert into vtiger_lead_view values (1,'Today',0,1)"); +Execute("insert into vtiger_lead_view values (2,'Last 2 Days',1,1)"); +Execute("insert into vtiger_lead_view values (3,'Last Week',2,1)"); + + +$create_query32 = "CREATE TABLE vtiger_date_format ( + `date_formatid` int(19) NOT NULL auto_increment, + `date_format` varchar(200) NOT NULL, + `sortorderid` int(19) NOT NULL default '0', + `presence` int(1) NOT NULL default '1', + PRIMARY KEY (`date_formatid`) + )"; +Execute($create_query32); + +Execute("insert into vtiger_date_format values (1,'dd-mm-yyyy',0,1)"); +Execute("insert into vtiger_date_format values (2,'mm-dd-yyyy',1,1)"); +Execute("insert into vtiger_date_format values (3,'yyyy-mm-dd',2,1)"); +//end of User fields added in field table + +//Activities and Leads Added under Marketing +Execute("insert into vtiger_parenttabrel values (2,7,5)"); +Execute("insert into vtiger_parenttabrel values (2,9,6)"); +Execute("insert into vtiger_parenttabrel values (4,9,8)"); + +//Queries to remove the rss categories +Execute("drop table vtiger_rsscategory"); +Execute("delete from vtiger_field where tabid=24"); + +//Added on 23-06-06 +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (29, $newfieldid, 'hour_format','vtiger_users',1,'116','hour_format','Calendar Hour Format',1,0,0,100,13,79,3,'I~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (29, $newfieldid, 'end_hour','vtiger_users',1,'116','end_hour','Day ends at',1,0,0,100,15,79,3,'I~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('29',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (29, $newfieldid, 'start_hour','vtiger_users',1,'116','start_hour','Day starts at',1,0,0,100,14,79,3,'I~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('29',$newfieldid); + +Execute("insert into vtiger_relatedlists values (".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",".getTabid("Potentials").",'get_opportunities',3,'Potentials',0)"); +Execute("insert into vtiger_relatedlists values(".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",9,'get_activities',4,'Activities',0)"); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (2, $newfieldid, 'campaignid','vtiger_potential',1,'58','campaignid','Campaign Source',1,0,0,100,12,1,1,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('2',$newfieldid); + +//Added on 28-06-06 +//Campaigns module added in Leads and Contacts RelatedList +Execute("insert into vtiger_relatedlists values(".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Campaigns").",'get_campaigns',6,'Campaigns',0)"); +Execute("insert into vtiger_relatedlists values(".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Campaigns").",'get_campaigns',11,'Campaigns',0)"); + +//Contact Name has been removed from Events Information +Execute("delete from vtiger_field where tabid=16 and fieldname='contact_id'"); + +//queries to resequence the fields +$fieldname=array('eventstatus','sendnotification','activitytype','location','createdtime','modifiedtime','taskpriority','notime','visibility'); +$tablename=array('vtiger_activity','vtiger_activity','vtiger_activity','vtiger_activity','vtiger_crmentity','vtiger_crmentity','vtiger_activity','vtiger_activity','vtiger_activity'); + +$sequence = array(10,11,12,13,14,15,16,17,18); +for($j = 0;$j < 9;$j++) +{ + Execute("update vtiger_field set sequence=".$sequence[$j]." where tablename='".$tablename[$j]."' && fieldname='".$fieldname[$j]."' and tabid=16"); +} + +//Campaign has been removed from field table +Execute("delete from vtiger_field where tabid=7 and fieldname='campaignid'"); +Execute("delete from vtiger_field where tabid=4 and fieldname='campaignid'"); + +//Query added to have Calendar under Marketing and Support +$conn->query("insert into vtiger_parenttabrel values (2,17,7)"); +$conn->query("insert into vtiger_parenttabrel values (4,17,9)"); + + + +//Added on 02-08-2006 ie., 2nd August 2006 + +//column added for proxy server settings +Execute("alter table vtiger_systems add column server_port int(19) default NULL after server"); + +//type changed to support decimal places +Execute("alter table vtiger_campaign change expectedrevenue expectedrevenue decimal(11,3)"); +Execute("alter table vtiger_campaign change budgetcost budgetcost decimal(11,3)"); +Execute("alter table vtiger_campaign change actualcost actualcost decimal(11,3)"); +Execute("alter table vtiger_campaign change expectedroi expectedroi decimal(11,3)"); +Execute("alter table vtiger_campaign change actualroi actualroi decimal(11,3)"); + +//homeorder value modified to get graph in homepage +Execute("update vtiger_users set homeorder='ALVT,PLVT,QLTQ,CVLVT,HLT,OLV,GRT,OLTSO,ILTI,MNL,HDB'"); + +//Removed activities from product related list +Execute("delete from vtiger_relatedlists where tabid = 14 and related_tabid=9"); +Execute("insert into vtiger_relatedlists values(".$conn->getUniqueID('vtiger_relatedlists').",".getTabid("HelpDesk").",9,'get_history',4,'Activity History',0)"); + +//Assigned to field for Events made Optional +Execute("update vtiger_field set typeofdata='V~M' where columnname='smownerid' and tabid=16 and fieldname='assigned_user_id'"); + +//Query added to have Notes under Marketing and Support --Jeri -- 04-06-06 +Execute("insert into vtiger_parenttabrel values (2,8,8)"); + + +//Update Query for quickcreate sequence of Campaign & Ticket -- Added by Ahmed -- 11-07-2006 +Execute("update vtiger_field set quickcreatesequence='3' where fieldname='filename' and tabid=13"); +Execute("update vtiger_field set quickcreatesequence='4' where fieldname='ticketpriorities' and tabid=13"); +Execute("update vtiger_field set quickcreatesequence='3' where fieldname='campaigntype' and tabid=26"); +Execute("update vtiger_field set quickcreatesequence='6' where fieldname='campaignstatus' and tabid=26"); +Execute("update vtiger_field set quickcreatesequence='2' where fieldname='closingdate' and tabid=26"); + + +//Added for Tax and Inventory - Product details handling + +Execute("CREATE TABLE vtiger_inventoryproductrel (id int(19) NOT NULL, productid int(19) NOT NULL, sequence_no int(4) NOT NULL default 1, quantity int(19) default NULL, listprice decimal(11,3) default NULL, discount_percent decimal(7,3) default NULL, discount_amount decimal(11,3) default NULL, comment varchar(100) default NULL, KEY inventoryproductrel_id_idx (id), KEY inventoryproductrel_productid_idx (productid) ) ENGINE=InnoDB"); + +//Execute("alter table vtiger_inventorytaxinfo add column deleted int(1) default 0"); + +Execute("CREATE TABLE vtiger_shippingtaxinfo ( taxid int(3) NOT NULL, taxname varchar(50) default NULL, taxlabel varchar(50) default NULL, percentage decimal(7,3) default NULL, deleted int(1) default '0', PRIMARY KEY (taxid), KEY shippingtaxinfo_taxname_idx (taxname) ) ENGINE=InnoDB"); + +Execute("CREATE TABLE vtiger_inventoryshippingrel (id int(19) NOT NULL, KEY inventoryishippingrel_id_idx (id) ) ENGINE=InnoDB"); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (21, $newfieldid, 'taxtype','vtiger_purchaseorder',1,'15','hdnTaxType','Tax Type',1,0,0,100,14,57,3,'V~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('21',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (21, $newfieldid, 'discount_percent','vtiger_purchaseorder',1,'1','hdnDiscountPercent','Discount Percent',1,0,0,100,14,57,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('21',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (21, $newfieldid, 'discount_amount','vtiger_purchaseorder',1,'1','hdnDiscountAmount','Discount Amount',1,0,0,100,14,57,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('21',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (21, $newfieldid, 's_h_amount','vtiger_purchaseorder',1,'1','hdnS_H_Amount','S&H Amount',1,0,0,100,14,57,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('21',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (22, $newfieldid, 'taxtype','vtiger_salesorder',1,'15','hdnTaxType','Tax Type',1,0,0,100,15,63,3,'V~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('22',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (22, $newfieldid, 'discount_percent','vtiger_salesorder',1,'1','hdnDiscountPercent','Discount Percent',1,0,0,100,15,63,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('22',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (22, $newfieldid, 'discount_amount','vtiger_salesorder',1,'1','hdnDiscountAmount','Discount Amount',1,0,0,100,15,63,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('22',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (22, $newfieldid, 's_h_amount','vtiger_salesorder',1,'1','hdnS_H_Amount','S&H Amount',1,0,0,100,15,63,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('22',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (20, $newfieldid, 'taxtype','vtiger_quotes',1,'15','hdnTaxType','Tax Type',1,0,0,100,14,51,3,'V~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('20',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (20, $newfieldid, 'discount_percent','vtiger_quotes',1,'1','hdnDiscountPercent','Discount Percent',1,0,0,100,14,51,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('20',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (20, $newfieldid, 'discount_amount','vtiger_quotes',1,'1','hdnDiscountAmount','Discount Amount',1,0,0,100,14,51,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('20',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (20, $newfieldid, 's_h_amount','vtiger_quotes',1,'1','hdnS_H_Amount','S&H Amount',1,0,0,100,14,51,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('20',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (23, $newfieldid, 'taxtype','vtiger_invoice',1,'15','hdnTaxType','Tax Type',1,0,0,100,13,69,3,'V~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('23',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (23, $newfieldid, 'discount_percent','vtiger_invoice',1,'1','hdnDiscountPercent','Discount Percent',1,0,0,100,13,69,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('23',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (23, $newfieldid, 'discount_amount','vtiger_invoice',1,'1','hdnDiscountAmount','Discount Amount',1,0,0,100,13,69,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('23',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (23, $newfieldid, 's_h_amount','vtiger_invoice',1,'1','hdnS_H_Amount','S&H Amount',1,0,0,100,14,57,3,'N~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('23',$newfieldid); + + +Execute("alter table vtiger_purchaseorder add column taxtype varchar(25) default NULL after subtotal"); +Execute("alter table vtiger_purchaseorder add column discount_percent decimal(11,3) default NULL after taxtype"); +Execute("alter table vtiger_purchaseorder add column discount_amount decimal(11,3) default NULL after discount_percent"); +Execute("alter table vtiger_purchaseorder add column s_h_amount decimal(11,3) default NULL after discount_amount"); + +Execute("alter table vtiger_salesorder add column taxtype varchar(25) default NULL after subtotal"); +Execute("alter table vtiger_salesorder add column discount_percent decimal(11,3) default NULL after taxtype"); +Execute("alter table vtiger_salesorder add column discount_amount decimal(11,3) default NULL after discount_percent"); +Execute("alter table vtiger_salesorder add column s_h_amount decimal(11,3) default NULL after discount_amount"); + +Execute("alter table vtiger_quotes add column taxtype varchar(25) default NULL after total"); +Execute("alter table vtiger_quotes add column discount_percent decimal(11,3) default NULL after taxtype"); +Execute("alter table vtiger_quotes add column discount_amount decimal(11,3) default NULL after discount_percent"); +Execute("alter table vtiger_quotes add column s_h_amount decimal(11,3) default NULL after discount_amount"); + +Execute("alter table vtiger_invoice add column taxtype varchar(25) default NULL after total"); +Execute("alter table vtiger_invoice add column discount_percent decimal(11,3) default NULL after taxtype"); +Execute("alter table vtiger_invoice add column discount_amount decimal(11,3) default NULL after discount_percent"); +Execute("alter table vtiger_invoice add column s_h_amount decimal(11,3) default NULL after discount_amount"); + + +//Update Query to Match Notes List View Header Fieldnames with Custom View combo values +Execute("update vtiger_field set fieldlabel='Title' where fieldlabel='Subject' and tabid=8"); +Execute("update vtiger_field set fieldlabel='File' where fieldlabel='Attachment' and tabid=8"); + + +//Update Query to change the UI type of Rating Field in Accounts Module from 1 to 15 to display combo list +Execute("update vtiger_field set uitype=15 where tabid=6 and fieldname='rating'"); + + +//Insert and Update Query for new block addition for Campaigns Module +Execute("update vtiger_blocks set blocklabel='LBL_EXPECTATIONS_AND_ACTUALS' where tabid=26 and blockid=78"); +Execute("insert into vtiger_blocks values (82,26,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0)"); + + +//Update Query for rearrangements of fields in Campaigns Module's Detail/Edit/Create View +Execute("update vtiger_field set sequence=1 where tabid=26 and columnname='campaignname' and fieldname='campaignname'"); +Execute("update vtiger_field set sequence=2 where tabid=26 and columnname='campaignstatus' and fieldname='campaignstatus'"); +Execute("update vtiger_field set sequence=3 where tabid=26 and columnname='smownerid' and fieldname='assigned_user_id'"); +Execute("update vtiger_field set sequence=4 where tabid=26 and columnname='product_id' and fieldname='product_id'"); +Execute("update vtiger_field set sequence=5 where tabid=26 and columnname='campaigntype' and fieldname='campaigntype'"); +Execute("update vtiger_field set sequence=6 where tabid=26 and columnname='closingdate' and fieldname='closingdate'"); +Execute("update vtiger_field set sequence=7 where tabid=26 and columnname='targetaudience' and fieldname='targetaudience'"); +Execute("update vtiger_field set sequence=8 where tabid=26 and columnname='targetsize' and fieldname='targetsize'"); +Execute("update vtiger_field set sequence=9 where tabid=26 and columnname='sponsor' and fieldname='sponsor'"); +Execute("update vtiger_field set sequence=10 where tabid=26 and columnname='numsent' and fieldname='numsent'"); +Execute("update vtiger_field set sequence=11 where tabid=26 and columnname='createdtime' and fieldname='createdtime'"); +Execute("update vtiger_field set sequence=12 where tabid=26 and columnname='modifiedtime' and fieldname='modifiedtime'"); + +Execute("update vtiger_field set sequence=1, block=78 where tabid=26 and columnname='budgetcost' and fieldname='budgetcost'"); +Execute("update vtiger_field set sequence=2, block=78 where tabid=26 and columnname='actualcost' and fieldname='actualcost'"); +Execute("update vtiger_field set sequence=3, block=78 where tabid=26 and columnname='expectedresponse' and fieldname='expectedresponse'"); +Execute("update vtiger_field set sequence=4, block=78 where tabid=26 and columnname='expectedrevenue' and fieldname='expectedrevenue'"); +Execute("update vtiger_field set sequence=5, block=78 where tabid=26 and columnname='expectedsalescount' and fieldname='expectedsalescount'"); +Execute("update vtiger_field set sequence=6, block=78 where tabid=26 and columnname='actualsalescount' and fieldname='actualsalescount'"); +Execute("update vtiger_field set sequence=7, block=78 where tabid=26 and columnname='expectedresponsecount' and fieldname='expectedresponsecount'"); +Execute("update vtiger_field set sequence=8, block=78 where tabid=26 and columnname='actualresponsecount' and fieldname='actualresponsecount'"); +Execute("update vtiger_field set sequence=9, block=78 where tabid=26 and columnname='expectedroi' and fieldname='expectedroi'"); +Execute("update vtiger_field set sequence=10, block=78 where tabid=26 and columnname='actualroi' and fieldname='actualroi'"); + + + +//Update query to set the fieldname in user detail/edit/create view +Execute("update vtiger_field set sequence=1 where tabid=29 and columnname='user_name' and fieldname='user_name' and block=79"); +Execute("update vtiger_field set sequence=2 where tabid=29 and columnname='is_admin' and fieldname='is_admin' and block=79"); +Execute("update vtiger_field set sequence=3 where tabid=29 and columnname='user_password' and fieldname='user_password' and block=79"); +Execute("update vtiger_field set sequence=4 where tabid=29 and columnname='email1' and fieldname='email1' and block=79"); +Execute("update vtiger_field set sequence=5 where tabid=29 and columnname='confirm_password' and fieldname='confirm_password' and block=79"); +Execute("update vtiger_field set sequence=6 where tabid=29 and columnname='status' and fieldname='status' and block=79"); +Execute("update vtiger_field set sequence=7 where tabid=29 and columnname='first_name' and fieldname='first_name' and block=79"); +Execute("update vtiger_field set sequence=8 where tabid=29 and columnname='currency_id' and fieldname='currency_id' and block=79"); +Execute("update vtiger_field set sequence=9 where tabid=29 and columnname='last_name' and fieldname='last_name' and block=79"); +Execute("update vtiger_field set sequence=10 where tabid=29 and columnname='lead_view' and fieldname='lead_view' and block=79"); +Execute("update vtiger_field set sequence=11 where tabid=29 and columnname='roleid' and fieldname='roleid' and block=79"); +Execute("update vtiger_field set sequence=12 where tabid=29 and columnname='activity_view' and fieldname='activity_view' and block=79"); +Execute("update vtiger_field set sequence=13 where tabid=29 and columnname='hour_format' and fieldname='hour_format' and block=79"); +Execute("update vtiger_field set sequence=14 where tabid=29 and columnname='start_hour' and fieldname='start_hour' and block=79"); +Execute("update vtiger_field set sequence=15 where tabid=29 and columnname='end_hour' and fieldname='end_hour' and block=79"); + +Execute("update vtiger_field set sequence=1 where tabid=29 and columnname='title' and fieldname='title' and block=80"); +Execute("update vtiger_field set sequence=2 where tabid=29 and columnname='phone_fax' and fieldname='phone_fax' and block=80"); +Execute("update vtiger_field set sequence=3 where tabid=29 and columnname='department' and fieldname='department' and block=80"); +Execute("update vtiger_field set sequence=4 where tabid=29 and columnname='email2' and fieldname='email2' and block=80"); +Execute("update vtiger_field set sequence=5 where tabid=29 and columnname='phone_work' and fieldname='phone_work' and block=80"); +Execute("update vtiger_field set sequence=6 where tabid=29 and columnname='yahoo_id' and fieldname='yahoo_id' and block=80"); +Execute("update vtiger_field set sequence=7 where tabid=29 and columnname='phone_mobile' and fieldname='phone_mobile' and block=80"); +Execute("update vtiger_field set sequence=8 where tabid=29 and columnname='reports_to_id' and fieldname='reports_to_id' and block=80"); +Execute("update vtiger_field set sequence=9 where tabid=29 and columnname='phone_home' and fieldname='phone_home' and block=80"); +Execute("update vtiger_field set sequence=10 where tabid=29 and columnname='imagename' and fieldname='imagename' and block=80"); +Execute("update vtiger_field set sequence=11 where tabid=29 and columnname='phone_other' and fieldname='phone_other' and block=80"); +Execute("update vtiger_field set sequence=12 where tabid=29 and columnname='date_format' and fieldname='date_format' and block=80"); +Execute("update vtiger_field set sequence=13 where tabid=29 and columnname='signature' and fieldname='signature' and block=80"); +Execute("update vtiger_field set sequence=14 where tabid=29 and columnname='description' and fieldname='description' and block=80"); +Execute("update vtiger_field set sequence=15 where tabid=29 and columnname='tagcloud' and fieldname='tagcloud' and block=80"); + +Execute("update vtiger_field set sequence=1 where tabid=29 and columnname='address_street' and fieldname='address_street' and block=81"); +Execute("update vtiger_field set sequence=2 where tabid=29 and columnname='address_country' and fieldname='address_country' and block=81"); +Execute("update vtiger_field set sequence=3 where tabid=29 and columnname='address_city' and fieldname='address_city' and block=81"); +Execute("update vtiger_field set sequence=4 where tabid=29 and columnname='address_postalcode' and fieldname='address_postalcode' and block=81"); +Execute("update vtiger_field set sequence=5 where tabid=29 and columnname='address_state' and fieldname='address_state' and block=81"); + +//Added for Recurring events +Execute("alter table vtiger_recurringevents add column recurringfreq int(19) default NULL"); +Execute("alter table vtiger_recurringevents add column recurringinfo varchar(50) default NULL"); + + +//Update Query for changing the uitype for existing picklist entries making it non-editable +Execute("update vtiger_field set uitype=111 where fieldname in ('sales_stage','ticketstatus','taskstatus','eventstatus','faqstatus','quotestage','postatus','sostatus','invoicestatus')"); + + + + + + + + + + +//Inventory Tax handlings -- Starts + +//Added to populate the default Shipping & Hanlding tax informations +$shvatid = $conn->getUniqueID("vtiger_shippingtaxinfo"); +$shsalesid = $conn->getUniqueID("vtiger_shippingtaxinfo"); +$shserviceid = $conn->getUniqueID("vtiger_shippingtaxinfo"); + +$conn->query("insert into vtiger_shippingtaxinfo values($shvatid,'shtax".$shvatid."','VAT','4.50','0')"); +$conn->query("insert into vtiger_shippingtaxinfo values($shsalesid,'shtax".$shsalesid."','Sales','10.00','0')"); +$conn->query("insert into vtiger_shippingtaxinfo values($shserviceid,'shtax".$shserviceid."','Service','12.50','0')"); + +//After added these taxes we should add these taxes as columns in vtiger_inventoryshippingrel table +$conn->query("alter table vtiger_inventoryshippingrel add column shtax$shvatid decimal(7,3) default NULL"); +$conn->query("alter table vtiger_inventoryshippingrel add column shtax$shsalesid decimal(7,3) default NULL"); +$conn->query("alter table vtiger_inventoryshippingrel add column shtax$shserviceid decimal(7,3) default NULL"); + + +//Added to populate the Common tax which will be used to save the existing tax (percentage will be calculated based on the total tax amount retrieved from the entity tables of PO, SO, Quotes and Invoice) +$migratedtaxid = 1; +$migratedtaxid = $conn->getUniqueID("vtiger_inventorytaxinfo"); +$migrated_taxname = "tax$migratedtaxid"; +$conn->query("insert into vtiger_inventorytaxinfo values($migratedtaxid,'".$migrated_taxname."','Tax','0.00','0')"); + +//After added these taxes we should add these taxes as columns in vtiger_inventoryproductrel table +$conn->query("alter table vtiger_inventoryproductrel add column $migrated_taxname decimal(7,3) default NULL"); + +//Now we should create tax for each and every value given in picklist taxclass +$taxres = $conn->query("select * from vtiger_taxclass"); +$taxcount = $conn->num_rows($taxres); +for($i=0;$i<$taxcount;$i++) +{ + $taxlabel = $conn->query_result($taxres,$i,'taxclass'); + + $newtaxid = $conn->getUniqueID("vtiger_inventorytaxinfo"); + $addtaxres = $conn->query("alter table vtiger_inventoryproductrel add column tax$newtaxid decimal(7,3) default NULL"); + if($addtaxres) + $conn->query("insert into vtiger_inventorytaxinfo values($newtaxid,'tax".$newtaxid."','".$taxlabel."','0.00','0')"); +} +//Finished the add tax process based on the available tax classes + +//To save Product - Tax relationship +//get Product - taxclass and add entry in vtiger_producttaxrel for this product - tax relationship +$productres = $conn->query("select productid, taxclass from vtiger_products"); +$productcount = $conn->num_rows($productres); +for($i=0;$i<$productcount;$i++) +{ + $productid = $conn->query_result($productres,$i,'productid'); + $taxlabel = $conn->query_result($productres,$i,'taxclass'); + + $taxres = $conn->query("select taxid from vtiger_inventorytaxinfo where taxlabel='".addslashes($taxlabel)."'"); + $taxid = $conn->query_result($taxres,0,'taxid'); + + $taxquery = "insert into vtiger_producttaxrel values($productid, \"$taxid\", '0.00')"; + //Execute($taxquery); + $conn->query($taxquery); +} + + + + + +//Retrieve values from poproductrel, soproductrel, quotesproductrel, invoiceproductrel and store in vtiger_inventoryproductrel + +$inventory_tables = Array( + 'vtiger_poproductrel'=>'purchaseorderid', + 'vtiger_soproductrel'=>'salesorderid', + 'vtiger_quotesproductrel'=>'quoteid', + 'vtiger_invoiceproductrel'=>'invoiceid' + ); + +foreach($inventory_tables as $tablename => $idname) +{ + $res = $conn->query("select * from $tablename order by $idname"); + $count = $conn->num_rows($res); + + $id = $oldid = 0; + $seqno = 0; + + for($i=0;$i<$count;$i++) + { + $oldid = $id; + $id = $conn->query_result($res,$i,$idname); + + //for every new PO/SO/Quotes/Invoice entity we should set the sequence start value as 1 + if($id != $oldid) + $seqno = 1; + + $productid = $conn->query_result($res,$i,'productid'); + $quantity = $conn->query_result($res,$i,'quantity'); + $listprice = $conn->query_result($res,$i,'listprice'); + + $query1 = "insert into vtiger_inventoryproductrel(id,productid,sequence_no,quantity,listprice) values($id, $productid,$seqno, $quantity, $listprice)"; + Execute($query1); + $seqno++; + } +} + + +//Now for each and every PO, SO, Quotes and Invoice we should get the total, discount, tax +$inventory_tables = Array( + 'vtiger_purchaseorder'=>'purchaseorderid', + 'vtiger_salesorder'=>'salesorderid', + 'vtiger_quotes'=>'quoteid', + 'vtiger_invoice'=>'invoiceid' + ); + +foreach($inventory_tables as $tablename => $idname) +{ + $res2 = $conn->query("select * from $tablename order by $idname"); + $entitycount = $conn->num_rows($res2); + + for($i=0;$i<$entitycount;$i++) + { + $idval = $conn->query_result($res2,$i,$idname); + + //$res3 = $conn->query("select * from $tablename where $idname=$idval"); + $subtotal = $conn->query_result($res2,$i,'subtotal'); + $taxamount = $conn->query_result($res2,$i,'salestax'); + + //Now based on the inventory tax total - calculate the percentage + $taxpercent = '0.00'; + if($taxamount > 0 && $subtotal >0) + { + $taxpercent = $taxamount*100/$subtotal; + } + + //update the taxtype as group + $query2 = "update $tablename set taxtype='group'"; + Execute($query2); + + //update the calculated percentage for the entity ie., PO/SO/Quotes/Invoice + $query3 = "update vtiger_inventoryproductrel set $migrated_taxname='".$taxpercent."' where id=$idval"; + Execute($query3); + } +} + + +//we have retrieve and saved all the values, so we can delete the unwanted tables +Execute("drop table vtiger_poproductrel"); +Execute("drop table vtiger_soproductrel"); +Execute("drop table vtiger_quotesproductrel"); +Execute("drop table vtiger_invoiceproductrel"); + +//Inventory Tax handlings -- Ends + + +//Add Inventory History tracking tables ie.,PO Status, SO Status, Quote Stage and Invoice Status tables +//PO Status +Execute("CREATE TABLE vtiger_postatushistory ( historyid int(19) NOT NULL auto_increment, purchaseorderid int(19) NOT NULL, vendorname varchar(100) default NULL, total decimal(10,0) default NULL, postatus varchar(200) default NULL, lastmodified datetime default NULL, PRIMARY KEY (historyid), KEY postatushistory_purchaseorderid_idx (purchaseorderid), CONSTRAINT fk_1_vtiger_postatushistory FOREIGN KEY (purchaseorderid) REFERENCES vtiger_purchaseorder (purchaseorderid) ON DELETE CASCADE ) ENGINE=InnoDB"); + +//SO Status +Execute("CREATE TABLE vtiger_sostatushistory (historyid int(19) NOT NULL auto_increment, salesorderid int(19) NOT NULL, accountname varchar(100) default NULL, total decimal(10,0) default NULL, sostatus varchar(200) default NULL, lastmodified datetime default NULL, PRIMARY KEY (historyid), KEY sostatushistory_salesorderid_idx (salesorderid), CONSTRAINT fk_1_vtiger_sostatushistory FOREIGN KEY (salesorderid) REFERENCES vtiger_salesorder (salesorderid) ON DELETE CASCADE ) ENGINE=InnoDB"); + +//Quote Stage +Execute("CREATE TABLE vtiger_quotestagehistory ( historyid int(19) NOT NULL auto_increment, quoteid int(19) NOT NULL, accountname varchar(100) default NULL, total decimal(10,0) default NULL, quotestage varchar(200) default NULL, lastmodified datetime default NULL, PRIMARY KEY (historyid), KEY quotestagehistory_quoteid_idx (quoteid), CONSTRAINT fk_1_vtiger_quotestagehistory FOREIGN KEY (quoteid) REFERENCES vtiger_quotes (quoteid) ON DELETE CASCADE) ENGINE=InnoDB"); + +//Invoice Status +Execute("CREATE TABLE vtiger_invoicestatushistory ( historyid int(19) NOT NULL auto_increment, invoiceid int(19) NOT NULL, accountname varchar(100) default NULL, total decimal(10,0) default NULL, invoicestatus varchar(200) default NULL, lastmodified datetime default NULL, PRIMARY KEY (historyid), KEY invoicestatushistory_invoiceid_idx (invoiceid), CONSTRAINT fk_1_vtiger_invoicestatushistory FOREIGN KEY (invoiceid) REFERENCES vtiger_invoice (invoiceid) ON DELETE CASCADE) ENGINE=InnoDB"); + + +//User image handling +Execute("insert into vtiger_blocks values (83,29,'LBL_USER_IMAGE_INFORMATION',4,0,0,0,0,0)"); +Execute("update vtiger_field set block=83 where tabid=29 and fieldname='imagename' and columnname='imagename'"); + +Execute("update vtiger_field set tablename='vtiger_products' where fieldname='taxclass' && tabid=14"); + +Execute("update vtiger_field set info_type='BAS' where tabid=4 and fieldname='email' and columnname='email'"); + +Execute("update vtiger_field set info_type='ADV' where tabid=4 and fieldname='otherphone' and columnname='otherphone'"); + +Execute("CREATE TABLE vtiger_salesmanattachmentsrel ( smid int(19) NOT NULL default '0', attachmentsid int(19) NOT NULL default '0', PRIMARY KEY (smid, attachmentsid), KEY salesmanattachmentsrel_smid_idx (smid), KEY salesmanattachmentsrel_attachmentsid_idx (attachmentsid), CONSTRAINT fk_1_vtiger_salesmanattachmentsrel FOREIGN KEY (smid) REFERENCES vtiger_users (id), CONSTRAINT fk_2_vtiger_salesmanattachmentsrel FOREIGN KEY (attachmentsid) REFERENCES vtiger_attachments (attachmentsid) ON DELETE CASCADE) ENGINE=InnoDB"); + + +//Changes made for Activity merge with Calendar - Starts +Execute("alter table vtiger_activity add column time_end varchar(50) default NULL after time_start"); + +Execute("delete from vtiger_tab where tabid=17"); + +Execute("update vtiger_tab set name='Calendar',tablabel='Calendar' where tabid=9"); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (9, $newfieldid, 'time_end','vtiger_activity', 1,'2','time_end','End Time',1,0,0,100,6,19,3,'T~O',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('9',$newfieldid); + +$newfieldid = $conn->getUniqueID("vtiger_field"); +$query = "insert into vtiger_field values (16, $newfieldid, 'time_end','vtiger_activity', 1,'2','time_end','End Time',1,0,0,100,6,41,3,'T~M',1,null,'BAS')"; +Execute($query); +populateFieldForSecurity('16',$newfieldid); + +Execute("delete from vtiger_profile2tab where tabid=17"); + +Execute("delete from vtiger_org_share_action2tab where tabid=17"); + +Execute("delete from vtiger_def_org_share where tabid=17"); + +Execute("delete from vtiger_parenttabrel where tabid=17"); +//Changes made for Activity merge with Calendar - Ends + +//audit trial table +Execute("create table vtiger_audit_trial(auditid int(19) NOT NULL, userid int(19) default NULL, module varchar(255) default NULL, action varchar(255) default NULL, recordid varchar(20) default NULL, actiondate datetime default NULL, PRIMARY KEY (auditid)) ENGINE=InnoDB"); + +//Added after 5 rc release +Execute("alter table vtiger_account modify siccode varchar(50)"); +Execute("update vtiger_field set typeofdata='V~O' where fieldname='siccode' and columnname='siccode' and tabid=6"); + +//changes made for CustomView and Reports - Activities changed to Calendar -- Starts +//Added to change the entitytype from Activities to Calendar for customview +Execute("update vtiger_crmentity set setype='Calendar' where setype='Activities'"); +Execute("update vtiger_customview set entitytype='Calendar' where entitytype='Activities'"); + +//Added to change the primarymodule from Activities to Calendar for Reports +Execute("update vtiger_reportmodules set primarymodule='Calendar' where primarymodule='Activities'"); +Execute("update vtiger_reportmodules set primarymodule='PurchaseOrder' where primarymodule='Orders'"); +Execute("update vtiger_reportmodules set secondarymodules='PurchaseOrder' where secondarymodules='Orders'"); + +//we should change the Activities to Calendar in columnname values in customview and report related tables +$prefix = "vtiger_"; +$change_cols_array = Array( + "cvcolumnlist"=>"columnname", + "cvstdfilter"=>"columnname", + "cvadvfilter"=>"columnname", + "selectcolumn"=>"columnname", + "relcriteria"=>"columnname", + "reportsortcol"=>"columnname", + "reportdatefilter"=>"datecolumnname", + "reportsummary"=>"columnname", + ); + +//This is to change Activities to Calendar +foreach($change_cols_array as $tablename => $columnname) +{ + $result = $conn->query("select $columnname from $prefix$tablename where $columnname like \"%Activities%\""); + + while($row = $conn->fetch_row($result)) + { + if($row[$columnname] !='' && $row[$columnname] != 'none') + { + Execute("update $prefix$tablename set $columnname=\"".str_replace("Activities","Calendar",$row[$columnname])."\" where $columnname=\"$row[$columnname]\""); + } + } +} + +//This is to change the Orders to PurchaseOrder +foreach($change_cols_array as $tablename => $columnname) +{ + $result1 = $conn->query("select $columnname from $prefix$tablename where $columnname like \"%Orders%\""); + + while($row1 = $conn->fetch_row($result1)) + { + if($row1[$columnname] !='' && $row1[$columnname] != 'none') + { + Execute("update $prefix$tablename set $columnname=\"".str_replace("Orders","PurchaseOrder",$row1[$columnname])."\" where $columnname=\"$row1[$columnname]\""); + } + } +} +//we have to change the table name from activity to crmentity for customview activity description +Execute('update vtiger_cvcolumnlist set columnname="vtiger_crmentity:description:description:Calendar_Description:V" where columnname="vtiger_activity:description:description:Calendar_Description:V"'); +//we have to change the table name (alias) from activity to crmentiryCalendar for reports activity description +Execute('update vtiger_selectcolumn set columnname="vtiger_crmentityCalendar:description:Calendar_Description:description:V" where columnname="vtiger_activity:description:Calendar_Description:description:V"'); +//changes made for CustomView and Reports - Activities changed to Calendar -- Ends + +Execute("update vtiger_field set uitype = 16 where tabid=2 and uitype=111 and columnname='sales_stage'"); + +Execute("update vtiger_field set quickcreate=1,quickcreatesequence=null where fieldname='duration_hours' and tabid=16"); + +Execute("update vtiger_field set quickcreate=0,quickcreatesequence=5 where fieldname='due_date' and tabid=16"); + +//we have to add id, sortorderid and presence in all existing custom field pick list tables. +$cf_picklist_res = $conn->query("select fieldname from vtiger_field where uitype=15 and fieldname like 'cf_%'"); +$noofPicklists = $conn->num_rows($cf_picklist_res); +for($i=0;$i<$noofPicklists;$i++) +{ + $fieldname = $conn->query_result($cf_picklist_res,$i,'fieldname'); + + $tablename = "vtiger_".$fieldname; + $idname = $fieldname."id"; + + $alterquery = "alter table $tablename add column $idname int(19) auto_increment PRIMARY KEY FIRST, add column sortorderid int(19) default 0 NOT NULL, add column presence int(1) default 1 NOT NULL"; + Execute($alterquery); +} + +$conn->query("alter table vtiger_organizationdetails drop primary key"); +Execute("alter table vtiger_organizationdetails change column organizationame organizationname varchar(60) NOT NULL"); +Execute("alter table vtiger_organizationdetails ADD PRIMARY KEY (organizationname)"); + +//Activity related changes +Execute('update vtiger_field set typeofdata="D~M~OTH~GE~date_start~Start Date & Time", uitype=23 where fieldname="due_date" and tabid=16'); +Execute('update vtiger_field set uitype=53 where tabid=16 and fieldname="assigned_user_id"'); + +Execute('update vtiger_field set typeofdata="D~M~OTH~GE~date_start~Start Date & Time", uitype=23 where fieldname="due_date" and tabid=9'); +Execute('update vtiger_field set uitype=53 where tabid=9 and fieldname="assigned_user_id"'); + +Execute("alter table vtiger_activity change column subject subject varchar(100) NOT NULL"); +Execute("alter table vtiger_activity change column activitytype activitytype varchar(50) NOT NULL"); +Execute("alter table vtiger_activity change column date_start date_start date NOT NULL"); +Execute("alter table vtiger_activity change column time_start time_start varchar(50) default NULL"); +//Execute("alter table vtiger_activity change column visibility visibility varchar(50) NOT NULL default 'all'"); + +Execute("delete from vtiger_field where tabid=14 and fieldname='currency'"); + +//Product related changes +Execute('update vtiger_field set typeofdata="D~O~OTH~GE~sales_start_date~Sales Start Date" where tabid=14 and fieldname="sales_end_date"'); +Execute('update vtiger_field set typeofdata="D~O~OTH~GE~start_date~Start Date" where tabid=14 and fieldname="expiry_date"'); + +//changes related to Incoming mail server settings +Execute("alter table vtiger_mail_accounts drop column showbody"); + +//change the Account relatedlist Activity label from Acivities to Activities +Execute("update vtiger_relatedlists set label='Activities' where tabid=6 and relation_id=3"); + +//change the fieldname from title to notes_title for notes and update in columnlist also +Execute("update vtiger_field set fieldname='notes_title' where tabid=8 and fieldname='title'"); +Execute('update vtiger_cvcolumnlist set columnname="vtiger_notes:title:notes_title:Notes_Title:V" where columnname="vtiger_notes:title:title:Notes_Title:V"'); + +//change the sequence of Billing and Shipping address details for Inventory modules +Execute("update vtiger_field set sequence=5 where tabid in (20,21,22,23) and fieldname='bill_city'"); +Execute("update vtiger_field set sequence=6 where tabid in (20,21,22,23) and fieldname='ship_city'"); +Execute("update vtiger_field set sequence=7 where tabid in (20,21,22,23) and fieldname='bill_state'"); +Execute("update vtiger_field set sequence=8 where tabid in (20,21,22,23) and fieldname='ship_state'"); +Execute("update vtiger_field set sequence=9 where tabid in (20,21,22,23) and fieldname='bill_code'"); +Execute("update vtiger_field set sequence=10 where tabid in (20,21,22,23) and fieldname='ship_code'"); +Execute("update vtiger_field set sequence=11 where tabid in (20,21,22,23) and fieldname='bill_country'"); +Execute("update vtiger_field set sequence=12 where tabid in (20,21,22,23) and fieldname='ship_country'"); + +//for vtiger_campaignleadrel table +Execute("alter table vtiger_campaignleadrel DROP PRIMARY KEY"); +Execute("alter table vtiger_campaignleadrel ADD PRIMARY KEY (campaignid,leadid)"); + +//for vtiger_campaigncontrel table +Execute("alter table vtiger_campaigncontrel DROP PRIMARY KEY"); +Execute("alter table vtiger_campaigncontrel ADD PRIMARY KEY (campaignid,contactid)"); + +//for vtiger_seactivityrel table +Execute("alter table vtiger_seactivityrel DROP PRIMARY KEY"); +Execute("alter table vtiger_seactivityrel ADD PRIMARY KEY (crmid,activityid)"); + +//change the block for vendor address details +Execute("update vtiger_field set fieldname='street' where tabid=18 and columnname='street'"); +Execute("update vtiger_field set block=46 where tabid=18 and fieldname in ('city','country','pobox','postalcode','state','street')"); + +//change the calendar sharing access to private +Execute("update vtiger_def_org_share set permission=3 where tabid=9"); +//Now sharing access is not available for Emails +Execute("delete from vtiger_def_org_share where tabid=10"); + +//we have to delete the entry from datashare_relatedmodules (Settings -> Sharing Access -> Add Privileges) +Execute("delete from vtiger_datashare_relatedmodules where tabid=10"); +Execute("delete from vtiger_datashare_relatedmodules where relatedto_tabid=10"); + + +//change the share_action_name in vtiger_org_share_action_mapping table for entry Public:Read,Create/Edit +Execute('update vtiger_org_share_action_mapping set share_action_name="Public: Read, Create/Edit" where share_action_name="Public:Read,Create/Edit"'); + +//delete the entries from vtiger_profile2standardpermissions table for Emails +Execute("delete from vtiger_profile2standardpermissions where tabid=10"); + +//delete the tagcloud entry from users +Execute("delete from vtiger_field where tabid=29 and fieldname='tagcloud'"); +Execute("alter table vtiger_users drop column tagcloud"); + +//we have missed to add the Received Shipment in postatus table +$sortorderid = $conn->query_result($conn->query("select max(sortorderid) as id from vtiger_postatus"),0,'id')+1; +Execute("insert into vtiger_postatus values('','Received Shipment',$sortorderid,1)"); +Execute("alter table vtiger_attachments add index attachments_description_name_type_attachmentsid_idx (`description`,`type`,`attachmentsid`)"); + +//Added after 5.0 GA release + +//In 4.2.3 we have assigned to group option only for Leads, HelpDesk and Activies and default None can be assigned. Now we will assign the unassigned entities to current user +Execute("update vtiger_crmentity set smownerid=1 where smownerid=0 and setype not in ('Leads','HelpDesk','Calendar')"); + +//CALCULATE Activity End Time (time_end) +//we have to calculate activity end time (time_end) based on start time (time_start) and duration (duration_hours, duration_minutes) +$sql = "select * from vtiger_activity"; +$result = $conn->query($sql); +$num_rows = $conn->num_rows($result); +for($i=0;$i<$num_rows;$i++) +{ + //First we have to retrieve the time_start, duration_hours and duration_minutes and form as a date with time + $activityid = $conn->query_result($result,$i,'activityid'); + $date_start = $conn->query_result($result,$i,'date_start'); + $time_start = $conn->query_result($result,$i,'time_start'); + $duration_hours = $conn->query_result($result,$i,'duration_hours'); + $duration_minutes = $conn->query_result($result,$i,'duration_minutes'); + + if($duration_hours != '' && $duration_minutes != '') + { + $date_details = explode("-",$date_start); + $start_year = $date_details[0]; + $start_month = $date_details[1]; + $start_date = $date_details[2]; + + $start_details = explode(":",$time_start); + $start_hour = $start_details[0]; + $start_minutes = $start_details[1]; + + $full_duration = "$duration_hours:$duration_minutes:00"; + + $start = date("Y-m-d H:i:s",mktime($start_hour, $start_minutes, 0, $start_month, $start_date, $start_year)); + $end = date("Y-m-d H:i:s",mktime($start_hour+$duration_hours, $start_minutes+$duration_minutes, 0, $start_month, $start_date, $start_year)); + + $end_details = explode(" ",$end); + $due_date = $end_details[0]; + + $end_time_details = explode(":",$end_details[1]); + $time_end = $end_time_details[0].":".$end_time_details[1]; + + $update_query = "update vtiger_activity set due_date=\"$due_date\", time_end=\"$time_end\" where activityid=$activityid"; + + $conn->query($update_query); + } +} + +//Added after 5.0.1 +//we have to delete the entries from customview and report related tables for deleted customfields +include("modules/Migration/deleteCustomFields.php"); + + + + +//Finally add vtiger_ prefix for all the entries in 'tablename' column in field table - 2nd August 2006 +$field_res = $conn->query("select fieldid, tablename from vtiger_field"); +for($field_count=0;$field_count<$conn->num_rows($field_res);$field_count++) +{ + //get the tablename + $tablename = $conn->query_result($field_res,$field_count,'tablename'); + + //check whether the table name has the prefix vtiger_ + if(substr($tablename, 0, 7) != 'vtiger_') + { + $tablename = "vtiger_$tablename"; + + //Now update the tablename + $fieldid = $conn->query_result($field_res,$field_count,'fieldid'); + Execute("update vtiger_field set tablename=\"$tablename\" where fieldid=$fieldid"); + } +} + + +$migrationlog->debug("\n\nDB Changes from 4.2.x to 5.0 GA -------- Ends \n\n"); + + +//Added to get the conversion rate and update for all records +?> + +query($query); + + $query_count++; + if(is_object($status)) + { + echo ' + + '.get_class($status).' + S + '.$query.' + '; + $success_query_array[$success_query_count++] = $query; + $migrationlog->debug("Query Success ==> $query"); + } + else + { + echo ' + + '.$status.' + F + '.$query.' + '; + $failure_query_array[$failure_query_count++] = $query; + $migrationlog->debug("Query Failed ==> $query \n Error is ==> [".$conn->database->ErrorNo()."]".$conn->database->ErrorMsg()); + //$migrationlog->debug("Error is ==> ".$conn->ErrorMsg()); + } +} + +//Added on 23-12-2005 which is used to populate the vtiger_profile2field and vtiger_def_org_field table entries for the field per tab +//if we enter a field in vtiger_field table then we must populate that field in these table for security access +function populateFieldForSecurity($tabid,$fieldid) +{ + global $conn; + + $profileresult = $conn->query("select * from vtiger_profile"); + $countprofiles = $conn->num_rows($profileresult); + for ($i=0;$i<$countprofiles;$i++) + { + $profileid = $conn->query_result($profileresult,$i,'profileid'); + $sqlProf2FieldInsert[$i] = 'insert into vtiger_profile2field values ('.$profileid.','.$tabid.','.$fieldid.',0,1)'; + Execute($sqlProf2FieldInsert[$i]); + } + $def_query = "insert into vtiger_def_org_field values (".$tabid.",".$fieldid.",0,1)"; + Execute($def_query); +} + +function localcreateRole($roleName,$parentRoleId,$roleProfileArray) +{ + global $migrationlog; + $migrationlog->debug("Entering localcreateRole(".$roleName.",".$parentRoleId.",".$roleProfileArray.") method ..."); + + global $conn; + $parentRoleDetails = localgetRoleInformation($parentRoleId); + $parentRoleInfo=$parentRoleDetails[$parentRoleId]; + $roleid_no=$conn->getUniqueId("vtiger_role"); + $roleId='H'.$roleid_no; + $parentRoleHr=$parentRoleInfo[1]; + $parentRoleDepth=$parentRoleInfo[2]; + $nowParentRoleHr=$parentRoleHr.'::'.$roleId; + $nowRoleDepth=$parentRoleDepth + 1; + + //Inserting vtiger_role into db + $query="insert into vtiger_role values('".$roleId."','".$roleName."','".$nowParentRoleHr."',".$nowRoleDepth.")"; + $conn->query($query); + + //Inserting into vtiger_role2profile vtiger_table + foreach($roleProfileArray as $profileId) + { + if($profileId != '') + { + localinsertRole2ProfileRelation($roleId,$profileId); + } + } + + $migrationlog->debug("Exiting localcreateRole method ..."); + return $roleId; + +} +function localgetRoleInformation($roleid) +{ + global $migrationlog; + $migrationlog->debug("Entering localgetRoleInformation(".$roleid.") method ..."); + global $conn; + + $query = "select * from vtiger_role where roleid='".$roleid."'"; + $result = $conn->query($query); + $rolename=$conn->query_result($result,0,'rolename'); + $parentrole=$conn->query_result($result,0,'parentrole'); + $roledepth=$conn->query_result($result,0,'depth'); + $parentRoleArr=explode('::',$parentrole); + $immediateParent=$parentRoleArr[sizeof($parentRoleArr)-2]; + + $roleDet=Array(); + $roleDet[]=$rolename; + $roleDet[]=$parentrole; + $roleDet[]=$roledepth; + $roleDet[]=$immediateParent; + $roleInfo=Array(); + $roleInfo[$roleid]=$roleDet; + + $migrationlog->debug("Exiting localgetRoleInformation method ..."); + + return $roleInfo; +} + +function localinsertRole2ProfileRelation($roleId,$profileId) +{ + global $migrationlog; + $migrationlog->debug("Entering localinsertRole2ProfileRelation(".$roleId.",".$profileId.") method ..."); + + global $conn; + $query="insert into vtiger_role2profile values('".$roleId."',".$profileId.")"; + $conn->query($query); + + $migrationlog->debug("Exiting localinsertRole2ProfileRelation method ..."); +} + +?> diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/501_to_502.php b/oss/vtiger/trunk/modules/Migration/DBChanges/501_to_502.php new file mode 100644 index 00000000..878f1cc0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/501_to_502.php @@ -0,0 +1,72 @@ +debug("\n\nDB Changes from 5.0.1 to 5.0.2 -------- Starts \n\n"); + +//Query added to show Manufacturer field in Products module +ExecuteQuery("update vtiger_field set displaytype=1,block=31 where tabid=14 and block=1"); +ExecuteQuery("update vtiger_field set block=23,displaytype=1 where block=1 and displaytype=23 and tabid=10"); +ExecuteQuery("update vtiger_field set block=22,displaytype=1 where block=1 and displaytype=22 and tabid=10"); + +//Added to rearange the attachment in HelpDesk +ExecuteQuery(" update vtiger_field set block=25,sequence=12 where tabid=13 and fieldname='filename'"); + +//Query added to as entityname,its tablename,its primarykey are saved in a table +ExecuteQuery(" CREATE TABLE `vtiger_entityname` ( + `tabid` int(19) NOT NULL default '0', + `modulename` varchar(50) NOT NULL, + `tablename` varchar(50) NOT NULL, + `fieldname` varchar(150) NOT NULL, + `entityidfield` varchar(150) NOT NULL, + PRIMARY KEY (`tabid`), + KEY `entityname_tabid_idx` (`tabid`) +)"); + +//Data Populated for the existing modules +ExecuteQuery("insert into vtiger_entityname values(7,'Leads','vtiger_leaddetails','lastname,firstname','leadid')"); +ExecuteQuery("insert into vtiger_entityname values(6,'Accounts','vtiger_account','accountname','accountid')"); +ExecuteQuery("insert into vtiger_entityname values(4,'Contacts','vtiger_contactdetails','lastname,firstname','contactid')"); +ExecuteQuery("insert into vtiger_entityname values(2,'Potentials','vtiger_potential','potentialname','potentialid')"); +ExecuteQuery("insert into vtiger_entityname values(8,'Notes','vtiger_notes','title','notesid')"); +ExecuteQuery("insert into vtiger_entityname values(13,'HelpDesk','vtiger_troubletickets','title','ticketid')"); +ExecuteQuery("insert into vtiger_entityname values(9,'Calendar','vtiger_activity','subject','activityid')"); +ExecuteQuery("insert into vtiger_entityname values(10,'Emails','vtiger_activity','subject','activityid')"); +ExecuteQuery("insert into vtiger_entityname values(14,'Products','vtiger_products','productname','productid')"); +ExecuteQuery("insert into vtiger_entityname values(29,'Users','vtiger_users','last_name,first_name','id')"); +ExecuteQuery("insert into vtiger_entityname values(23,'Invoice','vtiger_invoice','subject','invoiceid')"); +ExecuteQuery("insert into vtiger_entityname values(20,'Quotes','vtiger_quotes','subject','quoteid')"); +ExecuteQuery("insert into vtiger_entityname values(21,'PurchaseOrder','vtiger_purchaseorder','subject','purchaseorderid')"); +ExecuteQuery("insert into vtiger_entityname values(22,'SalesOrder','vtiger_salesorder','subject','salesorderid')"); +ExecuteQuery("insert into vtiger_entityname values(18,'Vendors','vtiger_vendor','vendorname','vendorid')"); +ExecuteQuery("insert into vtiger_entityname values(19,'PriceBooks','vtiger_pricebook','bookname','pricebookid')"); +ExecuteQuery("insert into vtiger_entityname values(26,'Campaigns','vtiger_campaign','campaignname','campaignid')"); +ExecuteQuery("insert into vtiger_entityname values(15,'Faq','vtiger_faq','question','id')"); + +//added quantity in stock in product default listview - All +$res = $adb->query("select vtiger_cvcolumnlist.cvid from vtiger_cvcolumnlist inner join vtiger_customview on vtiger_cvcolumnlist.cvid=vtiger_customview.cvid where entitytype='Products' and viewname='All'"); +if($adb->num_rows != 0) +{ + $cvid = $adb->query_result($res,0,'cvid'); + $adb->query("insert into vtiger_cvcolumnlist values($cvid,5,'vtiger_products:qtyinstock:qtyinstock:Products_Quantity_In_Stock:V')"); +} + + +//echo "
      5.0/5.0.1 ==> 5.0.2 Database changes has been done.
    "; + +$migrationlog->debug("\n\nDB Changes from 5.0.1 to 5.0.2 -------- Ends \n\n"); + +?> diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/502_to_503rc2.php b/oss/vtiger/trunk/modules/Migration/DBChanges/502_to_503rc2.php new file mode 100644 index 00000000..347b0bc1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/502_to_503rc2.php @@ -0,0 +1,111 @@ +debug("\n\nDB Changes from 5.0.2 to 5.0.3 RC2 -------- Starts \n\n"); + +$query_array = Array( + "alter table vtiger_entityname add column entityidcolumn varchar(150)", + + "update vtiger_entityname set entityidcolumn='leadid' where tabid=7", + "update vtiger_entityname set entityidcolumn='account_id' where tabid=6", + "update vtiger_entityname set entityidcolumn='contact_id' where tabid=4", + "update vtiger_entityname set entityidcolumn='potential_id' where tabid=2", + "update vtiger_entityname set entityidcolumn='notesid' where tabid=8", + "update vtiger_entityname set entityidcolumn='ticketid' where tabid=13", + "update vtiger_entityname set entityidcolumn='activityid' where tabid=9", + "update vtiger_entityname set entityidcolumn='activityid' where tabid=10", + "update vtiger_entityname set entityidcolumn='product_id' where tabid=14", + "update vtiger_entityname set entityidcolumn='id' where tabid=29", + "update vtiger_entityname set entityidcolumn='invoiceid' where tabid=23", + "update vtiger_entityname set entityidcolumn='quote_id' where tabid=20", + "update vtiger_entityname set entityidcolumn='purchaseorderid' where tabid=21", + "update vtiger_entityname set entityidcolumn='salesorder_id' where tabid=22", + "update vtiger_entityname set entityidcolumn='vendor_id' where tabid=18", + "update vtiger_entityname set entityidcolumn='pricebookid' where tabid=19", + "update vtiger_entityname set entityidcolumn='campaignid' where tabid=26", + "update vtiger_entityname set entityidcolumn='id' where tabid=15", + "alter table vtiger_entityname MODIFY entityidcolumn varchar(150) NOT NULL", + + "update vtiger_field set fieldlabel='Part Number' where tabid=14 and fieldname='productcode'", + + + "alter table vtiger_tab change customized customized integer(19)", + "alter table vtiger_tab add column ownedby integer(19)", + "ALTER TABLE vtiger_blocks ADD CONSTRAINT fk_1_vtiger_blocks FOREIGN KEY (tabid) REFERENCES vtiger_tab(tabid) ON DELETE CASCADE", + "alter table vtiger_crmentity modify setype varchar(25)", + + "ALTER TABLE vtiger_customview ADD INDEX customview_entitytype_idx (entitytype)", + "ALTER TABLE vtiger_customview ADD CONSTRAINT fk_1_vtiger_customview FOREIGN KEY (entitytype) REFERENCES vtiger_tab (name) ON DELETE CASCADE", + + "alter table vtiger_parenttabrel change parenttabid parenttabid integer(19)", + "alter table vtiger_parenttabrel change tabid tabid integer(19)", + + "ALTER TABLE vtiger_parenttabrel ADD CONSTRAINT fk_1_vtiger_parenttabrel FOREIGN KEY (tabid) REFERENCES vtiger_tab(tabid) ON DELETE CASCADE", + + "ALTER TABLE vtiger_parenttabrel ADD CONSTRAINT fk_2_vtiger_parenttabrel FOREIGN KEY (parenttabid) REFERENCES vtiger_parenttab(parenttabid) ON DELETE CASCADE", + + "ALTER TABLE vtiger_entityname ADD CONSTRAINT fk_1_vtiger_entityname FOREIGN KEY (tabid) REFERENCES vtiger_tab(tabid) ON DELETE CASCADE", + + "alter table vtiger_parenttab engine=InnoDB", + + "update vtiger_tab set customized=0", + "update vtiger_tab set ownedby=1", + "update vtiger_tab set ownedby=0 where tabid in (2,4,6,7,9,13,16,20,21,22,23,26)", + + ); + +foreach($query_array as $query) +{ + ExecuteQuery($query); +} + + +ExecuteQuery("ALTER TABLE vtiger_users MODIFY user_password varchar(32)"); + +//Changes related to Product - Lead/Account/Contact/Potential relationship - Mickie - 13-01-2007 +ExecuteQuery("delete from vtiger_field where tabid=14 and fieldname in ('parent_id','contact_id')"); + +//Before drop the contactid from products, we have to save this product - contact relationship in seproductsrel table +//ExecuteQuery("insert into vtiger_seproductsrel (select contactid, productid from vtiger_products where contactid is not NULL)"); +//In above query, if there is any duplicate entry then execution stopped. So we will insert undeleted products one by one +$product_contact_res = $adb->query("select contactid, productid from vtiger_products inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid where vtiger_crmentity.deleted=0 and contactid != 0 and contactid is NOT NULL"); +for($i=0;$i<$adb->num_rows($product_contact_res);$i++) +{ + $crmid = $adb->query_result($product_contact_res,$i,'contactid'); + $productid = $adb->query_result($product_contact_res,$i,'productid'); + + $adb->query("insert into vtiger_seproductsrel values ($crmid , $productid)"); +} +ExecuteQuery("alter table vtiger_products drop column contactid"); + + +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",14,7,'get_leads',9,'Leads',0)"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",14,6,'get_accounts',10,'Accounts',0)"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",14,4,'get_contacts',11,'Contacts',0)"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",14,2,'get_opportunities',12,'Potentials',0)"); + +ExecuteQuery("alter table vtiger_seproductsrel add column setype varchar(100)"); +//we have to update setype for all existing entries which will be NULL before execute the following query +ExecuteQuery("update vtiger_seproductsrel,vtiger_crmentity set vtiger_seproductsrel.setype=vtiger_crmentity.setype where vtiger_crmentity.crmid=vtiger_seproductsrel.crmid"); + + +ExecuteQuery("CREATE TABLE vtiger_version (id int(11) NOT NULL auto_increment, old_version varchar(30) default NULL, current_version varchar(30) default NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=latin1"); + +ExecuteQuery("delete from vtiger_selectcolumn WHERE columnname LIKE '%vtiger_crmentityRelProducts%'"); +//echo "
      5.0.2 ==> 5.0.3 Database changes has been done.
    "; + +$migrationlog->debug("\n\nDB Changes from 5.0.2 to 5.0.3 RC2 -------- Ends \n\n"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/503_to_504rc.php b/oss/vtiger/trunk/modules/Migration/DBChanges/503_to_504rc.php new file mode 100644 index 00000000..59e7f0bf --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/503_to_504rc.php @@ -0,0 +1,787 @@ +debug("\n\nDB Changes from 5.0.3 to 5.0.4 RC-------- Starts \n\n"); + + + +/**These two database changes are directly applied in index.php at line 186 to avoid fatal error before starting migration. + * So that these two lines are commented. + + //Added for UserBased TagCloud + ExecuteQuery("alter table vtiger_users add column tagcloud_view int(1) default 1"); + //Added for the Internal mailer option in Users module - By srini 04-09-07 + ExecuteQuery("alter table vtiger_users add column internal_mailer int(3) NOT NULL default '1'"); + */ + +ExecuteQuery("insert into vtiger_field values(29,".$adb->getUniqueID('vtiger_field').",'internal_mailer','vtiger_users',1,'56','internal_mailer','INTERNAL_MAIL_COMPOSER',1,0,0,50,15,80,1,'V~O',1,null,'BAS')"); + +//Added when prodving FCK editor feature in Email Templates. +//before using FCK editor we are using text area. it store next line as \n. so we change the \n to
    when displaying the contents. +//Now we are using FCK editor. So new line character will be automatically saved as
    //But the contents created with text area still having \n character as next line. So we need to change it to
    +//this code will get the contents from db and then convert all \n character with
    and again update in db. + +$result=$adb->query("select templateid,body from vtiger_emailtemplates"); + +for($i=0;$i<$adb->num_rows($result);$i++) +{ +$body=addslashes(nl2br($adb->query_result($result,$i,'body'))); +$templateid=$adb->query_result($result,$i,'templateid'); + +$adb->pquery("update vtiger_emailtemplates set body=? where templateid=?", array($body, $templateid)); +} + + + +//for Customer Portal Login details +$body=' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + +
    + + + + + + + + + + + + + + + +
    $logo$
    vtiger CRM
    The honest Open Source CRM
    +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Dear $contact_name$,
    Thank you very much for subscribing to the vtiger CRM - annual support service.
    Here is your self service portal login details:
    + + + + + + + + + + + +

    User ID : $login_name$
    Password: $password$
    $URL$
    +
    NOTE: We suggest you to change your password after logging in first time.

    Help Documentation

    After logging in to vtiger Self-service Portal first time, you can access the vtiger CRM documents from the Documents tab. Following documents are available for your reference:
    +
      +
    • Installation Manual (Windows & Linux OS)
    • +
    • User & Administrator Manual
    • +
    • vtiger Customer Portal - User Manual
    • +
    • vtiger Outlook Plugin - User Manual
    • +
    • vtiger Office Plug-in - User Manual
    • +
    • vtiger Thunderbird Extension - User Manual
    • +
    • vtiger Web Forms - User Manual
    • +
    • vtiger Firefox Tool bar - User Manual
    • +
    +

    Knowledge Base

    Periodically we update frequently asked question based on our customer experiences. You can access the latest articles from the FAQ tab.

    vtiger CRM - Details

    Kindly let us know your current vtiger CRM version and system specification so that we can provide you necessary guidelines to enhance your vtiger CRM system performance. Based on your system specification we alert you about the latest security & upgrade patches.

    Thank you once again and wish you a wonderful experience with vtiger CRM.


    Best Regards
    $support_team$
    www.vtiger.com
    +
    +
    + + + + + + + + + + + +
    Shree Narayana Complex, No 11 Sarathy Nagar, Vijaya Nagar , Velachery, Chennai - 600 042 India
    Telephone No: +91 - 44 - 4202 - 1990 Toll Free No: +1 877 788 4437
    Email Id: support@vtiger.com
    +
    +
    '; + +$fieldid = $adb->getUniqueID('vtiger_emailtemplates'); +$login_id=$fieldid; +$adb->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Customer Login Details','Customer Portal Login Details','Send Portal login details to customer','".$body."',0,".$fieldid.")"); + + +//for Support end notification before a week +$body=' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + +
    + + + + + + + + + + + + + + + +
    $logo$
    vtiger CRM
    The honest Open Source CRM
    +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Dear $contacts-lastname$,
    This is just a notification mail regarding your support end.
    Priority: Urgent
    Your Support is going to expire on next week
    Please contact support@vtiger.com.





    Sincerly
    Support Team
    www.vtiger.com
    +
    +
    + + + + + + + + + + + +
    Shree Narayana Complex, No 11 Sarathy Nagar, Vijaya Nagar , Velachery, Chennai - 600 042 India
    Telephone No: +91 - 44 - 4202 - 1990 Toll Free No: +1 877 788 4437
    Email Id: info@vtiger.com
    +
    +
    '; +$fieldid = $adb->getUniqueID('vtiger_emailtemplates'); +$week_id=$fieldid; +$adb->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Support end notification before a week','VtigerCRM Support Notification','Send Notification mail to customer before a week of support end date','".$body."',0,".$fieldid.")"); + + + + +//for Support end notification before a month +$body=' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + +
    + + + + + + + + + + + + + + + +
    $logo$
    vtiger CRM
    The honest Open Source CRM
    +
    + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Dear $contacts-lastname$,
    This is just a notification mail regarding your support end.
    Priority: Normal
    Your Support is going to expire on next month.
    Please contact support@vtiger.com





    Sincerly
    Support Team
    www.vtiger.com
    +
    +
    + + + + + + + + + + + +
    Shree Narayana Complex, No 11 Sarathy Nagar, Vijaya Nagar , Velachery, Chennai - 600 042 India
    Telephone No: +91 - 44 - 4202 - 1990 Toll Free No: +1 877 788 4437
    Email Id: info@vtiger.com
    +
    +
    '; +$fieldid = $adb->getUniqueID('vtiger_emailtemplates'); +$month_id=$fieldid; +$adb->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Support end notification before a month','VtigerCRM Support Notification','Send Notification mail to customer before a month of support end date','".$body."',0,".$fieldid.")"); + + + +//Queries for Notification scheduler +//to add a new column type in vtiger_notificationscheduler + +ExecuteQuery("alter table vtiger_notificationscheduler add column type varchar(10)"); + +$adb->query("update vtiger_notificationscheduler set notificationbody='".$login_id."',type='select' where schedulednotificationid=5"); +$adb->query("update vtiger_notificationscheduler set notificationbody='".$week_id."',type='select' where schedulednotificationid=6"); + + + + + +$adb->query("update vtiger_notificationscheduler set schedulednotificationname='LBL_SUPPORT_DESCRIPTION_MONTH',active='1',notificationsubject='Support end notification',notificationbody='".$month_id."',label='LBL_SUPPORT_NOTICIATION_MONTH',type='select' where schedulednotificationid=7"); + + +$fieldid = $adb->getUniqueID('vtiger_notificationscheduler'); +$adb->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label,type) values (".$fieldid.",'LBL_ACTIVITY_REMINDER_DESCRIPTION',1,'Activity Reminder Notification','This is a reminder notification for the Activity','LBL_ACTIVITY_NOTIFICATION','')"); + + +//End of Email templates and Notificatin Scheduler changes. + + +//creating the new tables vtiger_picklist,vtiger_picklist_seq and vtiger_role2picklist +$adb->query("CREATE TABLE `vtiger_picklist` (`picklistid` int(11) NOT NULL auto_increment,`name` varchar(200) NOT NULL,PRIMARY KEY (`picklistid`),UNIQUE KEY `picklist_name_idx` (`name`)) ENGINE=InnoDB"); + +$adb->query("CREATE TABLE `vtiger_role2picklist` ( + `roleid` varchar(255) NOT NULL, + `picklistvalueid` int(11) NOT NULL, + `picklistid` int(11) NOT NULL, + `sortid` int(11) default NULL, + PRIMARY KEY (`roleid`,`picklistvalueid`,`picklistid`), + KEY `role2picklist_roleid_picklistid_idx` (`roleid`,`picklistid`,`picklistvalueid`), + KEY `fk_2_vtiger_role2picklist` (`picklistid`)) type='InnoDB'"); + +//$adb->query("alter table vtiger_role2picklist add CONSTRAINT `fk_1_vtiger_role2picklist` FOREIGN KEY (`roleid`) REFERENCES `vtiger_role` (`roleid`) ON DELETE CASCADE"); + +$adb->query("alter table vtiger_role2picklist add CONSTRAINT `fk_3_vtiger_role2picklist` FOREIGN KEY (`picklistid`) REFERENCES `vtiger_picklist` (`picklistid`) ON DELETE CASCADE"); + + +//$adb->query("CREATE TABLE `vtiger_picklistvalues_seq` (`id` int(11) NOT NULL)"); +//$adb->query("insert into vtiger_picklistvalues_seq values(1)"); +//Alter picklist tables +$picklist_arr = array('leadsource','accounttype','industry','leadstatus','rating','opportunity_type','salutationtype','sales_stage','ticketstatus','ticketpriorities','ticketseverities','ticketcategories','eventstatus','taskstatus','taskpriority','manufacturer','productcategory','faqcategories','usageunit','glacct','quotestage','carrier','faqstatus','invoicestatus','postatus','sostatus','campaigntype','campaignstatus','expectedresponse'); + +$custom_result = $adb->query("select * from vtiger_field where (uitype=15 or uitype=33) and fieldname like '%cf_%'"); +$numrow = $adb->num_rows($custom_result); +for($i=0; $i < $numrow; $i++) +{ + $picklist_arr[] = $adb->query_result($custom_result,$i,'fieldname'); +} + +for($i=0;$iquery("alter table vtiger_$table_name drop column sortorderid"); + $adb->query("alter table vtiger_$table_name add column picklist_valueid int(19) not null default '0'"); +} + +//Inserting values on vtiger_picklist tables +function insert_picklist_table($picklist) +{ + global $adb; + $picklist_uniqueid = $adb->getUniqueID("vtiger_picklist"); + $adb->query("insert into vtiger_picklist values('$picklist_uniqueid','$picklist')"); + insert_values($picklist,$picklist_uniqueid); +} + +//Function to insert values on vtiger_role2picklist table and updating the values for picklist tables +function insert_values($picklist,$picklistid) +{ + global $adb; + $result = $adb->query("select * from vtiger_$picklist"); + $numrow = $adb->num_rows($result); + for($i=0; $i < $numrow; $i++) + { + $picklist_name = decode_html($adb->query_result($result,$i,$picklist)); + $picklist_valueid = getUniquePicklistID(); + $picklistquery = "update vtiger_$picklist set picklist_valueid=? where $picklist=?"; + $adb->pquery($picklistquery, array($picklist_valueid, $picklist_name)); + $sql="select roleid from vtiger_role"; + $role_result = $adb->query($sql); + $numrows = $adb->num_rows($role_result); + for($k=0; $k < $numrows; $k++) + { + $roleid = $adb->query_result($role_result,$k,'roleid'); + $adb->query("insert into vtiger_role2picklist values('".$roleid."',".$picklist_valueid.",$picklistid,".$i.")"); + } + } +} + + + +//drop the column description in troubletickets table -- by liza on 30-08-2007 +ExecuteQuery("update vtiger_field set tablename='vtiger_crmentity' where tabid =13 and fieldname='description'"); +ExecuteQuery("update vtiger_crmentity inner join vtiger_troubletickets on vtiger_troubletickets.ticketid=vtiger_crmentity.crmid set vtiger_crmentity.description=vtiger_troubletickets.description"); +ExecuteQuery("alter table vtiger_troubletickets drop column description"); + +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_crmentity:description:description:HelpDesk_Description:V' where columnname='vtiger_troubletickets:description:description:HelpDesk_Description:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_crmentity:description:HelpDesk_Description:V' where columnname='vtiger_troubletickets:description:description:HelpDesk_Description:V'"); + +//Changed the ordinary field to mandatory field for the field EventStatus??(Event Module) +//Changing the typeofdata as "V~M" from "V~O"--added by Bharath 30-08-07 +ExecuteQuery("update vtiger_field set typeofdata='V~M' where tabid=16 and columnname='eventstatus'"); + +//Modified the vtiger_mail_accounts for change password in incoming mail server settings - by srini 04-09-07 +ExecuteQuery("alter table vtiger_mail_accounts modify column mail_password varchar(150)"); + +//Modified the vtiger_portal table for make as default option in Mysites - by srini 04-09-07 +ExecuteQuery("alter table vtiger_portal add column setdefault int(3) NOT NULL default '0'"); + +//Modifed the quantity field from integer to decimal -By shahul +//Added to fix the ticket # 4119 +ExecuteQuery("alter table vtiger_inventoryproductrel modify column quantity decimal(25,3)"); + +//4065 -- to support email address as a user name -- by bharathi + +//ALTER TABLE vtiger_users MODIFY user_name varchar(100); + +//added for the ticket#4109 -- by bharathi +ExecuteQuery("update vtiger_relatedlists set sequence=sequence+1 where tabid=6 and sequence>6"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID("vtiger_relatedlists").",6,10,'get_emails',7,'Emails',0)"); + +//added by Dinakaran for the ticket(http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/4125) Date:24/08/2007 +ExecuteQuery("alter table vtiger_attachments add column subject varchar(200)"); + +//Added by mangai regarding performance + +ExecuteQuery("ALTER TABLE vtiger_cntactivityrel ADD CONSTRAINT fk_1_vtiger_cntactivityrel FOREIGN KEY (`activityid`) REFERENCES `vtiger_activity` (`activityid`) ON DELETE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_recurringevents ADD CONSTRAINT fk_1_vtiger_recurringevents FOREIGN KEY(activityid) REFERENCES vtiger_activity(activityid)"); + +ExecuteQuery("alter table vtiger_activity add column recurringtype varchar(30) default NULL"); + +ExecuteQuery("UPDATE vtiger_field SET tablename='vtiger_activity' where fieldname='recurringtype'"); + +ExecuteQuery("update vtiger_activity inner join vtiger_recurringevents on vtiger_recurringevents.activityid=vtiger_activity.activityid set vtiger_activity.recurringtype = vtiger_recurringevents.recurringtype"); + +//Added for the fix 3919 by akilan on 20th september +ExecuteQuery("update vtiger_field set uitype=255 where tabid in (7,4) and columnname='lastname'"); + +//We need to remove the field team from quotes. To avoid data loss, we need to create a new custom field and to move the team field values into the newly created sutom field. + +//Getting block id for custom information +$blockid = $adb->query_result($adb->query("select blockid from vtiger_blocks where tabid=20 and blocklabel = 'LBL_CUSTOM_INFORMATION'"),0,'blockid'); + +//Getting the sequence +$seq = $adb->query_result($adb->query("select max(sequence) as seq from vtiger_field where block=".$blockid." and tabid=20"),0,'seq'); + +//Removing the Team field from field table. +ExecuteQuery("delete from vtiger_field where tabid=20 and fieldname = 'team' and columnname='team'"); +//Creating new Custom field for quotes module and populating security entries. + +//Getting the biggest custom field name and id +$newfieldid=$adb->getUniqueID("vtiger_field"); +$new_cf_name = 'cf_'.$newfieldid; +$query="insert into vtiger_field values(20,".$newfieldid.",'".$new_cf_name."','vtiger_quotescf',2,1,'".$new_cf_name."','Team',0,0,0,100,".($seq+1).",".$blockid.",1,'V~O~LE~30',1,0,'BAS')"; +$result = $adb->query($query); + + +//Populate security entries for this new field +$profileresult = $adb->query("select * from vtiger_profile"); +$countprofiles = $adb->num_rows($profileresult); +for($i=0;$i<$countprofiles;$i++) +{ + $profileid = $adb->query_result($profileresult,$i,'profileid'); + $sqlProf2FieldInsert[$i] = 'insert into vtiger_profile2field values ('.$profileid.',20,'.$newfieldid.',0,1)'; + ExecuteQuery($sqlProf2FieldInsert[$i]); +} +$def_query = "insert into vtiger_def_org_field values (20,".$newfieldid.",0,1)"; +ExecuteQuery($def_query); +//End of security popullation + +ExecuteQuery("ALTER TABLE vtiger_quotescf ADD ".$new_cf_name." VARCHAR(100)"); + +//Copying all the existing values for team field in vtiger_quotes table into vtiger_quotescf table. ie, moving values from team field into a new custom field. +ExecuteQuery("update vtiger_quotescf inner join vtiger_quotes on vtiger_quotescf.quoteid=vtiger_quotes.quoteid set $new_cf_name=vtiger_quotes.team"); + +//If any custom view referring to the deleted field 'team' then we need to update it to point the newly created custom field. +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_quotescf:$new_cf_name:$new_cf_name:Quotes_Team:V' where columnname='vtiger_quotes:team:team:Quotes_Team:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_quotescf:$new_cf_name:$new_cf_name:Quotes_Team:V' where columnname='vtiger_quotes:team:team:Quotes_Team:V'"); +//Removing the team column from the vtiger_quotes table +ExecuteQuery("ALTER TABLE vtiger_quotes drop team"); + +//Added by Akilan on 18th November +ExecuteQuery("CREATE TABLE vtiger_soapservice (id int(19) default NULL, type varchar(25) default NULL,sessionid varchar(100) default NULL) ENGINE=InnoDB"); +//Added by dinakaran. 18th November +////User Name field size increased into 255 chars in vtiger_users table +ExecuteQuery("alter table vtiger_users change user_name user_name varchar(255)"); + +//And by dina to change sequence for purchaseorder +ExecuteQuery("update vtiger_field set sequence=5 where columnname='purchaseorder' and tabid=22"); + + +//Added by shahul for #4574 +////Changed type of data for Price Book's active field. +ExecuteQuery("update vtiger_field set typeofdata='C~O' where tabid=19 and fieldname='active'"); + +//Added by shaul for the fix 4615 +ExecuteQuery("update vtiger_field set typeofdata='N~O' where fieldname='expectedrevenue' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='N~O' where fieldname='budgetcost' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='N~O' where fieldname='actualcost' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='I~O' where fieldname='targetsize' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='I~O' where fieldname='expectedresponsecount' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='I~O' where fieldname='expectedsalescount' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='I~O' where fieldname='actualresponsecount' and tabid=26"); +ExecuteQuery("update vtiger_field set typeofdata='I~O' where fieldname='actualsalescount' and tabid=26"); + + +//Added by Akilan to fix the issue #4544 +ExecuteQuery("alter table vtiger_attachments change column name name varchar(255)"); + +// Added by akilan to fix the issue #4568 +// Custom field default value is null that should be replace to Empty value. +$cfresult = $adb->query("select columnname,tablename,uitype,fieldname,fieldlabel,typeofdata from vtiger_field where columnname like 'cf_%' and uitype in (1,13,11,15,17,85) order by columnname"); +$countcf = $adb->num_rows($cfresult); +for($i=0;$i<$countcf;$i++) +{ + $column = $adb->query_result($cfresult,$i,'columnname'); + $table = $adb->query_result($cfresult,$i,'tablename'); + $adb->query("alter table $table alter $column set default ''"); + $adb->query("update $table set $column = '' where $column is NULL"); +} + +//Added by liza for 4242 ticket +ExecuteQuery("alter table vtiger_products modify column qtyinstock decimal(25,3)"); +ExecuteQuery("update vtiger_field set typeofdata='NN~O' where tabid=14 and fieldname='qtyinstock'"); + + +//Added by Pavani 4th December +//To add check boxes for import/export for Trouble Tickets and Vendors +$profileresult = $adb->query("select * from vtiger_profile"); +$countprofiles = $adb->num_rows($profileresult); +for($i=0;$i<$countprofiles;$i++) +{ + $profileid = $adb->query_result($profileresult,$i,'profileid'); + + //For Trouble Tickets + ExecuteQuery("insert into vtiger_profile2utility values(".$profileid.",13,5,0)"); + ExecuteQuery("insert into vtiger_profile2utility values(".$profileid.",13,6,0)"); + //For Vendors + ExecuteQuery("insert into vtiger_profile2utility values(".$profileid.",18,5,0)"); + ExecuteQuery("insert into vtiger_profile2utility values(".$profileid.",18,6,0)"); + +} + +//Added by Minnie to set the TABLE - storage_engine type - InnoDB +ExecuteQuery("ALTER TABLE vtiger_blocks Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_activity_reminder Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_currency_info Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_customerdetails Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_defaultcv Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_def_org_field Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_def_org_share Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_durationhrs Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_durationmins Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_emaildetails Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_emailtemplates Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_faqcategories Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_faqstatus Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_files Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_freetags Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_group2role Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_group2rs Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_headers Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_import_maps Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_inventory_tandc Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_invitees Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_loginhistory Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_mail_accounts Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_portalinfo Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_profile2field Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_profile2standardpermissions Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_profile2tab Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_profile2utility Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_relatedlists Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_role2profile Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_rss Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_sales_stage Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_sharedcalendar Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_systems Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_taskstatus Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_ticketstracktime Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_users2group Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_users_last_import Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_wordtemplates Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_activsubtype Type=InnoDB"); +ExecuteQuery("ALTER TABLE vtiger_version Type=InnoDB"); + +//Added by Asha for tickets #4513 +////File Name field size increased into 255 chars in vtiger_attachments table +ExecuteQuery("alter table vtiger_attachments change name name varchar(255)"); +////Data type for File Path field changed to TEXT in vtiger_attachments table +ExecuteQuery("alter table vtiger_attachments change path path TEXT"); + +//Added by bharathi #4657 +ExecuteQuery("alter table vtiger_attachments drop index attachments_description_name_type_attachmentsid_idx"); +ExecuteQuery("alter table vtiger_attachments add index attachments_description_type_attachmentsid_idx (`description`,`type`,`attachmentsid`)"); + +//Added by Asha for ticket #4724 +ExecuteQuery("update vtiger_selectcolumn set columnname = 'vtiger_campaign:campaignname:Potentials_Campaign_Source:campaignid:V' where columnname = 'vtiger_potential:campaignid:Potentials_Campaign_Source:campaignid:V'"); + +//Added by bharathi for #4590 on dec 21-2007 +ExecuteQuery("alter table vtiger_potential change column amount amount decimal(14,2) default '0.00'"); + +//Added by Srini for #4684 on dec 21-2007 +ExecuteQuery("update vtiger_field set uitype=19 where fieldname='update_log' and tablename='vtiger_troubletickets'"); + +//In 503 we are using
    tags for line breaks in Inventory Notification mails. In 504 it is not necessary. +//this code will get the contents from db and then convert all
    character with \n and again update in db. +$result=$adb->query("select notificationid,notificationbody from vtiger_inventorynotification"); + +for($i=0;$i<$adb->num_rows($result);$i++) +{ + $body=decode_html($adb->query_result($result,$i,'notificationbody')); + $body=str_replace('
    ','\n', $body); + $notificationid=$adb->query_result($result,$i,'notificationid'); + $adb->pquery("update vtiger_inventorynotification set notificationbody=? where notificationid=?", array($body, $notificationid)); +} +//Added by Asha for #4826 +ExecuteQuery("update vtiger_pricebook set active=0 where active is null"); + +$migrationlog->debug("\n\nDB Changes from 5.0.3 to 5.0.4 RC-------- Ends \n\n"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/503rc2_to_503.php b/oss/vtiger/trunk/modules/Migration/DBChanges/503rc2_to_503.php new file mode 100644 index 00000000..6945c924 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/503rc2_to_503.php @@ -0,0 +1,853 @@ +debug("\n\nDB Changes from 5.0.3RC2 to 5.0.3 -------- Starts \n\n"); + +$query_array = Array( + //description field added in vtiger_inventoryproductrel + "alter table vtiger_inventoryproductrel add column description TEXT default NULL after comment", + + //size increased for comment field + "alter table vtiger_inventoryproductrel change comment comment varchar(250)", + + //size increased for tax and discount related fields in Inventory modules + "alter table vtiger_purchaseorder change salestax salestax decimal(25,3)", + "alter table vtiger_purchaseorder change adjustment adjustment decimal(25,3)", + "alter table vtiger_purchaseorder change salescommission salescommission decimal(25,3)", + "alter table vtiger_purchaseorder change exciseduty exciseduty decimal(25,3)", + "alter table vtiger_purchaseorder change total total decimal(25,3)", + "alter table vtiger_purchaseorder change subtotal subtotal decimal(25,3)", + "alter table vtiger_purchaseorder change discount_percent discount_percent decimal(25,3)", + "alter table vtiger_purchaseorder change discount_amount discount_amount decimal(25,3)", + "alter table vtiger_purchaseorder change s_h_amount s_h_amount decimal(25,3)", + + "alter table vtiger_salesorder change salestax salestax decimal(25,3)", + "alter table vtiger_salesorder change adjustment adjustment decimal(25,3)", + "alter table vtiger_salesorder change salescommission salescommission decimal(25,3)", + "alter table vtiger_salesorder change exciseduty exciseduty decimal(25,3)", + "alter table vtiger_salesorder change total total decimal(25,3)", + "alter table vtiger_salesorder change subtotal subtotal decimal(25,3)", + "alter table vtiger_salesorder change discount_percent discount_percent decimal(25,3)", + "alter table vtiger_salesorder change discount_amount discount_amount decimal(25,3)", + "alter table vtiger_salesorder change s_h_amount s_h_amount decimal(25,3)", + + "alter table vtiger_invoice change salestax salestax decimal(25,3)", + "alter table vtiger_invoice change adjustment adjustment decimal(25,3)", + "alter table vtiger_invoice change salescommission salescommission decimal(25,3)", + "alter table vtiger_invoice change exciseduty exciseduty decimal(25,3)", + "alter table vtiger_invoice change total total decimal(25,3)", + "alter table vtiger_invoice change subtotal subtotal decimal(25,3)", + "alter table vtiger_invoice change discount_percent discount_percent decimal(25,3)", + "alter table vtiger_invoice change discount_amount discount_amount decimal(25,3)", + "alter table vtiger_invoice change s_h_amount s_h_amount decimal(25,3)", + + "alter table vtiger_quotes change subtotal subtotal decimal(25,3)", + "alter table vtiger_quotes change tax tax decimal(25,3)", + "alter table vtiger_quotes change adjustment adjustment decimal(25,3)", + "alter table vtiger_quotes change total total decimal(25,3)", + "alter table vtiger_quotes change discount_percent discount_percent decimal(25,3)", + "alter table vtiger_quotes change discount_amount discount_amount decimal(25,3)", + "alter table vtiger_quotes change s_h_amount s_h_amount decimal(25,3)", + + "alter table vtiger_pricebookproductrel change listprice listprice decimal(25,3)", + + "alter table vtiger_inventoryproductrel change listprice listprice decimal(25,3)", + + "alter table vtiger_products change unit_price unit_price decimal(25,2)", + + "alter table vtiger_campaign change expectedrevenue expectedrevenue decimal(25,3)", + "alter table vtiger_campaign change budgetcost budgetcost decimal(25,3)", + "alter table vtiger_campaign change actualcost actualcost decimal(25,3)", + "alter table vtiger_campaign change expectedroi expectedroi decimal(25,3)", + "alter table vtiger_campaign change actualroi actualroi decimal(25,3)", + + //unwanted currency column removed from lead and contact + "alter table vtiger_leadsubdetails drop column currency", + + "alter table vtiger_contactdetails drop column currency", + + //Amount and probability field datatype modified.(http://forums.vtiger.com/viewtopic.php?t=14006) + + "alter table vtiger_potential change probability probability decimal(5,2)", + "alter table vtiger_potential change amount amount decimal(12,2)", + + //Homepage order has been changed + "update vtiger_users set homeorder = 'HDB,ALVT,PLVT,QLTQ,CVLVT,HLT,OLV,GRT,OLTSO,ILTI,MNL,OLTPO,LTFAQ'", + + ); + +foreach($query_array as $query) +{ + ExecuteQuery($query); +} + +//Added to avoid migration error. +//Check for the table availability before alter. +$exists1=$adb->query("show create table vtiger_opportunitystage"); +if($exists1) +{ + ExecuteQuery("alter table vtiger_opportunitystage change probability probability decimal(5,2)"); +} + +$exists2=$adb->query("show create table vtiger_dealintimation"); +if($exists2) +{ + ExecuteQuery("alter table vtiger_dealintimation change dealprobability dealprobability decimal(5,2)"); +} + +$exists3=$adb->query("show create table vtiger_potstagehistory"); +if($exists3) +{ + ExecuteQuery("alter table vtiger_potstagehistory change probability probability decimal(5,2)"); + ExecuteQuery("alter table vtiger_potstagehistory change amount amount decimal(12,2)"); +} +//Check ends + +//Added for Custom Invoice Number, No need for security population +//Invoice Number has been set the uitype as 3 which is a new UI type. user can configure but non editable +$newfieldid = $adb->getUniqueID("vtiger_field"); +ExecuteQuery("insert into vtiger_field values(23,".$newfieldid.",'invoice_no','vtiger_invoice',1,'3','invoice_no','Invoice No',1,0,0,100,3,69,1,'V~M',1,NULL,'BAS')"); +//Populate security entries for this new field +$profileresult = $adb->query("select * from vtiger_profile"); +$countprofiles = $adb->num_rows($profileresult); +for($i=0;$i<$countprofiles;$i++) +{ + $profileid = $adb->query_result($profileresult,$i,'profileid'); + $sqlProf2FieldInsert[$i] = 'insert into vtiger_profile2field values ('.$profileid.',23,'.$newfieldid.',0,1)'; + ExecuteQuery($sqlProf2FieldInsert[$i]); +} +$def_query = "insert into vtiger_def_org_field values (23,".$newfieldid.",0,1)"; +ExecuteQuery($def_query); + +ExecuteQuery("alter table vtiger_invoice add column (invoice_no varchar(50) UNIQUE default NULL)"); + +$res = $adb->query("select cvid from vtiger_customview where entitytype='Invoice' and viewname='All'"); +$cvid = $adb->query_result($res,0,'cvid'); + +ExecuteQuery("update vtiger_cvcolumnlist set columnindex=6 where columnindex=5 and cvid=$cvid"); +ExecuteQuery("update vtiger_cvcolumnlist set columnindex=5 where columnindex=4 and cvid=$cvid"); +ExecuteQuery("update vtiger_cvcolumnlist set columnindex=4 where columnindex=3 and cvid=$cvid"); +ExecuteQuery("update vtiger_cvcolumnlist set columnindex=3 where columnindex=2 and cvid=$cvid"); +ExecuteQuery("update vtiger_cvcolumnlist set columnindex=2 where columnindex=1 and cvid=$cvid"); +ExecuteQuery("insert into vtiger_cvcolumnlist values($cvid,1,'vtiger_invoice:invoice_no:invoice_no:Invoice_invoice_no:V')"); + +//Added for product custom view taxclass issue Ticket #3364 +ExecuteQuery("update vtiger_field set tablename='vtiger_products' where tablename='vtiger_producttaxrel' and columnname='taxclass'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_products:taxclass:taxclass:Products_Tax_Class:V' where columnname='vtiger_producttaxrel:taxclass:taxclass:Products_Tax_Class:V'"); + + + + +//Display type 3 added in profile & default org tables + +$profileresult = $adb->query("select * from vtiger_profile"); +$countprofiles = $adb->num_rows($profileresult); + +$res = $adb->query("select * from vtiger_field where fieldid not in (select fieldid from vtiger_profile2field) and generatedtype=1 and displaytype=3 and tabid!=29"); +//$res = $adb->query("select * from vtiger_field where generatedtype=1 and displaytype=3 and tabid!=29"); +$num_fields = $adb->num_rows($res); +for($i=0;$i<$num_fields;$i++) +{ + $tabid = $adb->query_result($res,$i,'tabid'); + $fieldid = $adb->query_result($res,$i,'fieldid'); + + //For each profile, we have to enter the current fields + for ($j=0;$j<$countprofiles;$j++) + { + $profileid = $adb->query_result($profileresult,$j,'profileid'); + ExecuteQuery('insert into vtiger_profile2field values ('.$profileid.','.$tabid.','.$fieldid.',0,1)'); + } + + $def_query = "insert into vtiger_def_org_field values (".$tabid.",".$fieldid.",0,1)"; + ExecuteQuery($def_query); +} + + +$query_array2 = Array( + + //Added To fix Duplicate items in Report's Select Column(ticket #3665) + + "update vtiger_field set fieldlabel='Adjustment' where tabid=22 and columnname='adjustment'", + + "update vtiger_field set fieldlabel='Sub Total' where tabid=22 and columnname='subtotal'", + + "update vtiger_field set fieldlabel='Adjustment' where tabid=23 and columnname='adjustment'", + + "update vtiger_field set fieldlabel='Sales Tax' where tabid=20 and columnname='tax'", + + // Changes made to make discontinued column in vtiger_products '0' during deactivation. + + "alter table vtiger_products modify discontinued int(1) NOT NULL default 0", + + "UPDATE vtiger_products SET discontinued=1 WHERE discontinued IS NULL", + + //Ref : ticket#3278, 3309, 3461 + "update vtiger_field set typeofdata='E~O' where fieldname in ('yahooid','yahoo_id')", + "alter table vtiger_leaddetails modify noofemployees int(50)", + "update vtiger_field set typeofdata='I~O' where fieldname ='noofemployees' && tabid='7'", + + //Ref : ticket#3521 + "update vtiger_field set typeofdata ='D~O' where tabid=21 && fieldname='duedate'", + + + //Changes made to add an email Id for standarduser since a user must have an Email Id.Changes for 5.0.3. + "update vtiger_users set email1='standarduser@vtigeruser.com' where id = '2' and email1 = ''", + + + //#3668, this query is already available in the file modules/Migration/DBChanges/42P2_to_50.php + "update vtiger_crmentity set setype='Calendar' where setype='Activities'", + + //we don't have field security for Emails module, so we can delete the existing entries + "delete from vtiger_profile2field where tabid=10", + "delete from vtiger_def_org_field where tabid=10", + ); + +foreach($query_array2 as $query) +{ + ExecuteQuery($query); +} + + +//change the picklist - presence value ie., if presence = 0 then you cannot edit, if presence = 1 then you can edit +$noneditable_tables = Array("ticketstatus","taskstatus","eventstatus","eventstatus","faqstatus","quotestage","postatus","sostatus","invoicestatus"); +$noneditable_values = Array( + "sales_stage"=>"Closed Won", + ); +foreach($noneditable_tables as $picklistname) +{ + //we have to interchange 0 and 1, so change 0->2, 1->0, 2->1 + ExecuteQuery("UPDATE vtiger_".$picklistname." SET PRESENCE=2 WHERE PRESENCE=0"); + ExecuteQuery("UPDATE vtiger_".$picklistname." SET PRESENCE=0 WHERE PRESENCE=1"); + ExecuteQuery("UPDATE vtiger_".$picklistname." SET PRESENCE=1 WHERE PRESENCE=2"); +} +foreach($noneditable_values as $picklistname => $value) +{ + ExecuteQuery("UPDATE vtiger_".$picklistname." SET PRESENCE=0 WHERE $picklistname='".$value."'"); +} + +//Assigned To value is shown as empty in Accounts, Emails and PO listviews because of uitype 52 +ExecuteQuery("update vtiger_field set uitype=53 where fieldname='assigned_user_id' and tabid in (6,10,21)"); + +//AccountName is shown as empty in SO/Quotes/Invoice listview because of account details in vtiger_cvcolumnlist.columnname +$modules_array = Array("SalesOrder","Quotes","Invoice","Contacts","Potentials"); +foreach($modules_array as $module) +{ + ExecuteQuery("update vtiger_cvcolumnlist inner join vtiger_customview on vtiger_customview.cvid=vtiger_cvcolumnlist.cvid set columnname='vtiger_account:accountname:accountname:".$module."_Account_Name:V' where columnname like '%:accountid:account_id:%' and vtiger_customview.entitytype='".$module."'"); +} + +//Previously PurchaseOrder was named as Order. Now we have to change the entitytype from Orders to PurchaseOrder +ExecuteQuery("update vtiger_customview set entitytype='PurchaseOrder' where entitytype='Orders'"); + +//ContactName is shown as empty in SO/Quotes/Invoice listview because of contact details in vtiger_cvcolumnlist.columnname +$modules_array = Array("SalesOrder","Quotes","Invoice","PurchaseOrder","Notes","Calendar"); +foreach($modules_array as $module) +{ + ExecuteQuery("update vtiger_cvcolumnlist inner join vtiger_customview on vtiger_customview.cvid=vtiger_cvcolumnlist.cvid set columnname='vtiger_contactdetails:lastname:lastname:".$module."_Contact_Name:V' where columnname like '%:contactid:contact_id:%' and vtiger_customview.entitytype='".$module."'"); +} + +/* +$res = $adb->query("select vtiger_cvcolumnlist.*, vtiger_customview.viewname from vtiger_cvcolumnlist inner join vtiger_customview on vtiger_customview.cvid=vtiger_cvcolumnlist.cvid where columnname like '%:accountid:account_id:%' and vtiger_customview.entitytype='SalesOrder'"); +for($i=0;$i<$adb->num_rows($res);$i++) +{ + $cvid = $adb->query_result($res,$i,'cvid'); + $columnindex = $adb->query_result($res,$i,'columnindex'); + ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_account:accountname:accountname:SalesOrder_Account_Name:V' where cvid=$cvid and columnindex=$columnindex"); +} +*/ + +//ContactName in Calendar listview is a link but record id is empty in link so when we click the link fatal error comes +//ExecuteQuery("update vtiger_cvcolumnlist inner join vtiger_customview on vtiger_customview.cvid=vtiger_cvcolumnlist.cvid set columnname = 'vtiger_cntactivityrel:contactid:contact_id:Calendar_Contact_Name:V' where columnname = 'vtiger_contactdetails:lastname:lastname:Calendar_Contact_Name:V' and vtiger_customview.entitytype='Calendar'"); + +//Related To is not displayed in Calendar Listview +ExecuteQuery("update vtiger_cvcolumnlist inner join vtiger_customview on vtiger_customview.cvid=vtiger_cvcolumnlist.cvid set columnname = 'vtiger_seactivityrel:crmid:parent_id:Calendar_Related_to:V' where columnname = 'vtiger_seactivityrel:crmid:parent_id:Calendar_Related_To:V' and vtiger_customview.entitytype='Calendar'"); + +/* Owner id is set to 1 for modules other than Leads, Helpdesk and Calendar irrespective of whether it is assigned to a group + [ This is done to fix an issue with 4.2.x versions. So resetting the owner id to 0 for other modules if it is assigned to a group */ +ExecuteQuery("update vtiger_crmentity set smownerid=0 where crmid in + (select accountid from vtiger_accountgrouprelation union select campaignid from vtiger_campaigngrouprelation + union select contactid from vtiger_contactgrouprelation union select invoiceid from vtiger_invoicegrouprelation + union select purchaseorderid from vtiger_pogrouprelation union select potentialid from vtiger_potentialgrouprelation + union select quoteid from vtiger_quotegrouprelation union select salesorderid from vtiger_sogrouprelation)"); + +//Change Emails to Webmails in main tabs - My Home Page, Marketing, Support drop down menu +ExecuteQuery("update vtiger_parenttabrel set tabid=28 where tabid=10"); + +//we have to put invoiceid as default Invoice Number for all invoices otherwise we cannot edit the invoices +ExecuteQuery("update vtiger_invoice set invoice_no=invoiceid"); + +//change the typeofdata for Emails fields(Custom Fields) from V~O to E~O +ExecuteQuery("update vtiger_field set typeofdata='E~O' where uitype=13 and typeofdata='V~O'"); + +//set the visible to 0 for the mandatory fields for both profile2field and def_org_share_field +ExecuteQuery("update vtiger_profile2field inner join vtiger_field on vtiger_field.fieldid = vtiger_profile2field.fieldid set visible=0 where uitype in (2,6,22,73,24,81,50,23,16,53,20) or displaytype=3"); +ExecuteQuery("update vtiger_def_org_field inner join vtiger_field on vtiger_field.fieldid = vtiger_def_org_field.fieldid set visible=0 where uitype in (2,6,22,73,24,81,50,23,16,53,20) or displaytype=3"); + +//remove http:// from the website in Accounts (In 5.x we will handle this in code instead of db) +ExecuteQuery("update vtiger_account set website = REPLACE(website,'http://','')"); + +//Change the invoice_no as Invoice No - fieldlabel in field table +ExecuteQuery("update vtiger_field set fieldlabel='Invoice No' where fieldlabel='invoice_no' and tabid='23'"); + +//Change the filter value for Account - Member Of in advance filter +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_account:parentid:account_id:Accounts_Member_Of:V' where columnname='vtiger_account:accountname:accountname:Accounts_Member_Of:V'"); + +//Drop the salestax from Quotes/PO/SO/Invoice which is unwanted field +ExecuteQuery("delete from vtiger_field where fieldname in ('txtTax') and tabid in (20,21,22,23)"); +ExecuteQuery("alter table vtiger_quotes drop column tax"); +ExecuteQuery("alter table vtiger_purchaseorder drop column salestax"); +ExecuteQuery("alter table vtiger_salesorder drop column salestax"); +ExecuteQuery("alter table vtiger_invoice drop column salestax"); + +//Contact Name is not shown in Notes ListView because of cvcolumnlist entry as now we need lastname in the query result +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactdetails:lastname:lastname:Notes_Contact_Name:V' where columnname='vtiger_notes:contact_id:contact_id:Notes_Contact_Name:I'"); + +//Missed Activity History entry in Potential related list has been added +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",2,9,'get_history',8,'Activity History',0)"); + +//Change the commission rate from decimal(3,3) to decimal(7,3) in products +ExecuteQuery("alter table vtiger_products modify column commissionrate decimal(7,3)"); + +//In inventory notification mails, line breaks are not propter. we have to replace \n with
    +$res = $adb->query("select notificationid, notificationbody from vtiger_inventorynotification"); +for($i=0;$i<$adb->num_rows($res);$i++) +{ + $notificationid = $adb->query_result($res,$i,'notificationid'); + $notificationbody = $adb->query_result($res,$i,'notificationbody'); + //Replace \n with
    + $notificationbody = str_replace("\n","
    ",$notificationbody); + ExecuteQuery("update vtiger_inventorynotification set notificationbody='$notificationbody' where notificationid=$notificationid"); +} + +//Move all the Potential custom fields into corresponding block(2) as they are placed in description block +ExecuteQuery("update vtiger_field set block=(select blockid from vtiger_blocks where tabid=2 and blocklabel='LBL_CUSTOM_INFORMATION') where tabid=2 and fieldname like 'cf_%'"); + +//Calendar - End Time fieldlabel has one extra space so that it comes twice in columns list in customview creation +ExecuteQuery("update vtiger_field set fieldlabel='End Time' where tabid=9 and fieldname='time_end'"); + +//change the cntactivityrel table primary key, add relatedlist entries then only related to, contact will be displayed +$adb->query("alter table vtiger_cntactivityrel drop primary key"); +$adb->query("alter table vtiger_cntactivityrel add primary key (contactid, activityid), ENGINE=InnoDB"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",9,0,'get_users',1,'Users',0)"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",9,4,'get_contacts',2,'Contacts',0)"); + +//Added activity history and Invoice status history in Invoice relatedlist +ExecuteQuery("insert into vtiger_relatedlists values (".$adb->getUniqueID('vtiger_relatedlists').",23,9,'get_history',3,'Activity History',0), (".$adb->getUniqueID('vtiger_relatedlists').",23,0,'get_invoicestatushistory',4,'Invoice Status History',0)"); + +//Changed the activity reminder notification as active +ExecuteQuery("update vtiger_notificationscheduler set active=1 where schedulednotificationname='LBL_ACTIVITY_REMINDER_DESCRIPTION'"); + +//Change Event Status values Planned, Held, Not Held as non editable +ExecuteQuery("update vtiger_eventstatus set presence=0 where eventstatus in ('Planned','Held','Not Held')"); + +//If engine is MyISAM then order is changing regularly so we have to change the engine to InnoDB +ExecuteQuery("alter table vtiger_industry engine=InnoDB"); +ExecuteQuery("alter table vtiger_industry modify column industry varchar(200) NOT NULL"); +$adb->query("alter table vtiger_industry drop index Industry_UK0"); +$adb->query("alter table vtiger_industry add UNIQUE index industry_industry_idx(industry)"); + +//we have removed contactid from products so that in cvcolumnlist we have to remove this column +ExecuteQuery("delete from vtiger_cvcolumnlist where columnname='vtiger_products:contactid:contact_id:Products_Contact_Name:I'"); + +//Make the Closed Lost as non editable in Sales Stage +ExecuteQuery("update vtiger_sales_stage set presence=0 where sales_stage='Closed Lost'"); + +//Added to fix the issues in group to entity relationship +$adb->query("DELETE FROM vtiger_leadgrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_leadgrouprelation DROP FOREIGN KEY fk_1_vtiger_leadgrouprelation"); +$adb->query("ALTER TABLE vtiger_leadgrouprelation DROP FOREIGN KEY fk_2_vtiger_leadgrouprelation"); + +$adb->query("DELETE FROM vtiger_accountgrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_accountgrouprelation DROP FOREIGN KEY fk_1_vtiger_accountgrouprelation"); +$adb->query("ALTER TABLE vtiger_accountgrouprelation DROP FOREIGN KEY fk_2_vtiger_accountgrouprelation"); + +$adb->query("DELETE FROM vtiger_contactgrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_contactgrouprelation DROP FOREIGN KEY fk_1_vtiger_contactgrouprelation"); +$adb->query("ALTER TABLE vtiger_contactgrouprelation DROP FOREIGN KEY fk_2_vtiger_contactgrouprelation"); + +$adb->query("DELETE FROM vtiger_potentialgrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_potentialgrouprelation DROP FOREIGN KEY fk_1_vtiger_potentialgrouprelation"); +$adb->query("ALTER TABLE vtiger_potentialgrouprelation DROP FOREIGN KEY fk_2_vtiger_potentialgrouprelation"); + +$adb->query("DELETE FROM vtiger_campaigngrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_campaigngrouprelation DROP FOREIGN KEY fk_1_vtiger_campaigngrouprelation"); +$adb->query("ALTER TABLE vtiger_campaigngrouprelation DROP FOREIGN KEY fk_2_vtiger_campaigngrouprelation"); + +$adb->query("DELETE FROM vtiger_activitygrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_activitygrouprelation DROP FOREIGN KEY fk_1_vtiger_activitygrouprelation"); +$adb->query("ALTER TABLE vtiger_activitygrouprelation DROP FOREIGN KEY fk_2_vtiger_activitygrouprelation"); + +$adb->query("DELETE FROM vtiger_ticketgrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_ticketgrouprelation DROP FOREIGN KEY fk_1_vtiger_ticketgrouprelation"); +$adb->query("ALTER TABLE vtiger_ticketgrouprelation DROP FOREIGN KEY fk_2_vtiger_ticketgrouprelation"); + +$adb->query("DELETE FROM vtiger_sogrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_sogrouprelation DROP FOREIGN KEY fk_1_vtiger_sogrouprelation"); +$adb->query("ALTER TABLE vtiger_sogrouprelation DROP FOREIGN KEY fk_2_vtiger_sogrouprelation"); + +$adb->query("DELETE FROM vtiger_quotegrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_quotegrouprelation DROP FOREIGN KEY fk_1_vtiger_quotegrouprelation"); +$adb->query("ALTER TABLE vtiger_quotegrouprelation DROP FOREIGN KEY fk_2_vtiger_quotegrouprelation"); + +$adb->query("DELETE FROM vtiger_pogrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_pogrouprelation DROP FOREIGN KEY fk_1_vtiger_pogrouprelation"); +$adb->query("ALTER TABLE vtiger_pogrouprelation DROP FOREIGN KEY fk_2_vtiger_pogrouprelation"); + +$adb->query("DELETE FROM vtiger_invoicegrouprelation where groupname is NULL or groupname = ''"); +$adb->query("ALTER TABLE vtiger_invoicegrouprelation DROP FOREIGN KEY fk_1_vtiger_invoicegrouprelation"); +$adb->query("ALTER TABLE vtiger_invoicegrouprelation DROP FOREIGN KEY fk_2_vtiger_invoicegrouprelation"); + + + + +ExecuteQuery("ALTER TABLE vtiger_leadgrouprelation ADD CONSTRAINT fk_1_vtiger_leadgrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_leadgrouprelation ADD CONSTRAINT fk_2_vtiger_leadgrouprelation FOREIGN KEY (leadid) REFERENCES vtiger_leaddetails(leadid) ON DELETE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_accountgrouprelation ADD CONSTRAINT fk_1_vtiger_accountgrouprelation FOREIGN KEY (accountid) REFERENCES vtiger_account(accountid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_accountgrouprelation ADD CONSTRAINT fk_2_vtiger_accountgrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_contactgrouprelation ADD CONSTRAINT fk_1_vtiger_contactgrouprelation FOREIGN KEY (contactid) REFERENCES vtiger_contactdetails(contactid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_contactgrouprelation ADD CONSTRAINT fk_2_vtiger_contactgrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_potentialgrouprelation ADD CONSTRAINT fk_1_vtiger_potentialgrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_potentialgrouprelation ADD CONSTRAINT fk_2_vtiger_potentialgrouprelation FOREIGN KEY (potentialid) REFERENCES vtiger_potential(potentialid) ON DELETE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_campaigngrouprelation ADD CONSTRAINT fk_1_vtiger_campaigngrouprelation FOREIGN KEY (campaignid) REFERENCES vtiger_campaign(campaignid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_campaigngrouprelation ADD CONSTRAINT fk_2_vtiger_campaigngrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_activitygrouprelation ADD CONSTRAINT fk_1_vtiger_activitygrouprelation FOREIGN KEY (activityid) REFERENCES vtiger_activity(activityid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_activitygrouprelation ADD CONSTRAINT fk_2_vtiger_activitygrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_ticketgrouprelation ADD CONSTRAINT fk_1_vtiger_ticketgrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_ticketgrouprelation ADD CONSTRAINT fk_2_vtiger_ticketgrouprelation FOREIGN KEY (ticketid) REFERENCES vtiger_troubletickets(ticketid) ON DELETE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_sogrouprelation ADD CONSTRAINT fk_1_vtiger_sogrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_sogrouprelation ADD CONSTRAINT fk_2_vtiger_sogrouprelation FOREIGN KEY (salesorderid) REFERENCES vtiger_salesorder(salesorderid) ON DELETE CASCADE"); + +ExecuteQuery("ALTER TABLE vtiger_quotegrouprelation ADD CONSTRAINT fk_1_vtiger_quotegrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_quotegrouprelation ADD CONSTRAINT fk_2_vtiger_quotegrouprelation FOREIGN KEY (quoteid) REFERENCES vtiger_quotes(quoteid) ON DELETE CASCADE"); + + +ExecuteQuery("ALTER TABLE vtiger_pogrouprelation ADD CONSTRAINT fk_1_vtiger_pogrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_pogrouprelation ADD CONSTRAINT fk_2_vtiger_pogrouprelation FOREIGN KEY (purchaseorderid) REFERENCES vtiger_purchaseorder(purchaseorderid) ON DELETE CASCADE"); + + +ExecuteQuery("ALTER TABLE vtiger_invoicegrouprelation ADD CONSTRAINT fk_1_vtiger_invoicegrouprelation FOREIGN KEY (groupname) REFERENCES vtiger_groups(groupname) ON UPDATE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_invoicegrouprelation ADD CONSTRAINT fk_2_vtiger_invoicegrouprelation FOREIGN KEY (invoiceid) REFERENCES vtiger_invoice(invoiceid) ON DELETE CASCADE"); + +//For emails listview, we have to update the column sender +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_crmentity:smownerid:assigned_user_id:Emails_Sender:V' where columnname='vtiger_crmentity:smownerid:assigned_user_id:Emails_Assigned_To:V'"); + +//if is_admin is set as 0 then we have to update as off and update status as Active if the status is NULL +ExecuteQuery("update vtiger_users set is_admin='off' where is_admin='0'"); +ExecuteQuery("update vtiger_users set status='Active' where status is NULL"); + +//Update the City, State, Zip and Country to Mailing City, State, Zip and Country +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactaddress:mailingcity:mailingcity:Contacts_Mailing_City:V' where columnname='vtiger_contactaddress:mailingcity:mailingcity:Contacts_City:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactaddress:mailingstate:mailingstate:Contacts_Mailing_State:V' where columnname='vtiger_contactaddress:mailingstate:mailingstate:Contacts_State:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactaddress:mailingzip:mailingzip:Contacts_Mailing_Zip:V' where columnname='vtiger_contactaddress:mailingzip:mailingzip:Contacts_Zip:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactaddress:mailingcountry:mailingcountry:Contacts_Mailing_Country:V' where columnname='vtiger_contactaddress:mailingcountry:mailingcountry:Contacts_Country:V'"); + +//Added Attachments and Quote stage history in Quotes relatedlist +ExecuteQuery("update vtiger_relatedlists set sequence=4 where tabid=20 and name='get_history'"); +ExecuteQuery("insert into vtiger_relatedlists values (".$adb->getUniqueID('vtiger_relatedlists').",20,0,'get_attachments',3,'Attachments',0), (".$adb->getUniqueID('vtiger_relatedlists').",20,0,'get_quotestagehistory',5,'Quote Stage History',0)"); + +//Added SalesOrder Status History in SalesOrder relatedlist +ExecuteQuery("insert into vtiger_relatedlists values (".$adb->getUniqueID('vtiger_relatedlists').",22,0,'get_sostatushistory',5,'SalesOrder Status History',0)"); + +//Added PurchaseOrder Status History in PurchaseOrder relatedlist +ExecuteQuery("insert into vtiger_relatedlists values (".$adb->getUniqueID('vtiger_relatedlists').",21,0,'get_postatushistory',4,'PurchaseOrder Status History',0)"); + +//Update SalesOrder Id as SalesOrder No for default All SalesOrder customview (only All customview has this field) +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_crmentity:crmid::SalesOrder_Order_No:I' where columnname='vtiger_crmentity:crmid::SalesOrder_Order_Id:I'"); + +//Update PurchaseOrder Id as Purchase No for default All PurchaseOrder customview (only All customview has this field) +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_crmentity:crmid::PurchaseOrder_Order_No:I' where columnname='vtiger_crmentity:crmid::PurchaseOrder_Order_Id:I'"); + + + + + + +$query = "select * from vtiger_emaildetails"; +$result = $adb->query($query); +$find_array = Array('<','>'); +$replace_array = Array('<','>'); +for($i = 0; $i < $adb->num_rows($result); $i++) +{ + $emailID = $adb->query_result($result,$i,'emailid'); + $from_email = $adb->query_result($result,$i,'from_email'); + $to_email = $adb->query_result($result,$i,'to_email'); + $cc_email = $adb->query_result($result,$i,'cc_email'); + $bcc_email = $adb->query_result($result,$i,'bcc_email'); + $assigned_user_email = $adb->query_result($result,$i,'assigned_user_email'); + $replace_from_email = str_replace($find_array,$replace_array,$from_email); + $replace_to_email = str_replace($find_array,$replace_array,$to_email); + $replace_cc_email = str_replace($find_array,$replace_array,$cc_email); + $replace_bcc_email = str_replace($find_array,$replace_array,$bcc_email); + $replace_assigned_user_email = str_replace($find_array,$replace_array,$assigned_user_email); + $query = "update vtiger_emaildetails set from_email='".$replace_from_email."', to_email='".$replace_to_email."', cc_email='".$replace_cc_email."' ,bcc_email='".$assigned_user_email."' where emailid=".$emailID; + //echo $query.'
    '; + ExecuteQuery($query); +} + +ExecuteQuery("delete from vtiger_selectcolumn where columnname='vtiger_contactdetailsProducts:lastname:Products_Contact_Name:contact_id:I'"); +ExecuteQuery("delete from vtiger_selectcolumn where columnname='vtiger_invoice:notes:Invoice_Notes:notes:V'"); +ExecuteQuery("delete from vtiger_selectcolumn where columnname='vtiger_invoice:invoiceterms:Invoice_Invoice_Terms:invoiceterms:V'"); + +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_leaddetails:email:Leads_Email:email:V' where columnname='vtiger_leaddetails:email:Leads_Email:email:E'"); + + + +//to remove Export from Emails Module Under Profiles +ExecuteQuery("delete from vtiger_profile2utility where tabid=10"); + + +//ALTER TABLE Queries + +ExecuteQuery("alter table vtiger_accountbillads change column city bill_city varchar(30)"); +ExecuteQuery("alter table vtiger_accountbillads change column code bill_code varchar(30)"); +ExecuteQuery("alter table vtiger_accountbillads change column country bill_country varchar(30)"); +ExecuteQuery("alter table vtiger_accountbillads change column state bill_state varchar(30)"); +ExecuteQuery("alter table vtiger_accountbillads change column street bill_street varchar(250)"); +ExecuteQuery("alter table vtiger_accountbillads change column pobox bill_pobox varchar(30)"); + +ExecuteQuery("alter table vtiger_accountshipads change column city ship_city varchar(30)"); +ExecuteQuery("alter table vtiger_accountshipads change column code ship_code varchar(30)"); +ExecuteQuery("alter table vtiger_accountshipads change column country ship_country varchar(30)"); +ExecuteQuery("alter table vtiger_accountshipads change column state ship_state varchar(30)"); +ExecuteQuery("alter table vtiger_accountshipads change column street ship_street varchar(250)"); +ExecuteQuery("alter table vtiger_accountshipads change column pobox ship_pobox varchar(30)"); + + +//Field Table Update Queries +ExecuteQuery("update vtiger_field set columnname='bill_city' where columnname='city' and tablename='vtiger_accountbillads'"); +ExecuteQuery("update vtiger_field set columnname='bill_code' where columnname='code' and tablename='vtiger_accountbillads'"); +ExecuteQuery("update vtiger_field set columnname='bill_country' where columnname='country' and tablename='vtiger_accountbillads'"); +ExecuteQuery("update vtiger_field set columnname='bill_state' where columnname='state' and tablename='vtiger_accountbillads'"); +ExecuteQuery("update vtiger_field set columnname='bill_street' where columnname='street' and tablename='vtiger_accountbillads'"); +ExecuteQuery("update vtiger_field set columnname='bill_pobox' where columnname='pobox' and tablename='vtiger_accountbillads'"); + + +ExecuteQuery("update vtiger_field set columnname='ship_city' where columnname='city' and tablename='vtiger_accountshipads'"); +ExecuteQuery("update vtiger_field set columnname='ship_code' where columnname='code' and tablename='vtiger_accountshipads'"); +ExecuteQuery("update vtiger_field set columnname='ship_country' where columnname='country' and tablename='vtiger_accountshipads'"); +ExecuteQuery("update vtiger_field set columnname='ship_state' where columnname='state' and tablename='vtiger_accountshipads'"); +ExecuteQuery("update vtiger_field set columnname='ship_street' where columnname='street' and tablename='vtiger_accountshipads'"); +ExecuteQuery("update vtiger_field set columnname='ship_pobox' where columnname='pobox' and tablename='vtiger_accountshipads'"); + + +//CustomView Queries +//Available in Populate CustomView.php so migration for that particular field +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_city:bill_city:Accounts_Billing_City:V' where columnname='vtiger_accountbillads:city:bill_city:Accounts_City:V'"); + +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_city:bill_city:Accounts_Billing_City:V' where columnname='vtiger_accountbillads:city:bill_city:Accounts_Billing_City:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_code:bill_code:Accounts_Billing_Code:V' where columnname='vtiger_accountbillads:code:bill_code:Accounts_Billing_Code:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_country:bill_country:Accounts_Billing_Country:V' where columnname='vtiger_accountbillads:country:bill_country:Accounts_Billing_Country:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_state:bill_state:Accounts_Billing_State:V' where columnname='vtiger_accountbillads:state:bill_state:Accounts_Billing_State:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_street:bill_street:Accounts_Billing_Address:V' where columnname='vtiger_accountbillads:street:bill_street:Accounts_Billing_Address:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountbillads:bill_pobox:bill_pobox:Accounts_Billing_Po_Box:V' where columnname='vtiger_accountbillads:pobox:bill_pobox:Accounts_Billing_Po_Box:V'"); + + + +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountshipads:ship_street:ship_street:Accounts_Shipping_Address:V' where columnname='vtiger_accountshipads:street:ship_street:Accounts_Shipping_Address:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountshipads:ship_pobox:ship_pobox:Accounts_Shipping_Po_Box:V' where columnname='vtiger_accountshipads:pobox:ship_pobox:Accounts_Shipping_Po_Box:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountshipads:ship_city:ship_city:Accounts_Shipping_City:V' where columnname='vtiger_accountshipads:city:ship_city:Accounts_Shipping_City:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountshipads:ship_state:ship_state:Accounts_Shipping_State:V' where columnname='vtiger_accountshipads:state:ship_state:Accounts_Shipping_State:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountshipads:ship_code:ship_code:Accounts_Shipping_Code:V' where columnname='vtiger_accountshipads:code:ship_code:Accounts_Shipping_Code:V'"); +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_accountshipads:ship_country:ship_country:Accounts_Shipping_Country:V' where columnname='vtiger_accountshipads:country:ship_country:Accounts_Shipping_Country:V'"); + +//CustomView Advanced Filter + +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountbillads:bill_city:bill_city:Accounts_Billing_City:V' where columnname='vtiger_accountbillads:city:bill_city:Accounts_Billing_City:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountbillads:bill_code:bill_code:Accounts_Billing_Code:V' where columnname='vtiger_accountbillads:code:bill_code:Accounts_Billing_Code:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountbillads:bill_country:bill_country:Accounts_Billing_Country:V' where columnname='vtiger_accountbillads:country:bill_country:Accounts_Billing_Country:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountbillads:bill_state:bill_state:Accounts_Billing_State:V' where columnname='vtiger_accountbillads:state:bill_state:Accounts_Billing_State:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountbillads:bill_street:bill_street:Accounts_Billing_Address:V' where columnname='vtiger_accountbillads:street:bill_street:Accounts_Billing_Address:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountbillads:bill_pobox:bill_pobox:Accounts_Billing_Po_Box:V' where columnname='vtiger_accountbillads:pobox:bill_pobox:Accounts_Billing_Po_Box:V'"); + + + +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountshipads:ship_street:ship_street:Accounts_Shipping_Address:V' where columnname='vtiger_accountshipads:street:ship_street:Accounts_Shipping_Address:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountshipads:ship_pobox:ship_pobox:Accounts_Shipping_Po_Box:V' where columnname='vtiger_accountshipads:pobox:ship_pobox:Accounts_Shipping_Po_Box:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountshipads:ship_city:ship_city:Accounts_Shipping_City:V' where columnname='vtiger_accountshipads:city:ship_city:Accounts_Shipping_City:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountshipads:ship_state:ship_state:Accounts_Shipping_State:V' where columnname='vtiger_accountshipads:state:ship_state:Accounts_Shipping_State:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountshipads:ship_code:ship_code:Accounts_Shipping_Code:V' where columnname='vtiger_accountshipads:code:ship_code:Accounts_Shipping_Code:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_accountshipads:ship_country:ship_country:Accounts_Shipping_Country:V' where columnname='vtiger_accountshipads:country:ship_country:Accounts_Shipping_Country:V'"); + + +//Reports Columns +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountbillads:bill_country:Accounts_Billing_Country:bill_country:V' where columnname='vtiger_accountbillads:country:Accounts_Billing_Country:bill_country:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountbillads:bill_city:Accounts_Billing_City:bill_city:V' where columnname='vtiger_accountbillads:city:Accounts_Billing_City:bill_city:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountbillads:bill_pobox:Accounts_Billing_Po_Box:bill_pobox:V' where columnname='vtiger_accountbillads:pobox:Accounts_Billing_Po_Box:bill_pobox:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountbillads:bill_street:Accounts_Billing_Address:bill_street:V' where columnname='vtiger_accountbillads:street:Accounts_Billing_Address:bill_street:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountbillads:bill_code:Accounts_Billing_Code:bill_code:V' where columnname='vtiger_accountbillads:code:Accounts_Billing_Code:bill_code:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountbillads:bill_state:Accounts_Billing_State:bill_state:V' where columnname='vtiger_accountbillads:state:Accounts_Billing_State:bill_state:V'"); + + +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountshipads:ship_city:Accounts_Shipping_City:ship_city:V' where columnname='vtiger_accountshipads:city:Accounts_Shipping_City:ship_city:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountshipads:ship_pobox:Accounts_Shipping_Po_Box:ship_pobox:V' where columnname='vtiger_accountshipads:pobox:Accounts_Shipping_Po_Box:ship_pobox:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountshipads:ship_street:Accounts_Shipping_Address:ship_street:V' where columnname='vtiger_accountshipads:street:Accounts_Shipping_Address:ship_street:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountshipads:ship_country:Accounts_Shipping_Country:ship_country:V' where columnname='vtiger_accountshipads:country:Accounts_Shipping_Country:ship_country:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountshipads:ship_code:Accounts_Shipping_Code:ship_code:V' where columnname='vtiger_accountshipads:code:Accounts_Shipping_Code:ship_code:V'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountshipads:ship_state:Accounts_Shipping_State:ship_state:V' where columnname='vtiger_accountshipads:state:Accounts_Shipping_State:ship_state:V'"); + +//Reports Advanced Filter +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountbillads:bill_country:Accounts_Billing_Country:bill_country:V' where columnname='vtiger_accountbillads:country:Accounts_Billing_Country:bill_country:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountbillads:bill_city:Accounts_Billing_City:bill_city:V' where columnname='vtiger_accountbillads:city:Accounts_Billing_City:bill_city:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountbillads:bill_pobox:Accounts_Billing_Po_Box:bill_pobox:V' where columnname='vtiger_accountbillads:pobox:Accounts_Billing_Po_Box:bill_pobox:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountbillads:bill_street:Accounts_Billing_Address:bill_street:V' where columnname='vtiger_accountbillads:street:Accounts_Billing_Address:bill_street:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountbillads:bill_code:Accounts_Billing_Code:bill_code:V' where columnname='vtiger_accountbillads:code:Accounts_Billing_Code:bill_code:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountbillads:bill_state:Accounts_Billing_State:bill_state:V' where columnname='vtiger_accountbillads:state:Accounts_Billing_State:bill_state:V'"); + + +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountshipads:ship_city:Accounts_Shipping_City:ship_city:V' where columnname='vtiger_accountshipads:city:Accounts_Shipping_City:ship_city:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountshipads:ship_pobox:Accounts_Shipping_Po_Box:ship_pobox:V' where columnname='vtiger_accountshipads:pobox:Accounts_Shipping_Po_Box:ship_pobox:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountshipads:ship_street:Accounts_Shipping_Address:ship_street:V' where columnname='vtiger_accountshipads:street:Accounts_Shipping_Address:ship_street:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountshipads:ship_country:Accounts_Shipping_Country:ship_country:V' where columnname='vtiger_accountshipads:country:Accounts_Shipping_Country:ship_country:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountshipads:ship_code:Accounts_Shipping_Code:ship_code:V' where columnname='vtiger_accountshipads:code:Accounts_Shipping_Code:ship_code:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountshipads:ship_state:Accounts_Shipping_State:ship_state:V' where columnname='vtiger_accountshipads:state:Accounts_Shipping_State:ship_state:V'"); + + +//FieldLabel of Phone Field for Contacts has been changed to Other Phone + +ExecuteQuery("update vtiger_field set fieldlabel = 'Other Phone' where tablename='vtiger_contactsubdetails' and columnname='otherphone'"); + +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactsubdetails:otherphone:otherphone:Contacts_Other_Phone:V' where columnname='vtiger_contactsubdetails:otherphone:otherphone:Contacts_Phone:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_contactsubdetails:otherphone:otherphone:Contacts_Other_Phone:V' where columnname='vtiger_contactsubdetails:otherphone:otherphone:Contacts_Phone:V'"); + + +//get the values from vtiger_selectcolumn with columnname like 'vtiger_contactdetails%' get the columnname value check for the field Phone and change the FieldLabel from Contacts_Phone to Contacts_Other_Phone -- To be done + +$query1 = "select columnname from vtiger_selectcolumn where columnname like 'vtiger_contactdetails%' and columnname like '%Contacts_Phone%'"; +$result = $adb->query($query1); +for($i = 0;$i < $adb->num_rows($result);$i++) +{ + $columnname = $adb->query_result($result,$i,'columnname'); + $update_columnname = str_replace('Contacts_Phone','Contacts_Other_Phone',$columnname); + $query = "update vtiger_selectcolumn set columnname='$update_columnname' where columnname='$columnname'"; + $adb->query($query); +} + +//get the values from vtiger_relcriteria with columnname like 'vtiger_contactdetails%' get the columnname value check for the field Phone and change the FieldLabel from Contacts_Phone to Contacts_Other_Phone-- To be done +$query1 = "select columnname from vtiger_relcriteria where columnname like 'vtiger_contactdetails%' and columnname like '%Contacts_Phone%'"; +$result = $adb->query($query1); +for($i = 0;$i < $adb->num_rows($result);$i++) +{ + $columnname = $adb->query_result($result,$i,'columnname'); + $update_columnname = str_replace('Contacts_Phone','Contacts_Other_Phone',$columnname); + $query = "update vtiger_relcriteria set columnname='$update_columnname' where columnname='$columnname'"; + $adb->query($query); +} + +//Removed the default value Mr in salutation +ExecuteQuery("alter table vtiger_contactdetails change column salutation salutation varchar(50)"); +ExecuteQuery("update vtiger_campaignstatus set campaignstatus='Completed' where campaignstatus='Complete'"); +ExecuteQuery("update vtiger_crmentity set setype='PurchaseOrder' where setype='Orders'"); +ExecuteQuery("update vtiger_crmentity set setype='PurchaseOrder Attachment' where setype='Orders Attachment'"); +ExecuteQuery("update vtiger_crmentity set setype='Vendors' where setype='Vendor'"); +ExecuteQuery("update vtiger_customview set entitytype='Vendors' where entitytype='Vendor'"); + +//Fixed customview related changes +//Calendar - Related To +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_seactivityrel:crmid:parent_id:Calendar_Related_to:V' where columnname='vtiger_seactivityrel:crmid:parent_id:Calendar_Related_to:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_seactivityrel:crmid:parent_id:Calendar_Related_to:V' where columnname='vtiger_seactivityrel:crmid:parent_id:Calendar_Related_to:I'"); + +//Calendar - Start Date (Date & Time) +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_activity:date_start:date_start:Calendar_Start_Date:DT' where columnname='vtiger_activity:date_start:date_start:Calendar_Start_Date_&_Time:DT' or columnname = 'activity:date_start:date_start:Activities_Start_Date_&_Time:DT'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_activity:date_start:date_start:Calendar_Start_Date:DT' where columnname='vtiger_activity:date_start:date_start:Calendar_Start_Date_&_Time:DT' or columnname = 'activity:date_start:date_start:Activities_Start_Date_&_Time:DT'"); + +//Notes - Related To +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_senotesrel:crmid:parent_id:Notes_Related_to:V' where columnname='vtiger_senotesrel:crmid:parent_id:Notes_Related_to:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_senotesrel:crmid:parent_id:Notes_Related_to:V' where columnname='vtiger_senotesrel:crmid:parent_id:Notes_Related_to:I'"); + +//Notes - Contact Name +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactdetails:lastname:lastname:Notes_Contact_Name:V' where columnname='vtiger_notes:contact_id:contact_id:Notes_Contact_Name:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_contactdetails:lastname:lastname:Notes_Contact_Name:V' where columnname='vtiger_notes:contact_id:contact_id:Notes_Contact_Name:V'"); + +//Notes - title +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_notes:title:notes_title:Notes_Title:V' where columnname='vtiger_notes:title:title:Notes_Subject:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_notes:title:notes_title:Notes_Title:V' where columnname='vtiger_notes:title:title:Notes_Subject:V'"); + +//In Products - Related To and Contact should be deleted +ExecuteQuery("delete from vtiger_cvcolumnlist where columnname='vtiger_seproductsrel:crmid:parent_id:Products_Related_to:I'"); +ExecuteQuery("delete from vtiger_cvadvfilter where columnname='vtiger_seproductsrel:crmid:parent_id:Products_Related_to:I'"); +ExecuteQuery("delete from vtiger_cvcolumnlist where columnname='vtiger_products:contactid:contact_id:Products_Contact_Name:I'"); +ExecuteQuery("delete from vtiger_cvadvfilter where columnname='vtiger_products:contactid:contact_id:Products_Contact_Name:I'"); + +//For vendors module we have to update the module name as Vendors from Vendor +$result = $adb->query("select vtiger_cvcolumnlist.cvid, vtiger_cvcolumnlist.columnname from vtiger_customview inner join vtiger_cvcolumnlist on vtiger_customview.cvid = vtiger_cvcolumnlist.cvid where vtiger_customview.entitytype='Vendors' and columnname != ''"); +for($i=0;$i<$adb->num_rows($result);$i++) +{ + $cvid = $adb->query_result($result,$i,'cvid'); + $columnname = $adb->query_result($result,$i,'columnname'); + $new_columnname = str_replace(':Vendor_',':Vendors_',$columnname); + + $adb->query("update vtiger_cvcolumnlist set columnname='$new_columnname' where columnname='$columnname'"); + $adb->query("update vtiger_cvadvfilter set columnname='$new_columnname' where columnname='$columnname'"); +} + +//Vendor - instead of street, treet has been saved previously +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_vendor:street:street:Vendors_Street:V' where columnname='vtiger_vendor:street:treet:Vendors_Street:V'"); + +//Accounts - Other Email +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_account:email2:email2:Accounts_Other_Email:V' where columnname='vtiger_account:email2:email2:Accounts_Other_Email:E'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_account:email2:email2:Accounts_Other_Email:V' where columnname='vtiger_account:email2:email2:Accounts_Other_Email:E'"); + +//Accounts - SIC Code +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_account:siccode:siccode:Accounts_SIC_Code:V' where columnname='vtiger_account:siccode:siccode:Accounts_SIC_Code:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_account:siccode:siccode:Accounts_SIC_Code:V' where columnname='vtiger_account:siccode:siccode:Accounts_SIC_Code:I'"); + +//Account - Member Of +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_account:parentid:account_id:Accounts_Member_Of:V' where columnname='vtiger_account:parentid:account_id:Accounts_Member_Of:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_account:parentid:account_id:Accounts_Member_Of:V' where columnname='vtiger_account:parentid:account_id:Accounts_Member_Of:I'"); + +//Account - Email +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_account:email1:email1:Accounts_Email:V' where columnname='vtiger_account:email1:email1:Accounts_Email:E'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_account:email1:email1:Accounts_Email:V' where columnname='vtiger_account:email1:email1:Accounts_Email:E'"); + +//Contact - Email +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_contactdetails:email:email:Contacts_Email:V' where columnname='vtiger_contactdetails:email:email:Contacts_Email:E'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_contactdetails:email:email:Contacts_Email:V' where columnname='vtiger_contactdetails:email:email:Contacts_Email:E'"); + +//Leads - Email +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_leaddetails:email:email:Leads_Email:V' where columnname='vtiger_leaddetails:email:email:Leads_Email:E'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_leaddetails:email:email:Leads_Email:V' where columnname='vtiger_leaddetails:email:email:Leads_Email:E'"); + +//Tickect - Related To +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_to:V' where columnname='vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_to:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_to:V' where columnname='vtiger_troubletickets:parent_id:parent_id:HelpDesk_Related_to:I'"); + +//Ticket - Product Name +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_troubletickets:product_id:product_id:HelpDesk_Product_Name:V' where columnname='vtiger_troubletickets:product_id:product_id:HelpDesk_Product_Name:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_troubletickets:product_id:product_id:HelpDesk_Product_Name:V' where columnname='vtiger_troubletickets:product_id:product_id:HelpDesk_Product_Name:I'"); + +//Invoice - Sales Order +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:V' where columnname='vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:V' where columnname='vtiger_invoice:salesorderid:salesorder_id:Invoice_Sales_Order:I'"); + +//Product - Active +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_products:discontinued:discontinued:Products_Product_Active:C' where columnname='vtiger_products:discontinued:discontinued:Products_Product_Active:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_products:discontinued:discontinued:Products_Product_Active:C' where columnname='vtiger_products:discontinued:discontinued:Products_Product_Active:V'"); + +//Product - Vendor Name +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_products:vendor_id:vendor_id:Products_Vendor_Name:V' where columnname='vtiger_products:vendor_id:vendor_id:Products_Vendor_Name:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_products:vendor_id:vendor_id:Products_Vendor_Name:V' where columnname='vtiger_products:vendor_id:vendor_id:Products_Vendor_Name:I'"); + +//Product - Product Code (Part Number) +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_products:productcode:productcode:Products_Part_Number:V' where columnname='vtiger_products:productcode:productcode:Products_Product_Code:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_products:productcode:productcode:Products_Part_Number:V' where columnname='vtiger_products:productcode:productcode:Products_Product_Code:V'"); + +//Purchase Order - Vendor Name +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:V' where columnname='vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:V' where columnname='vtiger_purchaseorder:vendorid:vendor_id:PurchaseOrder_Vendor_Name:I'"); + +//Purchase Order - Due Date +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_purchaseorder:duedate:duedate:PurchaseOrder_Due_Date:D' where columnname='vtiger_purchaseorder:duedate:duedate:PurchaseOrder_Due_Date:V'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_purchaseorder:duedate:duedate:PurchaseOrder_Due_Date:D' where columnname='vtiger_purchaseorder:duedate:duedate:PurchaseOrder_Due_Date:V'"); + +//SalesOrder - Potential Name +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_salesorder:potentialid:potential_id:SalesOrder_Potential_Name:V' where columnname='vtiger_salesorder:potentialid:potential_id:SalesOrder_Potential_Name:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_salesorder:potentialid:potential_id:SalesOrder_Potential_Name:V' where columnname='vtiger_salesorder:potentialid:potential_id:SalesOrder_Potential_Name:I'"); + +//SalesOrder - Quote Name +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_salesorder:quoteid:quote_id:SalesOrder_Quote_Name:V' where columnname='vtiger_salesorder:quoteid:quote_id:SalesOrder_Quote_Name:I'"); +ExecuteQuery("update vtiger_cvadvfilter set columnname='vtiger_salesorder:quoteid:quote_id:SalesOrder_Quote_Name:V' where columnname='vtiger_salesorder:quoteid:quote_id:SalesOrder_Quote_Name:I'"); + + +//Products Related To field deleted from vtiger_selectcolumn +ExecuteQuery("delete from vtiger_selectcolumn where columnname ='vtiger_seproductsrel:crmid:Products_Related_To:parent_id:I'"); + +//cvstdfilter table is in MyISAM engine so that the order of diplay will not be same in all time +$adb->query("alter table vtiger_cvstdfilter engine=InnoDB"); + +//we have to set set permission as 3 in vtiger_def_org_share as the Calendar is private +ExecuteQuery("update vtiger_def_org_share set permission=3 where tabid=16"); + + +//Query added to delete custom field entries available only in field table and not in customfield tables +$customtables_array = Array('vtiger_accountscf','vtiger_campaignscf','vtiger_contactscf','vtiger_invoicecf','vtiger_leadscf','vtiger_potentialscf','vtiger_pricebookcf','vtiger_productcf','vtiger_purchaseordercf','vtiger_quotescf','vtiger_salesordercf','vtiger_ticketcf','vtiger_vendorcf'); + +foreach($customtables_array as $customfieldtable) +{ + + $sql = "select fieldname,tablename,columnname,fieldid from vtiger_field where tablename='$customfieldtable'"; + $result = $adb->query($sql); + + $columns=$adb->getColumnNames($customfieldtable); + for($i=0;$i < $adb->num_rows($result); $i++) + { + $columnname = $adb->query_result($result,$i,'columnname'); + if(!in_array($columnname,$columns)) + { + $fieldID = $adb->query_result($result,$i,'fieldid'); + $query = "delete from vtiger_field where fieldid=".$fieldID; + $result1 = $adb->query($query); + } + } +} + + +$tables_array = Array( + "vtiger_cvcolumnlist"=>"columnname", + "vtiger_cvstdfilter"=>"columnname", + "vtiger_cvadvfilter"=>"columnname", + "vtiger_selectcolumn"=>"columnname", + "vtiger_relcriteria"=>"columnname", + "vtiger_reportsortcol"=>"columnname", + "vtiger_reportdatefilter"=>"datecolumnname", + "vtiger_reportsummary"=>"columnname", + ); + + +foreach($tables_array as $tablename => $columnname) +{ + $query = "select $columnname from $tablename where $columnname like '%:cf_%'"; + $result = $adb->query($query); + $noofrows = $adb->num_rows($result); + + for($i=0;$i<$noofrows;$i++) + { + //First get the fieldname from the result + $col_value = $adb->query_result($result,$i,$columnname); + $fieldname = substr($col_value,strpos($col_value,':cf_')+1,6); + + //Now check whether this field is available in field table + $sql1 = "select fieldid from vtiger_field where fieldname='".$fieldname."'"; + $result1 = $adb->query($sql1); + $noofrows1 = $adb->num_rows($result1); + $fieldid = $adb->query_result($result1,0,"fieldid"); + + //if there is no field then we have to delete that field entries + if($noofrows1 == 0 && !isset($fieldid)) + { + //Now we have to delete that customfield from the $tablename + $adb->query("delete from $tablename where $columnname like '%:".$fieldname.":%'"); + } + } +} + + + + + + + +$migrationlog->debug("\n\nDB Changes from 5.0.3RC2 to 5.0.3 -------- Ends \n\n"); + + + +?> diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/504_to_510rc.php b/oss/vtiger/trunk/modules/Migration/DBChanges/504_to_510rc.php new file mode 100644 index 00000000..e7d44736 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/504_to_510rc.php @@ -0,0 +1,2031 @@ +debug("\n\nDB Changes from 5.0.4 to 5.1.0 RC -------- Starts \n\n"); + +require_once('include/events/include.inc'); +$em = new VTEventsManager($adb); +/* For the event api */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_eventhandlers (eventhandler_id int, event_name varchar(100), handler_path varchar(400), handler_class varchar(100), cond text, is_active boolean, primary key(eventhandler_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_eventhandler_module(eventhandler_module_id int, module_name VARCHAR(100), handler_class VARCHAR(100), PRIMARY KEY(eventhandler_module_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* Added new column actions to vtiger_relatedlists which tracks the type of actions allowed for that related list */ +if(!in_array('actions', $adb->getColumnNames('vtiger_relatedlists'))) { + ExecuteQuery("alter table vtiger_relatedlists add column actions VARCHAR(50) default ''"); +} + +$accounts_tab_id = getTabid('Accounts'); +$contacts_tab_id = getTabid('Contacts'); +$notes_tab_id = getTabid('Documents'); +$products_tab_id = getTabid('Products'); +$leads_tab_id = getTabid('Leads'); +$campaigns_tab_id = getTabid('Campaigns'); +$potentials_tab_id = getTabid('Potentials'); +$emails_tab_id = getTabid('Emails'); +$calendar_tab_id = getTabid('Calendar'); +$helpdesk_tab_id = getTabid('HelpDesk'); +$quotes_tab_id = getTabid('Quotes'); +$so_tab_id = getTabid('SalesOrder'); +$po_tab_id = getTabid('PurchaseOrder'); +$invoice_tab_id = getTabid('Invoice'); +$pb_tab_id = getTabid('PriceBooks'); +$vendors_tab_id = getTabid('Vendors'); + +// Accounts related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$accounts_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$accounts_tab_id AND related_tabid=$notes_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$accounts_tab_id AND related_tabid=$products_tab_id"); + +// Leads related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$leads_tab_idAND related_tabid=$notes_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$leads_tab_id AND related_tabid IN ($calendar_tab_id,$emails_tab_id)"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$leads_tab_id AND related_tabid IN ($products_tab_id,$campaigns_tab_id)"); + +// Contacts related list +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$contacts_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$contacts_tab_id AND related_tabid=$notes_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$contacts_tab_id AND related_tabid IN ($products_tab_id,$campaigns_tab_id)"); + +// Potentials related list +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$potentials_tab_id AND related_tabid IN ($calendar_tab_id,$quotes_tab_id,$so_tab_id)");; +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$potentials_tab_id AND related_tabid=$notes_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$potentials_tab_id AND related_tabid IN ($products_tab_id,$contacts_tab_id)"); + +// Products related list +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$products_tab_id AND related_tabid IN ($helpdesk_tab_id,$quotes_tab_id,$so_tab_id,$po_tab_id,$invoice_tab_id,$pb_tab_id)");; +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$products_tab_id AND related_tabid=$notes_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$products_tab_id AND related_tabid IN ($accounts_tab_id,$contacts_tab_id,$leads_tab_id,$potentials_tab_id)"); + +// Emails related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select,bulkmail' WHERE tabid=$emails_tab_id AND related_tabid=$contacts_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$emails_tab_id AND related_tabid=$notes_tab_id"); + +// Trouble Tickets related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$helpdesk_tab_id AND related_tabid IN ($notes_tab_id,$calendar_tab_id)"); + +// Products related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$pb_tab_id AND related_tabid IN ($products_tab_id)"); + +// Vendors related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$vendors_tab_id AND related_tabid IN ($emails_tab_id,$po_tab_id)");; +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$vendors_tab_id AND related_tabid=$products_tab_id"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='select' WHERE tabid=$vendors_tab_id AND related_tabid IN ($contacts_tab_id)"); + +// Quotes related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$quotes_tab_id AND related_tabid IN ($notes_tab_id)"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$quotes_tab_id AND related_tabid IN ($calendar_tab_id)"); + +// PO related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$po_tab_id AND related_tabid IN ($notes_tab_id)"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$po_tab_id AND related_tabid IN ($calendar_tab_id)"); + +// SO related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$so_tab_id AND related_tabid IN ($notes_tab_id)"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$so_tab_id AND related_tabid IN ($calendar_tab_id)"); + +// Invoices related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$invoice_tab_id AND related_tabid IN ($notes_tab_id)"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$invoice_tab_id AND related_tabid IN ($calendar_tab_id)"); + +// Campaigns related lists +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select' WHERE tabid=$campaigns_tab_id AND related_tabid IN ($contacts_tab_id,$leads_tab_id)"); +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add' WHERE tabid=$campaigns_tab_id AND related_tabid IN ($calendar_tab_id,$potentials_tab_id)"); + +require_once("modules/com_vtiger_workflow/include.inc"); +require_once("modules/com_vtiger_workflow/tasks/VTEntityMethodTask.inc"); +require_once("modules/com_vtiger_workflow/VTEntityMethodManager.inc"); +$emm = new VTEntityMethodManager($adb); + +/* Update the profileid, block id in sequence table, to the current highest value of block id used. */ +$tmp = $adb->getUniqueId('vtiger_blocks'); +$max_block_id_query = $adb->query("SELECT MAX(blockid) AS max_blockid FROM vtiger_blocks"); +if($adb->num_rows($max_block_id_query)>0){ + $max_block_id = $adb->query_result($max_block_id_query,0,"max_blockid"); + ExecuteQuery("UPDATE vtiger_blocks_seq SET id=".($max_block_id)); +} + +$tmp = $adb->getUniqueId('vtiger_profile'); +$max_profile_id_query = $adb->query("SELECT MAX(profileid) AS max_profileid FROM vtiger_profile"); +if($adb->num_rows($max_profile_id_query)>0){ + $max_profile_id = $adb->query_result($max_profile_id_query,0,"max_profileid"); + ExecuteQuery("UPDATE vtiger_profile_seq SET id=".($max_profile_id)); +} + +/* Migration queries to cleanup ui type 15, 16, 111 - + * 15 for Standard picklist types, + * 16 for non-standard picklist types which do not support Role-based picklist */ +ExecuteQuery("update vtiger_field set uitype = '15' where uitype='16'"); +ExecuteQuery("update vtiger_field set uitype = '15', typeofdata='V~M' where uitype='111'"); + +ExecuteQuery("update vtiger_field set uitype=16 where fieldname in " . + "('visibility','duration_minutes','recurringtype','hdnTaxType','recurring_frequency','activity_view','lead_view','date_format','reminder_interval')" . + " and uitype = '15'"); + +/* Function to add Field Security for newly added fields */ +function addFieldSecurity($tabid, $fieldid, $allow_merge=false) { + global $adb; + ExecuteQuery("INSERT INTO vtiger_def_org_field (tabid, fieldid, visible, readonly) VALUES ($tabid, $fieldid, 0, 1)"); + + $profile_result = $adb->query("select distinct(profileid) as profileid from vtiger_profile"); + $num_profiles = $adb->num_rows($profile_result); + for($j=0; $j<$num_profiles; $j++) { + $profileid = $adb->query_result($profile_result,$j,'profileid'); + ExecuteQuery("INSERT INTO vtiger_profile2field (profileid, tabid, fieldid, visible, readonly) VALUES($profileid, $tabid, $fieldid, 0, 1)"); + } + + if ($allow_merge) { + $user_result = $adb->query("select distinct(id) as userid from vtiger_users"); + $num_users = $adb->num_rows($user_result); + for($j=0; $j<$num_users; $j++) { + $userid = $adb->query_result($user_result,$j,'userid'); + ExecuteQuery("INSERT INTO vtiger_user2mergefields VALUES($userid, $tabid, $fieldid, 0)"); + } + } +} + +/* Add Total column in default customview of Purchase Order */ +$res = $adb->query("select cvid from vtiger_customview where viewname='All' and entitytype='PurchaseOrder'"); + +if($adb->num_rows($res)>0){ + $po_cvid = $adb->query_result($res, 0, 'cvid'); + $adb->query("update vtiger_cvcolumnlist set columnindex = 5 where columnindex = 4 and cvid = $po_cvid"); + $adb->query("insert into vtiger_cvcolumnlist values ($po_cvid, 4, 'vtiger_purchaseorder:total:hdnGrandTotal:PurchaseOrder_Total:V')"); +} + + + +/* To Provide an option to Create Product from Quick Create */ +ExecuteQuery("UPDATE vtiger_field SET quickcreate = 0 WHERE tablename='vtiger_products' and columnname='productname'"); +ExecuteQuery("UPDATE vtiger_field SET quickcreate = 0 WHERE tablename='vtiger_products' and columnname='discontinued'"); +ExecuteQuery("UPDATE vtiger_field SET quickcreate = 0 WHERE tablename='vtiger_products' and columnname='unit_price'"); +ExecuteQuery("UPDATE vtiger_field SET quickcreate = 0 WHERE tablename='vtiger_products' and columnname='qtyinstock'"); + +/* Necessary DB Changes for Restoring the Related information of a Deleted Record */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_relatedlists_rb(entityid int(19), action varchar(50), rel_table varchar(200), rel_column varchar(200), ref_column varchar(200), related_crm_ids text) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +// Enable Search icon for all profiles by default for Recyclebin module +$profileresult = $adb->query("select * from vtiger_profile"); +$countprofiles = $adb->num_rows($profileresult); +for($i=0;$i<$countprofiles;$i++) +{ + $profileid = $adb->query_result($profileresult,$i,'profileid'); + ExecuteQuery("insert into vtiger_profile2utility values($profileid,30,3,0)"); + ExecuteQuery("insert into vtiger_profile2tab values ($profileid,30,0)"); +} + +/* For Role based customview support */ +ExecuteQuery("alter table vtiger_customview add column status int(1) default '3'"); +ExecuteQuery("update vtiger_customview set status=0 where viewname='All'"); +ExecuteQuery("alter table vtiger_customview add column userid int(19) default '1'"); + +/* Reminder Popup support for Calendar Events */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_activity_reminder_popup(reminderid int(19) NOT NULL AUTO_INCREMENT,semodule varchar(100) NOT NULL,recordid varchar(100) NOT NULL,date_start DATE,time_start varchar(100) NOT NULL,status int(2) NOT NULL, PRIMARY KEY(reminderid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_reminder_interval(reminder_intervalid int(19) NOT NULL AUTO_INCREMENT,reminder_interval varchar(200) NOT NULL,sortorderid int(19) NOT NULL,presence int(1) NOT NULL, PRIMARY KEY(reminder_intervalid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("alter table vtiger_users add column reminder_interval varchar(100) NOT NULL"); +ExecuteQuery("alter table vtiger_users add column reminder_next_time varchar(100)"); + +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'None',0,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'1 Minute',1,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'5 Minutes',2,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'15 Minutes',3,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'30 Minutes',4,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'45 Minutes',5,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'1 Hour',6,1)"); +ExecuteQuery("INSERT INTO vtiger_reminder_interval values(".$adb->getUniqueId("vtiger_reminder_interval").",'1 Day',7,1)"); +ExecuteQuery("UPDATE vtiger_users SET reminder_interval='5 Minutes', reminder_next_time='".date('Y-m-d H:i')."'"); +$user_adv_block_id = $adb->getUniqueID('vtiger_blocks'); +ExecuteQuery("insert into vtiger_blocks values (".$user_adv_block_id.",29,'LBL_USER_ADV_OPTIONS',5,0,0,0,0,0)"); //Added a New Block User Image Info in Users Module +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values (29,".$adb->getUniqueID("vtiger_field").",'reminder_interval','vtiger_users',1,'16','reminder_interval','Reminder Interval',1,0,0,100,1,$user_adv_block_id,1,'V~O',1,null,'BAS')"); + +/* For Duplicate Records Merging feature */ +ExecuteQuery("INSERT INTO vtiger_actionmapping values(10,'DuplicatesHandling',0)"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_user2mergefields (userid int(11) REFERENCES vtiger_users( id ) , tabid int( 19 ) ,fieldid int( 19 ), visible int(2)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +function insertUser2mergefields($userid, $tabid) +{ + global $log,$adb; + $log->debug("Entering insertUser2mergefields(".$userid.") method ..."); + $log->info("in insertUser2mergefields ".$userid); + + foreach($tabid AS $key=>$tab_id) { + $fld_result = getFieldsResultForMerge($tab_id); + if ($fld_result != null) { + $num_rows = $adb->num_rows($fld_result); + for($j=0; $j<$num_rows; $j++) { + $field_id = $adb->query_result($fld_result,$j,'fieldid'); + $data_type = explode("~",$adb->query_result($fld_result,$j,'typeofdata')); + if($data_type[1] == 'M') { + $visible = 1; + } else { + $visible = 2; + } + ExecuteQuery("insert into vtiger_user2mergefields values ($userid, $tab_id, $field_id, $visible)"); + } + } + } + $log->debug("Exiting insertUser2mergefields method ..."); +} + +$tabid = Array(); +$tab_res = $adb->query("SELECT distinct tabid FROM vtiger_tab"); +$noOfTabs = $adb->num_rows($tab_res); +for($i=0;$i<$noOfTabs;$i++) { + $tabid[] = $adb->query_result($tab_res,$i,'tabid'); +} + +$usr_sql = $adb->query("select id from vtiger_users"); +$num_usr = $adb->num_rows($usr_sql); +for($i=0;$i<$num_usr;$i++) { + insertUser2mergefields($adb->query_result($usr_sql,$i,'id'),$tabid); +} + +$profile_sql = $adb->query("select profileid from vtiger_profile"); +$num_profile = $adb->num_rows($profile_sql); +/*Duplicate merging is supported for + * Accounts, Potentials, Contacts, Leads, Products, Vendors, TroubleTickets + */ +$dupSupported = array(6, 2, 4, 7, 14, 18, 13); +for($i=0;$i<$num_profile;$i++) { + $profile_id = $adb->query_result($profile_sql,$i,'profileid'); + for($j=0;$j<$noOfTabs;$j++) { + if (in_array($tabid[$j], $dupSupported)) { + ExecuteQuery("insert into vtiger_profile2utility values($profile_id,".$tabid[$j].",10,0)"); + } + } +} + +/* Local Backup Feature */ +ExecuteQuery("alter table vtiger_systems add column server_path varchar(256)"); + +/* Multi-Currency Support in Products, Pricebooks and Other Inventory Modules */ + +// To save mapping between products and its price in different currencies. +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_productcurrencyrel (productid int(11) not null, currencyid int(11) not null, converted_price decimal(25,2) default NULL, actual_price decimal(25, 2) default NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +// Update Product related tables +ExecuteQuery("alter table vtiger_products drop column currency"); +ExecuteQuery("alter table vtiger_products add column currency_id int(19) not null default '1'"); + +// Update Currency related tables +ExecuteQuery("alter table vtiger_currency_info add column deleted int(1) not null default '0'"); + +// Update Inventory related tables +ExecuteQuery("alter table vtiger_quotes drop column currency"); +ExecuteQuery("alter table vtiger_quotes add column currency_id int(19) not null default '1'"); +ExecuteQuery("alter table vtiger_quotes add column conversion_rate decimal(10,3) not null default '1.000'"); +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(20,$field_id,'currency_id','vtiger_quotes','1','117','currency_id','Currency','1','0','1','100','21','51','3','I~O','1',null,'BAS')"); +addFieldSecurity(20,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(20,$field_id,'conversion_rate','vtiger_quotes','1','1','conversion_rate','Conversion Rate','1','0','1','100','22','51','3','N~O','1',null,'BAS')"); +addFieldSecurity(20,$field_id); + +ExecuteQuery("alter table vtiger_purchaseorder add column currency_id int(19) not null default '1'"); +ExecuteQuery("alter table vtiger_purchaseorder add column conversion_rate decimal(10,3) not null default '1.000'"); +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(21,$field_id,'currency_id','vtiger_purchaseorder','1','117','currency_id','Currency','1','0','1','100','18','57','3','I~O','1',null,'BAS')"); +addFieldSecurity(21,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(21,$field_id,'conversion_rate','vtiger_purchaseorder','1','1','conversion_rate','Conversion Rate','1','0','1','100','19','57','3','N~O','1',null,'BAS')"); +addFieldSecurity(21,$field_id); + +ExecuteQuery("alter table vtiger_salesorder add column currency_id int(19) not null default '1'"); +ExecuteQuery("alter table vtiger_salesorder add column conversion_rate decimal(10,3) not null default '1.000'"); +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(22,$field_id,'currency_id','vtiger_salesorder','1','117','currency_id','Currency','1','0','1','100','19','63','3','I~O','1',null,'BAS')"); +addFieldSecurity(22,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(22,$field_id,'conversion_rate','vtiger_salesorder','1','1','conversion_rate','Conversion Rate','1','0','1','100','20','63','3','N~O','1',null,'BAS')"); +addFieldSecurity(22,$field_id); + +ExecuteQuery("alter table vtiger_invoice add column currency_id int(19) not null default '1'"); +ExecuteQuery("alter table vtiger_invoice add column conversion_rate decimal(10,3) not null default '1.000'"); +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(23,$field_id,'currency_id','vtiger_invoice','1','117','currency_id','Currency','1','0','1','100','18','69','3','I~O','1',null,'BAS')"); +addFieldSecurity(23,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values(23,$field_id,'conversion_rate','vtiger_invoice','1','1','conversion_rate','Conversion Rate','1','0','1','100','19','69','3','N~O','1',null,'BAS')"); +addFieldSecurity(23,$field_id); + +// Update Price Book related tables +ExecuteQuery("alter table vtiger_pricebook drop column description"); +ExecuteQuery("alter table vtiger_pricebook add column currency_id int(19) not null default '1'"); +ExecuteQuery("alter table vtiger_pricebookproductrel add column usedcurrency int(11) not null default '1'"); +$pb_currency_field_id = $adb->getUniqueID('vtiger_field'); +$pb_tab_id = getTabid('PriceBooks'); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($pb_tab_id,$pb_currency_field_id,'currency_id','vtiger_pricebook','1','117','currency_id','Currency','1','0','0','100','5','48','1','I~M','0','3','BAS')"); +$adb->query("insert into vtiger_cvcolumnlist values('23','2','vtiger_pricebook:currency_id:currency_id:PriceBooks_Currency:I')"); +addFieldSecurity($pb_tab_id,$pb_currency_field_id); + +/* Documents module */ +$documents_tab_id = getTabid('Documents'); +ExecuteQuery("delete from vtiger_cvcolumnlist where columnname like '%Notes_Contact_Name%'"); +ExecuteQuery("delete from vtiger_cvcolumnlist where columnname like '%Notes_Related_to%'"); + +ExecuteQuery("insert into vtiger_def_org_share values (".$adb->getUniqueID('vtiger_def_org_share').",$documents_tab_id,2,0)"); + +for($i=0;$i<4;$i++) +{ + ExecuteQuery("insert into vtiger_org_share_action2tab values(".$i.",$documents_tab_id)"); +} + +ExecuteQuery("alter table vtiger_customview drop foreign key fk_1_vtiger_customview "); +ExecuteQuery("update vtiger_customview set entitytype='Documents' where entitytype='Notes'"); +ExecuteQuery("update vtiger_tab set ownedby=0,name='Documents',tablabel='Documents' where tabid=$documents_tab_id"); +ExecuteQuery("update vtiger_entityname set modulename='Documents' where tabid=$documents_tab_id"); +ExecuteQuery("alter table vtiger_customview add constraint FOREIGN KEY fk_1_vtiger_customview (entitytype) REFERENCES vtiger_tab (name) ON DELETE CASCADE"); + +ExecuteQuery("UPDATE vtiger_relatedlists SET actions='add,select', related_tabid=$documents_tab_id WHERE name='get_attachments'"); +ExecuteQuery("alter table vtiger_notes add(folderid int(19) DEFAULT 1,filetype varchar(50) default NULL,filelocationtype varchar(5) default NULL,filedownloadcount int(19) default NULL,filestatus int(19) default NULL,filesize int(19) NOT NULL default '0',fileversion varchar(50) default NULL)"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_attachmentsfolder ( folderid int(19) AUTO_INCREMENT NOT NULL,foldername varchar(200) NOT NULL default '', description varchar(250) default '', createdby int(19) NOT NULL, sequence int(19) default NULL, PRIMARY KEY (folderid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("insert into vtiger_attachmentsfolder values (1,'Existing Notes','Contains all Notes migrated from the earlier version',1,1)"); + +ExecuteQuery("alter table vtiger_senotesrel drop foreign key fk_2_vtiger_senotesrel "); + +ExecuteQuery("UPDATE vtiger_crmentity SET setype='Documents' WHERE setype='Notes'"); + +$attachmentidQuery = 'select vtiger_seattachmentsrel.attachmentsid as attachmentid, vtiger_seattachmentsrel.crmid as id from vtiger_seattachmentsrel INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_seattachmentsrel.crmid WHERE vtiger_crmentity.deleted = 0'; +$res = $adb->pquery($attachmentidQuery,array()); +if($adb->num_rows($res)>0){ + for($index=0;$index<$adb->num_rows($res);$index++){ + $attachmentid = $adb->query_result($res,$index,'attachmentid'); + $crmid = $adb->query_result($res,$index,'id'); + if($attachmentid != ''){ + $attachmentInfoQuery = 'select * from vtiger_attachments where attachmentsid = ?'; + $attachres = $adb->pquery($attachmentInfoQuery,array($attachmentid)); + if($adb->num_rows($attachres)>0){ + $filename = $adb->query_result($attachres,0,'name'); + $attch_sub = $adb->query_result($attachres,0,'subject'); + $description = $adb->query_result($attachres,0,'description'); + $filepath = $adb->query_result($attachres,0,'path'); + $filetype = $adb->query_result($attachres,0,'type'); + if(file_exists($filepath.$attachmentid."_".$filename)) { + $filesize = filesize($filepath.$attachmentid."_".$filename); + $filestatus = "1"; + } else { + $filesize = "0"; + $filestatus = "0"; + } + + $noteid_query = $adb->pquery("SELECT notesid FROM vtiger_notes WHERE notesid = ?",array($crmid)); + if($adb->num_rows($noteid_query)>0) { + $notesid = $adb->query_result($noteid_query,0,"notesid"); + ExecuteQuery("update vtiger_notes set folderid = 1,filestatus='$filestatus',filelocationtype='I',filedownloadcount=0,fileversion='',filetype='".$filetype."',filesize='".$filesize."',filename='".$filename."' where notesid = ".$notesid); + } else { + require_once("modules/Documents/Documents.php"); + + $notes_obj = new Documents(); + if($attch_sub == '') $attch_sub = $filename; + $notes_obj->column_fields['notes_title'] = decode_html($attch_sub); + $notes_obj->column_fields['notecontent'] = decode_html($description); + $notes_obj->column_fields['assigned_user_id'] = 1; + $notes_obj->save("Documents"); + $notesid = $notes_obj->id; + + ExecuteQuery("Update vtiger_notes set folderid=1,filedownloadcount=0, filestatus='$filestatus', fileversion='', filesize = '$filesize', filetype = '$filetype' , filelocationtype = 'I', filename = '$filename' where notesid = $notesid"); + ExecuteQuery("INSERT INTO vtiger_senotesrel VALUES($crmid,$notesid)"); + ExecuteQuery("INSERT INTO vtiger_seattachmentsrel VALUES($notesid,$attachmentid)"); + } + } + } + else{ + ExecuteQuery("update vtiger_notes set folderid=1, filestatus=1,filelocationtype='',filedownloadcount='',fileversion='',filetype='',filesize='',filename='' where notesid = ".$notesid); + } + } +} + +$fieldid = Array(); +for($i=0;$i<8;$i++) +{ + $fieldid[$i] = $adb->getUniqueID("vtiger_field"); +} +$file_block_id = $adb->getUniqueID('vtiger_blocks'); +ExecuteQuery("insert into vtiger_blocks values($file_block_id,$documents_tab_id,'LBL_FILE_INFORMATION',2,0,0,0,0,0)"); + +$description_block_id_Query = 'select blockid from vtiger_blocks where tabid = '.$documents_tab_id.' and blocklabel = "" '; +$desc_id = $adb->pquery($description_block_id_Query,array()); +if($adb->num_rows($desc_id)>0){ + $desc = $adb->query_result($desc_id,0,'blockid'); + $desc_update = 'update vtiger_blocks set blocklabel ="LBL_DESCRIPTION",show_title = 0,sequence = 3 where blockid = ?'; + $desc_block_update = $adb->pquery($desc_update,array($desc)); + ExecuteQuery("update vtiger_field set sequence=1,quickcreate=1,presence=2,block=$desc where tabid=$documents_tab_id and columnname='notecontent'"); +} + +ExecuteQuery("update vtiger_field set sequence=1 where tabid=$documents_tab_id and columnname='title'"); +ExecuteQuery("update vtiger_field set sequence=8,quickcreate=3 where tabid=$documents_tab_id and columnname='createdtime'"); +ExecuteQuery("update vtiger_field set sequence=9,quickcreate=3 where tabid=$documents_tab_id and columnname='modifiedtime'"); + +ExecuteQuery("update vtiger_field set sequence = 3,quickcreate=3,block = $file_block_id,fieldlabel='File Name',displaytype = 1,uitype=28 where tabid = $documents_tab_id and columnname = 'filename'"); + +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[0].",'smownerid','vtiger_crmentity',1,53,'assigned_user_id','Assigned To',1,0,0,100,2,17,1,'V~M',0,3,'BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[1].",'filetype','vtiger_notes',1,1,'filetype','File Type',1,2,0,100,5,$file_block_id,2,'V~O',3,'','BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[2].",'filesize','vtiger_notes',1,1,'filesize','File Size',1,2,0,100,4,$file_block_id,2,'V~O',3,'','BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[3].",'filelocationtype','vtiger_notes',1,27,'filelocationtype','Download Type',1,0,0,100,1,$file_block_id,1,'V~O',1,'','BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[4].",'fileversion','vtiger_notes',1,1,'fileversion','Version',1,2,0,100,6,17,1,'V~O',1,'','BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[5].",'filestatus','vtiger_notes',1,56,'filestatus','Active',1,2,0,100,2,$file_block_id,1,'V~O',1,'','BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[6].",'filedownloadcount','vtiger_notes',1,1,'filedownloadcount','Download Count',1,2,0,100,6,$file_block_id,2,'I~O',3,'','BAS')"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values ($documents_tab_id,".$fieldid[7].",'folderid','vtiger_notes',1,26,'folderid','Folder Name',1,2,0,100,4,17,1,'V~O',2,'2','BAS')"); + +for($i=0;$iquery($dbQuery); +$noofrecords = $adb->num_rows($dbresult); +if($noofrecords > 0) +{ + for($i=0;$i<$noofrecords;$i++) + { + $contactid = $adb->query_result($dbresult,$i,'contact_id'); + $notesid = $adb->query_result($dbresult,$i,'notesid'); + $dup_check = $adb->pquery("SELECT * from vtiger_senotesrel WHERE crmid = ? AND notesid = ?",array($contactid,$notesid)); + if($contactid != 0 && $adb->num_rows($dup_check)==0){ + ExecuteQuery("insert into vtiger_senotesrel values (".$contactid.",".$notesid.")"); + } + } +} + +ExecuteQuery("delete from vtiger_field where tabid = 8 and fieldname = 'contact_id'"); +ExecuteQuery("delete from vtiger_field where tabid = 8 and fieldname = 'parent_id'"); + +ExecuteQuery("alter table vtiger_notes drop column contact_id"); + +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_notes:filename:filename:Documents_Filename:V' where cvid = 22 and columnindex = 3"); +custom_addCustomFilterColumn('Documents','All', 'vtiger_crmentity','smownerid','assigned_user_id','Documents_Assigned_To:V',7); + +ExecuteQuery("UPDATE vtiger_field SET columnname='name' WHERE fieldname='filename' AND tablename='vtiger_attachments' AND tabid=".getTabid('Emails')); + +//remove filename column from trouble ticket +ExecuteQuery("alter table vtiger_troubletickets drop column filename"); +ExecuteQuery("delete from vtiger_field where fieldname='filename' and tablename='vtiger_attachments' AND tabid=".getTabid('HelpDesk')); +//End: Database changes regarding Documents module + +/* Home Page Customization */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_homestuff (stuffid int(19) NOT NULL default '0', stuffsequence int(19) NOT NULL default '0', stufftype varchar(100) default NULL, userid int(19) NOT NULL, visible int(10) NOT NULL default '0', stufftitle varchar(100) default NULL, PRIMARY KEY (stuffid), KEY stuff_stuffid_idx (stuffid), KEY fk_1_vtiger_homestuff (userid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_homedashbd (stuffid int(19) NOT NULL default 0, dashbdname varchar(100) default NULL, dashbdtype varchar(100) default NULL, PRIMARY KEY (stuffid), KEY stuff_stuffid_idx (stuffid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_homedefault (stuffid int(19) NOT NULL default 0, hometype varchar(30) NOT NULL, maxentries int(19) default NULL, setype varchar(30) default NULL, PRIMARY KEY (stuffid), KEY stuff_stuffid_idx (stuffid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_homemodule (stuffid int(19) NOT NULL, modulename varchar(100) default NULL, maxentries int(19) NOT NULL, customviewid int(19) NOT NULL, setype varchar(30) NOT NULL, PRIMARY KEY (stuffid), KEY stuff_stuffid_idx (stuffid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_homemoduleflds (stuffid int(19) default NULL, fieldname varchar(255) default NULL, KEY stuff_stuffid_idx (stuffid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_homerss (stuffid int(19) NOT NULL default 0, url varchar(100) default NULL, maxentries int(19) NOT NULL, PRIMARY KEY (stuffid), KEY stuff_stuffid_idx (stuffid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("ALTER TABLE vtiger_homestuff ADD CONSTRAINT fk_1_vtiger_homestuff FOREIGN KEY (userid) REFERENCES vtiger_users (id) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_homedashbd ADD CONSTRAINT fk_1_vtiger_homedashbd FOREIGN KEY (stuffid) REFERENCES vtiger_homestuff (stuffid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_homedefault ADD CONSTRAINT fk_1_vtiger_homedefault FOREIGN KEY (stuffid) REFERENCES vtiger_homestuff (stuffid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_homemodule ADD CONSTRAINT fk_1_vtiger_homemodule FOREIGN KEY (stuffid) REFERENCES vtiger_homestuff (stuffid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_homemoduleflds ADD CONSTRAINT fk_1_vtiger_homemoduleflds FOREIGN KEY (stuffid) REFERENCES vtiger_homemodule (stuffid) ON DELETE CASCADE"); +ExecuteQuery("ALTER TABLE vtiger_homerss ADD CONSTRAINT fk_1_vtiger_homerss FOREIGN KEY (stuffid) REFERENCES vtiger_homestuff (stuffid) ON DELETE CASCADE"); + +//to get the users lists +$query = $adb->pquery('select * from vtiger_users',array()); +for($i=0;$i<$adb->num_rows($query);$i++) +{ + $userid = $adb->query_result($query,$i,'id'); + + $s1=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s1.",1,'Default',".$userid.",1,'Top Accounts')"; + $res=$adb->pquery($sql,array()); + + $s2=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s2.",2,'Default',".$userid.",1,'Home Page Dashboard')"; + $res=$adb->pquery($sql,array()); + + $s3=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s3.",3,'Default',".$userid.",1,'Top Potentials')"; + $res=$adb->pquery($sql,array()); + + $s4=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s4.",4,'Default',".$userid.",1,'Top Quotes')"; + $res=$adb->pquery($sql,array()); + + $s5=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s5.",5,'Default',".$userid.",1,'Key Metrics')"; + $res=$adb->pquery($sql,array()); + + $s6=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s6.",6,'Default',".$userid.",1,'Top Trouble Tickets')"; + $res=$adb->pquery($sql,array()); + + $s7=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s7.",7,'Default',".$userid.",1,'Upcoming Activities')"; + $res=$adb->pquery($sql,array()); + + $s8=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s8.",8,'Default',".$userid.",1,'My Group Allocation')"; + $res=$adb->pquery($sql,array()); + + $s9=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s9.",9,'Default',".$userid.",1,'Top Sales Orders')"; + $res=$adb->pquery($sql,array()); + + $s10=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s10.",10,'Default',".$userid.",1,'Top Invoices')"; + $res=$adb->pquery($sql,array()); + + $s11=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s11.",11,'Default',".$userid.",1,'My New Leads')"; + $res=$adb->pquery($sql,array()); + + $s12=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s12.",12,'Default',".$userid.",1,'Top Purchase Orders')"; + $res=$adb->pquery($sql,array()); + + $s13=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s13.",13,'Default',".$userid.",1,'Pending Activities')"; + $res=$adb->pquery($sql,array()); + + $s14=$adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values(".$s14.",14,'Default',".$userid.",1,'My Recent FAQs')"; + $res=$adb->pquery($sql,array()); + + // Non-Default Home Page widget (no entry is requried in vtiger_homedefault below) + $tc = $adb->getUniqueID("vtiger_homestuff"); + $sql="insert into vtiger_homestuff values($tc, 15, 'Tag Cloud', $userid, 0, 'Tag Cloud')"; + $adb->query($sql); + + $sql="insert into vtiger_homedefault values(".$s1.",'ALVT',5,'Accounts')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s2.",'HDB',5,'Dashboard')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s3.",'PLVT',5,'Potentials')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s4.",'QLTQ',5,'Quotes')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s5.",'CVLVT',5,'NULL')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s6.",'HLT',5,'HelpDesk')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s7.",'UA',5,'Calendar')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s8.",'GRT',5,'NULL')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s9.",'OLTSO',5,'SalesOrder')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s10.",'ILTI',5,'Invoice')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s11.",'MNL',5,'Leads')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s12.",'OLTPO',5,'PurchaseOrder')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s13.",'PA',5,'Calendar')"; + $adb->pquery($sql,array()); + + $sql="insert into vtiger_homedefault values(".$s14.",'LTFAQ',5,'Faq')"; + $adb->pquery($sql,array()); +} +for($i=0;$i<$adb->num_rows($query);$i++) +{ + $def_homeorder = $adb->query_result($query,$i,'homeorder'); + $user_id = $adb->query_result($query,$i,'id'); + $def_array = explode(",",$def_homeorder); + $sql = $adb->pquery("SELECT vtiger_homestuff.stuffid FROM vtiger_homestuff INNER JOIN vtiger_homedefault WHERE vtiger_homedefault.hometype in (". generateQuestionMarks($def_array) . ") AND vtiger_homestuff.stuffid = vtiger_homedefault.stuffid AND vtiger_homestuff.userid = ?",array($def_array,$user_id)); + $stuffid_list = array(); + for($j=0;$j<$adb->num_rows($sql);$j++) { + $stuffid_list[] = $adb->query_result($sql,$j,'stuffid'); + } + $adb->pquery("UPDATE vtiger_homestuff SET visible = 0 WHERE stuffid in (". generateQuestionMarks($stuffid_list) .")",array($stuffid_list)); +} + +/* For Layout Editor */ +ExecuteQuery("ALTER TABLE vtiger_blocks ADD COLUMN display_status int(1) NOT NULL DEFAULT '1'"); + +/* Adding Custom Events Migration */ +ExecuteQuery("UPDATE vtiger_field SET uitype=15,typeofdata='V~M' WHERE tabid=16 and columnname='activitytype'"); +ExecuteQuery("alter table vtiger_activitytype drop column sortorderid"); +ExecuteQuery("alter table vtiger_activitytype add column picklist_valueid int(19) NOT NULL default '0'"); +$picklist_id = $adb->getUniqueId("vtiger_picklist"); +ExecuteQuery("INSERT INTO vtiger_picklist VALUES(".$picklist_id.",'activitytype')"); + +$query = $adb->pquery("SELECT * from vtiger_activitytype",array()); +for($i=0;$i<$adb->num_rows($query);$i++){ + $picklist_valueid = $adb->getUniqueID('vtiger_picklistvalues'); + $activitytypeid = $adb->query_result($query,$i,'activitytypeid'); + $adb->pquery("UPDATE vtiger_activitytype SET picklist_valueid=? , presence=0 WHERE activitytypeid = ? ",array($picklist_valueid,$activitytypeid)); +} + +$role_query = $adb->query("SELECT * FROM vtiger_role"); +for($j=0;$j<$adb->num_rows($role_query);$j++){ + $roleid = $adb->query_result($role_query,$j,'roleid'); + $query = $adb->pquery("SELECT * from vtiger_activitytype",array()); + for($i=0;$i<$adb->num_rows($query);$i++){ + $picklist_valueid = $adb->query_result($query,$i,'picklist_valueid'); + ExecuteQuery("INSERT INTO vtiger_role2picklist VALUES('".$roleid."',".$picklist_valueid.",".$picklist_id.",$i)"); + } +} + +$uniqueid = $adb->getUniqueID("vtiger_relatedlists"); +$faqtabid = getTabid('Faq'); +ExecuteQuery("insert into vtiger_relatedlists values($uniqueid,$faqtabid,$documents_tab_id,'get_attachments',1,'Documents',0,'add,select')"); +//CustomEvents Migration Ends + +/* Important column renaming to support database porting */ +$adb->pquery("ALTER TABLE vtiger_profile2standardpermissions CHANGE Operation testoperation INTEGER", array()); +$adb->pquery("ALTER TABLE vtiger_profile2standardpermissions CHANGE testoperation operation INTEGER", array()); + +$renameArray = array( + "vtiger_sales_stage", + "vtiger_faqcategories", + "vtiger_faqstatus", + "vtiger_rating", + "vtiger_ticketcategories", + "vtiger_ticketpriorities", + "vtiger_ticketseverities", + "vtiger_ticketstatus" +); +foreach($renameArray as $tablename) { + $adb->pquery("ALTER TABLE $tablename CHANGE PRESENCE testpresence INTEGER", array()); + $adb->pquery("ALTER TABLE $tablename CHANGE testpresence presence INTEGER", array()); +} +// Renaming completed + +/* Important database schema changes to support database porting */ +ExecuteQuery("alter table vtiger_attachments drop index attachments_description_type_attachmentsid_idx"); +ExecuteQuery("alter table vtiger_attachments modify column description TEXT"); +ExecuteQuery("alter table vtiger_emaildetails modify column idlists TEXT"); + +/* Product Bundles Feature */ +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Products").",'get_products',13,'Product Bundles',0,'add,select')"); +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Products").",'get_parent_products',14,'Parent Products',0,'')"); + +/* vtmailscanner customization */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_mailscanner(scannerid INT AUTO_INCREMENT NOT NULL PRIMARY KEY,scannername VARCHAR(30), + server VARCHAR(100),protocol VARCHAR(10),username VARCHAR(255),password VARCHAR(255),ssltype VARCHAR(10), +sslmethod VARCHAR(30),connecturl VARCHAR(255),searchfor VARCHAR(10),markas VARCHAR(10),isvalid INT(1)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_mailscanner_ids(scannerid INT, messageid TEXT,crmid INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_mailscanner_folders(folderid INT AUTO_INCREMENT NOT NULL PRIMARY KEY,scannerid INT,foldername VARCHAR(255),lastscan VARCHAR(30),rescan INT(1), enabled INT(1)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_mailscanner_rules(ruleid INT AUTO_INCREMENT NOT NULL PRIMARY KEY,scannerid INT,fromaddress VARCHAR(255),toaddress VARCHAR(255),subjectop VARCHAR(20),subject VARCHAR(255),bodyop VARCHAR(20),body VARCHAR(255),matchusing VARCHAR(5),sequence INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_mailscanner_actions(actionid INT AUTO_INCREMENT NOT NULL PRIMARY KEY,scannerid INT,actiontype VARCHAR(10),module VARCHAR(30),lookup VARCHAR(30),sequence INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_mailscanner_ruleactions(ruleid INT,actionid INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +// END + +/* Recurring Invoice Feature */ +$new_block_seq_no = 2; +// Get all the blocks of the same module (SalesOrder), and update their sequence depending on the sequence of the new block added. +$res = $adb->query("SELECT blockid FROM vtiger_blocks WHERE tabid = ". getTabid('SalesOrder') ." AND sequence >= ". $new_block_seq_no); +$no_of_blocks = $adb->num_rows($res); +for ($i=0; $i<$no_of_blocks;$i++) { + $blockid = $adb->query_result($res, $i, 'blockid'); + ExecuteQuery("UPDATE vtiger_blocks SET sequence = sequence+1 WHERE blockid=$blockid"); +} +// Add new block to show recurring invoice information at specified position (sequence of blocks) +$new_block_id = $adb->getUniqueID('vtiger_blocks'); +ExecuteQuery("INSERT INTO vtiger_blocks VALUES (".$new_block_id.",".getTabid('SalesOrder').",'Recurring Invoice Information',$new_block_seq_no,0,0,0,0,0,1)"); + +ExecuteQuery("ALTER TABLE vtiger_salesorder ADD COLUMN enable_recurring INT default 0"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_invoice_recurring_info(salesorderid INT, recurring_frequency VARCHAR(200), start_period DATE, end_period DATE, last_recurring_date DATE default NULL, " . + " payment_duration VARCHAR(200), invoice_status VARCHAR(200)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_recurring_frequency(recurring_frequency_id INT, recurring_frequency VARCHAR(200), sortorderid INT, presence INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +// Add default values for the recurring_frequency picklist +ExecuteQuery("INSERT INTO vtiger_recurring_frequency values(".$adb->getUniqueID('vtiger_recurring_frequency').",'--None--',1,1)"); +ExecuteQuery("INSERT INTO vtiger_recurring_frequency values(".$adb->getUniqueID('vtiger_recurring_frequency').",'Daily',2,1)"); +ExecuteQuery("INSERT INTO vtiger_recurring_frequency values(".$adb->getUniqueID('vtiger_recurring_frequency').",'Weekly',3,1)"); +ExecuteQuery("INSERT INTO vtiger_recurring_frequency values(".$adb->getUniqueID('vtiger_recurring_frequency').",'Monthly',4,1)"); +ExecuteQuery("INSERT INTO vtiger_recurring_frequency values(".$adb->getUniqueID('vtiger_recurring_frequency').",'Quarterly',5,1)"); +ExecuteQuery("INSERT INTO vtiger_recurring_frequency values(".$adb->getUniqueID('vtiger_recurring_frequency').",'Yearly',6,1)"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_payment_duration(payment_duration_id INT, payment_duration VARCHAR(200), sortorderid INT, presence INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +// Add default values for the vtiger_payment_duration picklist +ExecuteQuery("INSERT INTO vtiger_payment_duration values(".$adb->getUniqueID('vtiger_payment_duration').",'Net 30 days',1,1)"); +ExecuteQuery("INSERT INTO vtiger_payment_duration values(".$adb->getUniqueID('vtiger_payment_duration').",'Net 45 days',2,1)"); +ExecuteQuery("INSERT INTO vtiger_payment_duration values(".$adb->getUniqueID('vtiger_payment_duration').",'Net 60 days',3,1)"); + +// Add fields for the Recurring Information block +$salesorder_tabid = getTabid('SalesOrder'); +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($salesorder_tabid,$field_id,'enable_recurring','vtiger_salesorder',1,'56','enable_recurring','Enable Recurring',1,0,0,100,1,$new_block_id,1,'C~O',3,null,'BAS')"); +addFieldSecurity($salesorder_tabid,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($salesorder_tabid,$field_id,'recurring_frequency','vtiger_invoice_recurring_info',1,'16','recurring_frequency','Frequency',1,0,0,100,2,$new_block_id,1,'V~O',3,null,'BAS')"); +addFieldSecurity($salesorder_tabid,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($salesorder_tabid,$field_id,'start_period','vtiger_invoice_recurring_info',1,'5','start_period','Start Period',1,0,0,100,3,$new_block_id,1,'D~O',3,null,'BAS')"); +addFieldSecurity($salesorder_tabid,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($salesorder_tabid,$field_id,'end_period','vtiger_invoice_recurring_info',1,'5','end_period','End Period',1,0,0,100,4,$new_block_id,1,'D~O~OTH~G~start_period~Start Period',3,null,'BAS')"); +addFieldSecurity($salesorder_tabid,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($salesorder_tabid,$field_id,'payment_duration','vtiger_invoice_recurring_info',1,'16','payment_duration','Payment Duration',1,0,0,100,5,$new_block_id,1,'V~O',3,null,'BAS')"); +addFieldSecurity($salesorder_tabid,$field_id); + +$field_id = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type) values($salesorder_tabid,$field_id,'invoice_status','vtiger_invoice_recurring_info',1,'15','invoicestatus','Invoice Status',1,0,0,100,6,$new_block_id,1,'V~O',3,null,'BAS')"); +addFieldSecurity($salesorder_tabid,$field_id); + +// Add new picklist value 'AutoCreated' for Invoice Status and add the same for all the existing roles. +$picklistRes = $adb->query("SELECT picklistid FROM vtiger_picklist WHERE name='invoicestatus'"); +if($adb->num_rows($picklistRes)>0){ + $picklistid = $adb->query_result($picklistRes,0,'picklistid'); + + $picklist_valueid = $adb->getUniqueID('vtiger_picklistvalues'); + $max_seq_id_qry = $adb->pquery("SELECT max(inovicestatusid) as maxid from vtiger_invoicestatus",array()); + if($adb->num_rows($max_seq_id_qry)>0) { + $tmp = $adb->getUniqueID('vtiger_invoicestatus'); + $max_seq_id = $adb->query_result($max_seq_id_qry,0,'maxid'); + $adb->pquery("UPDATE vtiger_invoicestatus_seq SET id=?",array($max_seq_id)); + } + $id = $adb->getUniqueID('vtiger_invoicestatus'); + + ExecuteQuery("insert into vtiger_invoicestatus values($id, 'AutoCreated', 1, $picklist_valueid)"); + + //Default entries for role2picklist relation has been inserted.. + $sql="select roleid from vtiger_role"; + $role_result = $adb->pquery($sql, array()); + $numrow = $adb->num_rows($role_result); + for($k=0; $k < $numrow; $k ++) + { + $roleid = $adb->query_result($role_result,$k,'roleid'); + $params = array($roleid, $picklist_valueid, $picklistid, $id-1); + $adb->pquery("insert into vtiger_role2picklist values(?,?,?,?)", $params); + } +} + +// Add Event handler for Recurring Invoice +$em->registerHandler('vtiger.entity.aftersave', 'modules/SalesOrder/RecurringInvoiceHandler.php', 'RecurringInvoiceHandler'); + +/* Workflow Manager - com_vtiger_workflow */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflows_seq (id int(11)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("insert into com_vtiger_workflows_seq (id) values(1)"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflows (workflow_id int, module_name varchar(100), summary varchar(100), test varchar(400), task_id int(11), exec_date int, execution_condition varchar(50)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery('CREATE TABLE IF NOT EXISTS com_vtiger_workflow_activatedonce (entity_id int, workflow_id int) ENGINE=InnoDB DEFAULT CHARSET=utf8;'); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflowtasks_seq (id int(11)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("insert into com_vtiger_workflowtasks_seq (id) values(1)"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflowtasks (task_id int, workflow_id int, summary varchar(100), task text, primary key(task_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflowtask_queue (task_id int, entity_id varchar(100), do_after int, primary key(task_id, entity_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflowtasks_entitymethod_seq (id int(11)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("insert into com_vtiger_workflowtasks_entitymethod_seq (id) values(1)"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS com_vtiger_workflowtasks_entitymethod (workflowtasks_entitymethod_id int, module_name varchar(100), method_name varchar(100), function_path varchar(400), function_name varchar(100), primary key(workflowtasks_entitymethod_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +ExecuteQuery("CREATE TABLE com_vtiger_workflowtemplates ( + template_id int(11) NOT NULL default '0', + module_name varchar(100) default NULL, + title varchar(400) default NULL, + template text, PRIMARY KEY (template_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +$em->registerHandler('vtiger.entity.aftersave', 'modules/com_vtiger_workflow/VTEventHandler.inc', 'VTWorkflowEventHandler'); +// com_vtiger_workflow ends + +/* Mass Edit Feature */ +ExecuteQuery("ALTER TABLE vtiger_field ADD COLUMN masseditable int(11) NOT NULL DEFAULT '1'"); +$tab_field_array = array( + 'Accounts'=>array('accountname','account_id'), + 'Contacts'=>array('imagename','portal','contact_id'), + 'Products'=>array('imagename','product_id'), + 'Invoice'=>array('invoice_no','salesorder_id'), + 'SalesOrder'=>array('quote_id','salesorder_no','enable_recurring','recurring_frequency','start_period','end_period','payment_duration','invoicestatus'), + 'PurchaseOrder'=>array('purchaseorder_no'), + 'Quotes'=>array('quote_no'), + 'HelpDesk'=>array('filename'), +); +foreach($tab_field_array as $index=>$value){ + $tabid = getTabid($index); + $adb->pquery("UPDATE vtiger_field SET masseditable=0 WHERE tabid=? AND fieldname IN (".generateQuestionMarks($value).")",array($tabid,$value)); +} + +/* Showing Emails in Vendors related list */ +ExecuteQuery("insert into vtiger_relatedlists values(".$adb->getUniqueID('vtiger_relatedlists').",".getTabid("Vendors").",".getTabid("Emails").",'get_emails',4,'Emails',0,'add')"); + +/* Added for module sequence number customization */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_modentity_num (num_id int(19) NOT NULL, semodule varchar(50) NOT NULL, prefix varchar(50) NOT NULL DEFAULT '', start_id varchar(50) NOT NULL, cur_id varchar(50) NOT NULL, active int(2) NOT NULL, PRIMARY KEY(num_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +// Setup module sequence numbering for all modules (except Invoice). +function custom_addInventoryRows($paramArray){ + global $adb; + + $fieldCreateCount = 0; + + for($index = 0; $index < count($paramArray); ++$index) { + $criteria = $paramArray[$index]; + + $semodule = $criteria['semodule']; + $adb->pquery("INSERT into vtiger_modentity_num values(?,?,?,?,?,?)",array($adb->getUniqueId("vtiger_modentity_num"),$semodule,$criteria['prefix'],$criteria['startid'],$criteria['curid'],1)); + } +} +$modseq = array( + 'Leads' =>'LEA', + 'Accounts' =>'ACC', + 'Campaigns' =>'CAM', + 'Contacts' =>'CON', + 'Potentials'=>'POT', + 'HelpDesk' =>'TT', + 'Quotes' =>'QUO', + 'SalesOrder'=>'SO', + 'PurchaseOrder'=>'PO', + 'Products' =>'PRO', + 'Vendors' =>'VEN', + 'PriceBooks'=>'PB', + 'Faq' =>'FAQ', + 'Documents' =>'DOC' +); +foreach($modseq as $modname => $prefix) { + custom_addInventoryRows( + array( + array('semodule'=>$modname, 'active'=>'1','prefix'=>$prefix,'startid'=>'1','curid'=>'1') + ) + ); +} +// Setup module sequence for Invoice +@include_once('user_privileges/CustomInvoiceNo.php'); +// We need to move the existing information of Custom numbering to database +// but in case the previous setting is not available...we are defaulting +if(!isset($inv_str)) $inv_str = 'INV'; +if(!isset($inv_no)) $inv_no = '1'; + +custom_addInventoryRows( + array( + array('semodule'=>'Invoice', 'active'=>'1','prefix'=>decode_html($inv_str),'startid'=>'1','curid'=>$inv_no) + ) + ); + +// Add Module Number Field to UI. + +$blockid = getBlockId(6,'LBL_ACCOUNT_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (6,".$adb->getUniqueID("vtiger_field").",'account_no','vtiger_account',1,'4','account_no','Account No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_account ADD COLUMN account_no varchar(100) not null"); + +$blockid = getBlockId(7,'LBL_LEAD_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (7,".$adb->getUniqueID("vtiger_field").",'lead_no','vtiger_leaddetails',1,'4','lead_no','Lead No',1,0,0,100,3,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_leaddetails ADD COLUMN lead_no varchar(100) not null"); + +$blockid = getBlockId(4,'LBL_CONTACT_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (4,".$adb->getUniqueID("vtiger_field").",'contact_no','vtiger_contactdetails',1,'4','contact_no','Contact Id',1,0,0,100,3,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_contactdetails ADD COLUMN contact_no varchar(100) not null"); + +$blockid = getBlockId(2,'LBL_OPPORTUNITY_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (2,".$adb->getUniqueID("vtiger_field").",'potential_no','vtiger_potential',1,'4','potential_no','Potential No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_potential ADD COLUMN potential_no varchar(100) not null"); + +$blockid = getBlockId(26,'LBL_CAMPAIGN_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (26,".$adb->getUniqueID("vtiger_field").",'campaign_no','vtiger_campaign',1,'4','campaign_no','Campaign No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_campaign ADD COLUMN campaign_no varchar(100) not null"); + +$blockid = getBlockId(13,'LBL_TICKET_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (13,".$adb->getUniqueID("vtiger_field").",'ticket_no','vtiger_troubletickets',1,'4','ticket_no','Ticket No',1,0,0,100,1,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_troubletickets ADD COLUMN ticket_no varchar(100) not null"); + +$blockid = getBlockId(14,'LBL_PRODUCT_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (14,".$adb->getUniqueID("vtiger_field").",'product_no','vtiger_products',1,'4','product_no','Product No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_products ADD COLUMN product_no varchar(100) not null"); + +$blockid = getBlockId(8,'LBL_NOTE_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (8,".$adb->getUniqueID("vtiger_field").",'note_no','vtiger_notes',1,'4','note_no','Document No',1,0,0,100,7,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_notes ADD COLUMN note_no varchar(100) not null"); + +$blockid = getBlockId(15,'LBL_FAQ_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (15,".$adb->getUniqueID("vtiger_field").",'faq_no','vtiger_faq',1,'4','faq_no','Faq No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_faq ADD COLUMN faq_no varchar(100) not null"); + +$blockid = getBlockId(18,'LBL_VENDOR_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (18,".$adb->getUniqueID("vtiger_field").",'vendor_no','vtiger_vendor',1,'4','vendor_no','Vendor No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_vendor ADD COLUMN vendor_no varchar(100) not null"); + +$blockid = getBlockId(19,'LBL_PRICEBOOK_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (19,".$adb->getUniqueID("vtiger_field").",'pricebook_no','vtiger_pricebook',1,'4','pricebook_no','PriceBook No',1,0,0,100,3,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_pricebook ADD COLUMN pricebook_no varchar(100) not null"); + +$blockid = getBlockId(22,'LBL_SO_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (22,".$adb->getUniqueID("vtiger_field").",'salesorder_no','vtiger_salesorder',1,'4','salesorder_no','SalesOrder No',1,0,0,100,3,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_salesorder ADD COLUMN salesorder_no varchar(100) not null"); + +$blockid = getBlockId(21,'LBL_PO_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (21,".$adb->getUniqueID("vtiger_field").",'purchaseorder_no','vtiger_purchaseorder',1,'4','purchaseorder_no','PurchaseOrder No',1,0,0,100,2,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_purchaseorder ADD COLUMN purchaseorder_no varchar(100) not null"); + +$blockid = getBlockId(20,'LBL_QUOTE_INFORMATION'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (20,".$adb->getUniqueID("vtiger_field").",'quote_no','vtiger_quotes',1,'4','quote_no','Quote No',1,0,0,100,3,$blockid,1,'V~O',1,null,'BAS',0)"); +ExecuteQuery("ALTER TABLE vtiger_quotes ADD COLUMN quote_no varchar(100) not null"); + + +$field_result = $adb->query("select tabid, fieldid from vtiger_field where uitype='4'"); +$num_fields = $adb->num_rows($field_result); +for($i = 0; $i<$num_fields; $i++) +{ + $tab_id = $adb->query_result($field_result,$i,'tabid'); + $fld_id = $adb->query_result($field_result,$i,'fieldid'); + addFieldSecurity($tab_id, $fld_id, false); +} + +ExecuteQuery("update vtiger_field set uitype = '4' where tabid = 23 and columnname = 'invoice_no' "); +ExecuteQuery("update vtiger_field set typeofdata = 'V~O' where tabid = 23 and columnname = 'invoice_no' "); + +// ADD COLUMN TO SPECIFIED MODULE CUSTOM VIEW / FILTER. +function custom_addCustomFilterColumn($module, $filtername, $tablename, $columnname, $fieldname, $displayinfo, $columnindex=0) { + global $adb; + + $result = $adb->query("SELECT * FROM vtiger_customview WHERE entitytype = '".$adb->sql_escape_string($module)."' AND viewname = '".$adb->sql_escape_string($filtername)."'"); + if($adb->num_rows($result) > 0) { + $cvid = $adb->query_result($result, 0, 'cvid'); + } + + if($cvid == null) return; + + // (cvid, columnindex) is combined key so we have to update columnindex suitably + ExecuteQuery("UPDATE vtiger_cvcolumnlist set columnindex=columnindex+1 WHERE cvid = $cvid AND columnindex >= $columnindex ORDER BY columnindex DESC"); + + $cvcolumnname_value = $tablename . ":" . $columnname . ":" . $fieldname . ":" . $displayinfo; + ExecuteQuery("INSERT INTO vtiger_cvcolumnlist(cvid, columnindex, columnname) VALUES ($cvid, $columnindex, '$cvcolumnname_value')"); +} + +// REMOVE SPECIFIED COLUMN FROM MODULE FILTER. +function custom_removeCustomFilterColumn($module, $filtername, $tablename, $columnname, $fieldname, $displayinfo) { + global $adb; + + $result = $adb->query("SELECT * FROM vtiger_customview WHERE entitytype = '".$adb->sql_escape_string($module)."' AND viewname = '".$adb->sql_escape_string($filtername)."'"); + if($adb->num_rows($result) > 0) { + $cvid = $adb->query_result($result, 0, 'cvid'); + } + + if($cvid == null) return; + + $cvcolumnname_value = $tablename . ":" . $columnname . ":" . $fieldname . ":" . $displayinfo; + ExecuteQuery("DELETE FROM vtiger_cvcolumnlist where cvid = $cvid and columnname like '$cvcolumnname_value:%' "); +} + +custom_addCustomFilterColumn('Leads', 'All', 'vtiger_leaddetails', 'lead_no', 'lead_no', 'Leads_Lead_No:V'); +custom_addCustomFilterColumn('Accounts', 'All', 'vtiger_account', 'account_no', 'account_no', 'Accounts_Account_No:V'); +custom_addCustomFilterColumn('Campaigns', 'All', 'vtiger_campaign', 'campaign_no', 'campaign_no', 'Campaigns_Campaign_No:V'); +custom_addCustomFilterColumn('Contacts', 'All', 'vtiger_contactdetails', 'contact_no', 'contact_no', 'Contacts_Contact_Id:V'); +custom_addCustomFilterColumn('Potentials', 'All', 'vtiger_potential', 'potential_no', 'potential_no', 'Potentials_Potential_No:V'); + +custom_removeCustomFilterColumn('HelpDesk', 'All', 'vtiger_crmentity', 'crmid', '', 'HelpDesk_Ticket_ID'); +custom_addCustomFilterColumn('HelpDesk', 'All', 'vtiger_troubletickets', 'ticket_no', 'ticket_no', 'HelpDesk_Ticket_No:V'); + +custom_removeCustomFilterColumn('Quotes', 'All', 'vtiger_crmentity', 'crmid', '', 'Quotes_Quote_No'); +custom_addCustomFilterColumn('Quotes', 'All', 'vtiger_quotes', 'quote_no', 'quote_no', 'Quotes_Quote_No:V'); + +custom_removeCustomFilterColumn('SalesOrder', 'All', 'vtiger_crmentity', 'crmid','','SalesOrder_Order_No'); +custom_addCustomFilterColumn('SalesOrder', 'All', 'vtiger_salesorder', 'salesorder_no', 'salesorder_no', 'SalesOrder_SalesOrder_No:V'); + +custom_removeCustomFilterColumn('PurchaseOrder', 'All', 'vtiger_crmentity', 'crmid', '', 'PurchaseOrder_Order_No'); +custom_addCustomFilterColumn('PurchaseOrder', 'All', 'vtiger_purchaseorder', 'purchaseorder_no', 'purchaseorder_no', 'PurchaseOrder_PurchaseOrder_No:V'); + +custom_addCustomFilterColumn('Products', 'All', 'vtiger_products', 'product_no', 'product_no', 'Products_Product_No:V'); +custom_addCustomFilterColumn('Vendors', 'All', 'vtiger_vendor', 'vendor_no', 'vendor_no', 'Vendors_Vendor_No:V'); +custom_addCustomFilterColumn('PriceBooks', 'All', 'vtiger_pricebook', 'pricebook_no', 'pricebook_no', 'PriceBooks_PriceBook_No:V'); + +custom_removeCustomFilterColumn('Faq', 'All', 'vtiger_faq', 'id', '', 'Faq_FAQ_Id'); +custom_addCustomFilterColumn('Faq', 'All', 'vtiger_faq', 'faq_no', 'faq_no', 'Faq_Faq_No:V'); + +custom_addCustomFilterColumn('Documents', 'All', 'vtiger_notes', 'note_no', 'note_no', 'Notes_Note_No:V'); +// Sequence number customization ends + +/*asterisk related changes*/ +$sql = "drop table if exists vtiger_asteriskextensions"; +ExecuteQuery($sql); +$sql = "create table vtiger_asteriskextensions (userid int(11), asterisk_extension varchar(50), use_asterisk varchar(3)) ENGINE=InnoDB DEFAULT CHARSET=utf8"; +ExecuteQuery($sql); +$sql = "drop table if exists vtiger_asterisk"; +ExecuteQuery($sql); +$sql = "create table vtiger_asterisk (server varchar(30), port varchar(30), username varchar(50), password varchar(50), version varchar(50)) ENGINE=InnoDB DEFAULT CHARSET=utf8"; +ExecuteQuery($sql); +$sql = "drop table if exists vtiger_asteriskincomingcalls"; +ExecuteQuery($sql); +$sql = "create table vtiger_asteriskincomingcalls (from_number varchar(50) not null, from_name varchar(50) not null, to_number varchar(50) not null, callertype varchar(30), flag int(19), timer int(19)) ENGINE=InnoDB DEFAULT CHARSET=utf8"; +ExecuteQuery($sql); +$sql = "drop table if exists vtiger_asteriskoutgoingcalls"; +ExecuteQuery($sql); +$sql = "create table vtiger_asteriskoutgoingcalls (userid int(11) not null, from_number varchar(30) not null, to_number varchar(30) not null) ENGINE=InnoDB DEFAULT CHARSET=utf8"; +ExecuteQuery($sql); + +/*asterisk changes end here*/ +/* Updated phone field uitype */ +ExecuteQuery("update vtiger_field set uitype='11' where fieldname='mobile' and tabid=".getTabid('Leads')); +ExecuteQuery("update vtiger_field set uitype='11' where fieldname='mobile' and tabid=".getTabid('Contacts')); +ExecuteQuery("update vtiger_field set uitype='11' where fieldname='fax' and tabid=".getTabid('Leads')); +ExecuteQuery("update vtiger_field set uitype='11' where fieldname='fax' and tabid=".getTabid('Contacts')); +ExecuteQuery("update vtiger_field set uitype='11' where fieldname='fax' and tabid=".getTabid('Accounts')); + +/* Support to Configure the functionality of Updating Inventory Stock for Invoice/SalesOrder */ +ExecuteQuery("ALTER TABLE vtiger_inventoryproductrel ADD COLUMN incrementondel int(11) not null default '0'"); +$invoiceids = $adb->pquery("SELECT invoiceid from vtiger_invoice",array()); +$noOfRows = $adb->num_rows($invoiceids); +for($i=0;$i<$noOfRows;$i++){ + $adb->pquery("UPDATE vtiger_inventoryproductrel SET incrementondel = 1 WHERE id=?",array($adb->query_result($invoiceids,$i,"invoiceid"))); +} + +$emm->addEntityMethod("SalesOrder","UpdateInventory","include/InventoryHandler.php","handleInventoryProductRel");//Adding EntityMethod for Updating Products data after creating SalesOrder +$emm->addEntityMethod("Invoice","UpdateInventory","include/InventoryHandler.php","handleInventoryProductRel");//Adding EntityMethod for Updating Products data after creating Invoice + +$vtWorkFlow = new VTWorkflowManager($adb); +$invWorkFlow = $vtWorkFlow->newWorkFlow("Invoice"); +$invWorkFlow->test = '[{"fieldname":"subject","operation":"does not contain","value":"`!`"}]'; +$invWorkFlow->description = "UpdateInventoryProducts On Every Save"; +$vtWorkFlow->save($invWorkFlow); + +$tm = new VTTaskManager($adb); +$task = $tm->createTask('VTEntityMethodTask', $invWorkFlow->id); +$task->active=true; +$task->methodName = "UpdateInventory"; +$tm->saveTask($task); + +/* Support to track if a module is of CrmEntity type or not */ +ExecuteQuery("ALTER TABLE vtiger_tab ADD COLUMN isentitytype INT NOT NULL DEFAULT 1"); +ExecuteQuery("UPDATE vtiger_tab SET isentitytype=0 WHERE name IN ('Home','Dashboard','Rss','Reports','Portal','Users','Recyclebin')"); + +/* Support for different languages to be stored in database instead of config file - Vtlib */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_language(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), " . + "prefix VARCHAR(10), label VARCHAR(30), lastupdated DATETIME, sequence INT, isdefault INT(1), active INT(1)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* Register default language English. This will automatically register all the other langauges from config file */ +require_once('vtlib/Vtiger/Language.php'); +$vtlanguage = new Vtiger_Language(); +$vtlanguage->register('en_us','US English','English',true,true,true); + +/* To store relationship between the modules in a common table */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_crmentityrel (crmid int(11) NOT NULL, module varchar(100) NOT NULL, relcrmid int(11) NOT NULL, relmodule varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* To store the field to module relationship for uitype 10 */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_fieldmodulerel (fieldid int(11) NOT NULL, module varchar(100) NOT NULL, relmodule varchar(100) NOT NULL, + status varchar(10) default NULL, sequence int(11) default NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* Making users and groups depends on vtiger_users_seq */ +$max_grp_id = $adb->query("SELECT MAX(groupid) as maxid from vtiger_groups"); +$maxid = $adb->query_result($max_grp_id,0,"maxid"); + +$user_result = $adb->query("select max(id) as userid from vtiger_users"); +$inc_num = $adb->query_result($user_result,0,"userid"); + +$adb->getUniqueId("vtiger_users");//Creates vtiger_users_seq table if not exists. +$seq_id = $inc_num+$maxid; +$adb->pquery("UPDATE vtiger_users_seq SET id=?",array($seq_id)); + +$tab_info = array( + "vtiger_group2grouprel"=>array("fk_2_vtiger_group2grouprel","(groupid)","vtiger_groups(groupid)"), + "vtiger_users2group"=>array("fk_1_vtiger_users2group","(groupid)","vtiger_groups(groupid)"), + "vtiger_group2role"=>array("fk_1_vtiger_group2role","(groupid)","vtiger_groups(groupid)"), + "vtiger_group2rs"=>array("fk_1_vtiger_group2rs","(groupid)","vtiger_groups(groupid)"), + "vtiger_datashare_grp2grp"=>array("fk_2_vtiger_datashare_grp2grp","(share_groupid)","vtiger_groups(groupid)"), + "vtiger_datashare_grp2grp"=>array("fk_3_vtiger_datashare_grp2grp","(to_groupid)","vtiger_groups(groupid)"), + "vtiger_datashare_grp2role"=>array("fk_2_vtiger_datashare_grp2role","(share_groupid)","vtiger_groups(groupid)"), + "vtiger_datashare_role2group"=>array("fk_2_vtiger_datashare_role2group","(to_groupid)","vtiger_groups(groupid)"), + "vtiger_datashare_grp2rs"=>array("fk_2_vtiger_datashare_grp2rs","(share_groupid)","vtiger_groups(groupid)"), + "vtiger_datashare_rs2grp"=>array("fk_2_vtiger_datashare_rs2grp","(to_groupid)","vtiger_groups(groupid)"), + "vtiger_tmp_read_group_sharing_per"=>array("fk_1_vtiger_tmp_read_group_sharing_per","(sharedgroupid)","vtiger_groups(groupid)"), + "vtiger_tmp_write_group_sharing_per"=>array("fk_1_vtiger_tmp_write_group_sharing_per","(sharedgroupid)","vtiger_groups(groupid)"), +); +$drop_key_array = array("vtiger_group2grouprel","vtiger_datashare_grp2grp"); + +foreach($tab_info as $table=>$value){ + //Update constraints for vtiger_group2grouprel table + if(in_array($table,$drop_key_array)){ + ExecuteQuery("ALTER TABLE $table DROP FOREIGN KEY ".$value[0]); + } + ExecuteQuery("ALTER TABLE $table ADD CONSTRAINT ".$value[0]." FOREIGN KEY ".$value[1]." REFERENCES ".$value[2]." ON DELETE CASCADE ON UPDATE CASCADE"); +} + +$grp_result = $adb->query("select groupid from vtiger_groups ORDER BY groupid ASC"); +$num_grps = $adb->num_rows($grp_result); + +for($i=$num_grps-1; $i>=0; $i--) { + $oldId = $adb->query_result($grp_result,$i,"groupid"); + $newId = $adb->getUniqueId("vtiger_users"); + + ExecuteQuery("UPDATE vtiger_groups set groupid = $newId where groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_users2group set groupid = $newId where groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_group2grouprel set groupid = $newId where groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_group2role set groupid = $newId where groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_group2rs set groupid = $newId where groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_datashare_grp2grp set share_groupid = $newId where share_groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_datashare_grp2grp set to_groupid = $newId where to_groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_datashare_grp2role set share_groupid = $newId where share_groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_datashare_grp2rs set share_groupid = $newId where share_groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_datashare_role2group set to_groupid = $newId where to_groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_datashare_rs2grp set to_groupid = $newId where to_groupid = $oldId"); + ExecuteQuery("UPDATE vtiger_tmp_read_group_sharing_per set sharedgroupid = $newId where sharedgroupid = $oldId"); + ExecuteQuery("UPDATE vtiger_tmp_write_group_sharing_per set sharedgroupid = $newId where sharedgroupid = $oldId"); +} + +$sql_result = $adb->query("select crmid,setype from vtiger_crmentity where smownerid=0 order by setype"); +$num_rows = $adb->num_rows($sql_result); +$groupTables_array = array ( + 'Leads'=>array ('vtiger_leadgrouprelation','leadid'), + 'Accounts'=>array ('vtiger_accountgrouprelation','accountid'), + 'Contacts'=>array ('vtiger_contactgrouprelation','contactid'), + 'Potentials'=>array ('vtiger_potentialgrouprelation','potentialid'), + 'Quotes'=>array ('vtiger_quotegrouprelation','quoteid'), + 'SalesOrder'=>array ('vtiger_sogrouprelation','salesorderid'), + 'Invoice'=>array ('vtiger_invoicegrouprelation','invoiceid'), + 'PurchaseOrder'=>array ('vtiger_pogrouprelation','purchaseorderid'), + 'HelpDesk'=>array ('vtiger_ticketgrouprelation','ticketid'), + 'Campaigns'=>array ('vtiger_campaigngrouprelation','campaignid'), + 'Calendar'=>array ('vtiger_activitygrouprelation','activityid') + ); + +foreach($groupTables_array as $module=>$index){ + $modulereltable = $index[0]; + $modulerelindex = $index[1]; + ExecuteQuery("update vtiger_crmentity INNER JOIN {$modulereltable} ON vtiger_crmentity.crmid = {$modulereltable}.{$modulerelindex} INNER JOIN vtiger_groups ON vtiger_groups.groupname = {$modulereltable}.groupname set smownerid = vtiger_groups.groupid"); + ExecuteQuery("UPDATE vtiger_crmentity SET smownerid=1 WHERE smownerid=0 AND setype='{$module}'"); +} +// user-group ends + +/* Product Comment was Missing in Inventory PDF's - Fixed this by eliminating column product_description from vtiger_products + * and referring to description column of vtiger_crmentity wherever required */ +ExecuteQuery("UPDATE vtiger_crmentity, vtiger_products SET vtiger_crmentity.description=vtiger_products.product_description + WHERE vtiger_products.productid = vtiger_crmentity.crmid"); +ExecuteQuery("ALTER TABLE vtiger_products DROP COLUMN product_description"); +ExecuteQuery("UPDATE vtiger_field set fieldname='description', columnname='description', tablename='vtiger_crmentity' + WHERE tablename='vtiger_products' AND fieldname='product_description'"); + +/* Remove Products from all the Main tabs except for Inventory */ +$productTabId = getTabid('Products'); + +$inventoryTabRes = $adb->query("SELECT parenttabid FROM vtiger_parenttab WHERE parenttab_label='Inventory'"); +if($adb->num_rows($inventoryTabRes)>0){ + $inventoryTabId = $adb->query_result($inventoryTabRes, 0, 'parenttabid'); + ExecuteQuery("DELETE FROM vtiger_parenttabrel WHERE tabid=$productTabId AND parenttabid != $inventoryTabId"); +} + +$adb->query("ALTER TABLE vtiger_producttaxrel DROP FOREIGN KEY fk_1_vtiger_producttaxrel"); +$adb->query("ALTER TABLE vtiger_pricebookproductrel DROP FOREIGN KEY fk_2_vtiger_pricebookproductrel"); + +/* Vtlib Changes - Table added to store different types of links */ +/*ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_links (linkid INT AUTO_INCREMENT NOT NULL PRIMARY KEY, + tabid INT, linktype VARCHAR(20), linklabel VARCHAR(30), linkurl VARCHAR(255), linkicon VARCHAR(100), sequence INT) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE INDEX link_tabidtype_idx ON vtiger_links(tabid,linktype)");*/ + +/* Column added to vtiger_tab to track the version of the module */ +if(!in_array('version', $adb->getColumnNames('vtiger_tab'))) { + ExecuteQuery("ALTER TABLE vtiger_tab ADD COLUMN version VARCHAR(10)"); +} + +/*adding the notebook to vtiger*/ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_notebook_contents (userid int(19) not null, notebookid int(19), contents text) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +/*notbook changes end*/ + +/* Move Settings Page Information to Database */ +// This function moves the settings page to database +function moveSettingsToDatabase($adb){ + $adb->query("drop table if exists vtiger_settings_blocks"); + $adb->query("drop table if exists vtiger_settings_field"); + $adb->query("CREATE TABLE IF NOT EXISTS vtiger_settings_blocks (blockid int(19), label varchar(250), sequence int(19), primary key pk_vtiger_settings_blocks (blockid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + $adb->query("CREATE TABLE IF NOT EXISTS vtiger_settings_field (fieldid int(19), blockid int(19), name varchar(250), iconpath text, description text, linkto text, sequence int(19), active int(19) default 0,foreign key fk_vtiger_settings_fields (blockid) references vtiger_settings_blocks(blockid) on delete cascade) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + + //icons for all fields + $icons = array("ico-users.gif", + "ico-roles.gif", + "ico-profile.gif", + "ico-groups.gif", + "shareaccess.gif", + "orgshar.gif", + "audit.gif", + "set-IcoLoginHistory.gif", + "vtlib_modmng.gif", + "picklist.gif", + "ViewTemplate.gif", + "mailmarge.gif", + "notification.gif", + "inventory.gif", + "company.gif", + "ogmailserver.gif", + "backupserver.gif", + "assign.gif", + "currency.gif", + "taxConfiguration.gif", + "system.gif", + "proxy.gif", + "announ.gif", + "set-IcoTwoTabConfig.gif", + "terms.gif", + "settingsInvNumber.gif", + "mailScanner.gif", + "settingsWorkflow.png"); + + //labels for blocks + $blocks = array('LBL_MODULE_MANAGER', + 'LBL_USER_MANAGEMENT', + 'LBL_STUDIO', + 'LBL_COMMUNICATION_TEMPLATES', + 'LBL_OTHER_SETTINGS'); + + //field names + $names = array('LBL_USERS', + 'LBL_ROLES', + 'LBL_PROFILES', + 'USERGROUPLIST', + 'LBL_SHARING_ACCESS', + 'LBL_FIELDS_ACCESS', + 'LBL_AUDIT_TRAIL', + 'LBL_LOGIN_HISTORY_DETAILS', + 'VTLIB_LBL_MODULE_MANAGER', + 'LBL_PICKLIST_EDITOR', + 'EMAILTEMPLATES', + 'LBL_MAIL_MERGE', + 'NOTIFICATIONSCHEDULERS', + 'INVENTORYNOTIFICATION', + 'LBL_COMPANY_DETAILS', + 'LBL_MAIL_SERVER_SETTINGS', + 'LBL_BACKUP_SERVER_SETTINGS', + 'LBL_ASSIGN_MODULE_OWNERS', + 'LBL_CURRENCY_SETTINGS', + 'LBL_TAX_SETTINGS', + 'LBL_SYSTEM_INFO', + 'LBL_PROXY_SETTINGS', + 'LBL_ANNOUNCEMENT', + 'LBL_DEFAULT_MODULE_VIEW', + 'INVENTORYTERMSANDCONDITIONS', + 'LBL_CUSTOMIZE_MODENT_NUMBER', + 'LBL_MAIL_SCANNER', + 'LBL_LIST_WORKFLOWS',); + + $name_blocks = array('LBL_USERS'=>'LBL_USER_MANAGEMENT', + 'LBL_ROLES'=>'LBL_USER_MANAGEMENT', + 'LBL_PROFILES'=>'LBL_USER_MANAGEMENT', + 'USERGROUPLIST'=>'LBL_USER_MANAGEMENT', + 'LBL_SHARING_ACCESS'=>'LBL_USER_MANAGEMENT', + 'LBL_FIELDS_ACCESS'=>'LBL_USER_MANAGEMENT', + 'LBL_AUDIT_TRAIL'=>'LBL_USER_MANAGEMENT', + 'LBL_LOGIN_HISTORY_DETAILS'=>'LBL_USER_MANAGEMENT', + 'VTLIB_LBL_MODULE_MANAGER'=>'LBL_STUDIO', + 'LBL_PICKLIST_EDITOR'=>'LBL_STUDIO', + 'EMAILTEMPLATES'=>'LBL_COMMUNICATION_TEMPLATES', + 'LBL_MAIL_MERGE'=>'LBL_COMMUNICATION_TEMPLATES', + 'NOTIFICATIONSCHEDULERS'=>'LBL_COMMUNICATION_TEMPLATES', + 'INVENTORYNOTIFICATION'=>'LBL_COMMUNICATION_TEMPLATES', + 'LBL_COMPANY_DETAILS'=>'LBL_COMMUNICATION_TEMPLATES', + 'LBL_MAIL_SERVER_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_BACKUP_SERVER_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_ASSIGN_MODULE_OWNERS'=>'LBL_OTHER_SETTINGS', + 'LBL_CURRENCY_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_TAX_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_SYSTEM_INFO'=>'LBL_OTHER_SETTINGS', + 'LBL_PROXY_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_ANNOUNCEMENT'=>'LBL_OTHER_SETTINGS', + 'LBL_DEFAULT_MODULE_VIEW'=>'LBL_OTHER_SETTINGS', + 'INVENTORYTERMSANDCONDITIONS'=>'LBL_OTHER_SETTINGS', + 'LBL_CUSTOMIZE_MODENT_NUMBER'=>'LBL_OTHER_SETTINGS', + 'LBL_MAIL_SCANNER'=>'LBL_OTHER_SETTINGS', + 'LBL_LIST_WORKFLOWS'=>'LBL_OTHER_SETTINGS',); + + //description for fields + $description = array('LBL_USER_DESCRIPTION', + 'LBL_ROLE_DESCRIPTION', + 'LBL_PROFILE_DESCRIPTION', + 'LBL_GROUP_DESCRIPTION', + 'LBL_SHARING_ACCESS_DESCRIPTION', + 'LBL_SHARING_FIELDS_DESCRIPTION', + 'LBL_AUDIT_DESCRIPTION', + 'LBL_LOGIN_HISTORY_DESCRIPTION', + 'VTLIB_LBL_MODULE_MANAGER_DESCRIPTION', + 'LBL_PICKLIST_DESCRIPTION', + 'LBL_EMAIL_TEMPLATE_DESCRIPTION', + 'LBL_MAIL_MERGE_DESCRIPTION', + 'LBL_NOTIF_SCHED_DESCRIPTION', + 'LBL_INV_NOTIF_DESCRIPTION', + 'LBL_COMPANY_DESCRIPTION', + 'LBL_MAIL_SERVER_DESCRIPTION', + 'LBL_BACKUP_SERVER_DESCRIPTION', + 'LBL_MODULE_OWNERS_DESCRIPTION', + 'LBL_CURRENCY_DESCRIPTION', + 'LBL_TAX_DESCRIPTION', + 'LBL_SYSTEM_DESCRIPTION', + 'LBL_PROXY_DESCRIPTION', + 'LBL_ANNOUNCEMENT_DESCRIPTION', + 'LBL_DEFAULT_MODULE_VIEW_DESC', + 'LBL_INV_TANDC_DESCRIPTION', + 'LBL_CUSTOMIZE_MODENT_NUMBER_DESCRIPTION', + 'LBL_MAIL_SCANNER_DESCRIPTION', + 'LBL_LIST_WORKFLOWS_DESCRIPTION'); + + + $links = array('index.php?module=Administration&action=index&parenttab=Settings', + 'index.php?module=Settings&action=listroles&parenttab=Settings', + 'index.php?module=Settings&action=ListProfiles&parenttab=Settings', + 'index.php?module=Settings&action=listgroups&parenttab=Settings', + 'index.php?module=Settings&action=OrgSharingDetailView&parenttab=Settings', + 'index.php?module=Settings&action=DefaultFieldPermissions&parenttab=Settings', + 'index.php?module=Settings&action=AuditTrailList&parenttab=Settings', + 'index.php?module=Settings&action=ListLoginHistory&parenttab=Settings', + 'index.php?module=Settings&action=ModuleManager&parenttab=Settings', + 'index.php?module=PickList&action=PickList&parenttab=Settings', + 'index.php?module=Settings&action=listemailtemplates&parenttab=Settings', + 'index.php?module=Settings&action=listwordtemplates&parenttab=Settings', + 'index.php?module=Settings&action=listnotificationschedulers&parenttab=Settings', + 'index.php?module=Settings&action=listinventorynotifications&parenttab=Settings', + 'index.php?module=Settings&action=OrganizationConfig&parenttab=Settings', + 'index.php?module=Settings&action=EmailConfig&parenttab=Settings', + 'index.php?module=Settings&action=BackupServerConfig&parenttab=Settings', + 'index.php?module=Settings&action=ListModuleOwners&parenttab=Settings', + 'index.php?module=Settings&action=CurrencyListView&parenttab=Settings', + 'index.php?module=Settings&action=TaxConfig&parenttab=Settings', + 'index.php?module=System&action=listsysconfig&parenttab=Settings', + 'index.php?module=Settings&action=ProxyServerConfig&parenttab=Settings', + 'index.php?module=Settings&action=Announcements&parenttab=Settings', + 'index.php?module=Settings&action=DefModuleView&parenttab=Settings', + 'index.php?module=Settings&action=OrganizationTermsandConditions&parenttab=Settings', + 'index.php?module=Settings&action=CustomModEntityNo&parenttab=Settings', + 'index.php?module=Settings&action=MailScanner&parenttab=Settings', + 'index.php?module=com_vtiger_workflow&action=workflowlist&parenttab=Settings',); + + //insert settings blocks + $count = count($blocks); + for($i=0; $i<$count; $i++){ + $adb->query("insert into vtiger_settings_blocks values (".$adb->getUniqueID('vtiger_settings_blocks').", '$blocks[$i]', $i+1)"); + } + + $count = count($icons); + //insert settings fields + for($i=0, $seq=1; $i<$count; $i++, $seq++){ + if($i==8 || $i==12 || $i==18) { + $seq = 1; + } + $adb->query("insert into vtiger_settings_field (fieldid, blockid, name, iconpath, description, linkto, sequence) values (".$adb->getUniqueID('vtiger_settings_field').", ".getSettingsBlockId($name_blocks[$names[$i]]).", '$names[$i]', '$icons[$i]', '$description[$i]', '$links[$i]', $seq)"); + } + //hide the system details tab for now + $adb->query("update vtiger_settings_field set active=1 where name='LBL_SYSTEM_INFO'"); +} +//move settings page to database starts +moveSettingsToDatabase($adb); +//settings page to database ends +// END + + +/* Email status tracking*/ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_email_access(crmid INT, mailid INT, accessdate DATE, accesstime TIME) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_email_track(crmid INT, mailid INT, access_count INT, primary key(crmid, mailid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +$fieldid = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) VALUES ('10',".$fieldid.", 'access_count', 'vtiger_email_track', '1', '25', 'access_count', 'Access Count', '1', '0', '0', '100', '6', '21', '3', 'V~O', '1', NULL, 'BAS', 0)"); +addFieldSecurity(10, $fieldid, 'false'); +// END + +/* Reports Revamped */ +ExecuteQuery("ALTER TABLE vtiger_report ADD COLUMN owner int(11) NOT NULL"); +ExecuteQuery("UPDATE vtiger_field INNER JOIN vtiger_field as vtiger_field1 on vtiger_field1.tabid=vtiger_field.tabid SET vtiger_field.block = vtiger_field1.block WHERE vtiger_field.fieldname='faq_answer' and vtiger_field1.fieldname='question' and vtiger_field.tabid=15"); +ExecuteQuery("ALTER TABLE vtiger_report ADD COLUMN sharingtype varchar(200) NOT NULL DEFAULT 'Private'"); +ExecuteQuery("UPDATE vtiger_report SET sharingtype='Public', owner=1"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_reportsharing(reportid int(19) not null,shareid int(19) not null,setype varchar(200) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_reportfilters(filterid int(11) not null,name varchar(200) not null) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("INSERT INTO vtiger_reportfilters values(1,'Private')"); +ExecuteQuery("INSERT INTO vtiger_reportfilters values(2,'Public')"); +ExecuteQuery("INSERT INTO vtiger_reportfilters values(3,'Shared')"); + +/* Account Hierarchy */ +populateLinks(); + +/* Product Bundles Revamping */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_inventorysubproductrel(id int(19) NOT NULL, sequence_no INT(10) NOT NULL, productid INT(19) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* Support for Calendar Custom Fields */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_activitycf(activityid INT default '0' primary key) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +ExecuteQuery("insert into vtiger_blocks values (".$adb->getUniqueID('vtiger_blocks').",9,'LBL_CUSTOM_INFORMATION',3,0,0,0,0,0,1)"); +ExecuteQuery("insert into vtiger_blocks values (".$adb->getUniqueID('vtiger_blocks').",16,'LBL_CUSTOM_INFORMATION',4,0,0,0,0,0,1)"); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable) values (16,".$adb->getUniqueID('vtiger_field').",'contactid','vtiger_cntactivityrel',1,'57','contact_id','Contact Name',1,0,0,100,1,19,1,'I~O',1,null,'BAS',1)"); + +/* Added new field Help Info for vtiger_field table */ +if(!in_array('helpinfo', $adb->getColumnNames('vtiger_field'))) { + ExecuteQuery("ALTER TABLE vtiger_field ADD COLUMN helpinfo TEXT"); +} + +/* Add Services and Service Contracts Module */ + +// Added Hours and Days fields for HelpDesk module. +$helpDeskTabid = getTabid('HelpDesk'); +$ttBlockid = getBlockId($helpDeskTabid,'LBL_TICKET_INFORMATION'); + +$tt_field1 = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values ($helpDeskTabid,$tt_field1,'hours','vtiger_troubletickets',1,'1','hours','Hours',1,0,0,100,9,$ttBlockid,1,'I~O',1,null,'BAS',1, + 'This gives the estimated hours for the Ticket
    When the same ticket is added to a Service Contract, based on the Tracking Unit of the Service Contract, Used units is updated whenever a ticket is Closed.')"); +addFieldSecurity($helpDeskTabid, $tt_field1); +ExecuteQuery("ALTER TABLE vtiger_troubletickets ADD COLUMN hours VARCHAR(200)"); + +$tt_field2 = $adb->getUniqueID('vtiger_field'); +ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values ($helpDeskTabid,$tt_field2,'days','vtiger_troubletickets',1,'1','days','Days',1,0,0,100,10,$ttBlockid,1,'I~O',1,null,'BAS',1, + 'This gives the estimated days for the Ticket
    When the same ticket is added to a Service Contract, based on the Tracking Unit of the Service Contract, Used units is updated whenever a ticket is Closed.')"); +addFieldSecurity($helpDeskTabid, $tt_field2); +ExecuteQuery("ALTER TABLE vtiger_troubletickets ADD COLUMN days VARCHAR(200)"); +// Adding fields ends here + +//layout editor changes +$helpdesktabid = getTabid('HelpDesk'); +$invoicetabid = getTabid('Invoice'); +$salesordertabid = getTabid('SalesOrder'); +$purchaseorder = getTabid('PurchaseOrder'); +$faqtabid = getTabid('Faq'); +$quotes = getTabid('Quotes'); +$contacttabid = getTabid('Contacts'); +$campaigntabid = getTabid('Campaigns'); +$leadtabid = getTabid('Leads'); +$potentialtabid = getTabid('Potentials'); +$pricebooktabid = getTabid('PriceBooks'); +$producttabid = getTabid('Products'); +$vendortabid= getTabid('Vendors'); +$accounttabid = getTabid('Accounts'); + +ExecuteQuery("alter table vtiger_blocks add column iscustom int default 0"); + +ExecuteQuery("update vtiger_field set presence=2"); +ExecuteQuery("update vtiger_field set presence=0 where quickcreate=0 or fieldname='createdtime' or fieldname='modifiedtime' or typeofdata like '%M';"); +ExecuteQuery("update vtiger_field set presence=0 where fieldname in ('update_log','parent_id','comments','solution') and tabid=$helpdesktabid"); +ExecuteQuery("update vtiger_field set presence=0 where fieldname='potentialname'"); +ExecuteQuery("update vtiger_field set presence=0 where fieldname = 'comments' and tabid = $faqtabid"); +ExecuteQuery("update vtiger_field set typeofdata='I~M',presence=2 where fieldname='account_id' and tabid =$potentialtabid "); +ExecuteQuery("update vtiger_field set typeofdata='I~M',presence=2 where fieldname='account_id' and tabid =$quotes"); +ExecuteQuery("update vtiger_field set typeofdata='I~M',presence=2 where fieldname='account_id' and tabid =$salesordertabid"); +ExecuteQuery("update vtiger_field set typeofdata='I~M',presence=2 where fieldname='account_id' and tabid =$invoicetabid"); + +ExecuteQuery("update vtiger_field set presence=0,quickcreate=2 where fieldname='account_id' and tabid = $contacttabid"); +ExecuteQuery("update vtiger_field set presence=0,quickcreate=0 where fieldname='taxclass' and tabid=$producttabid"); +ExecuteQuery("update vtiger_field set presence = 0,quickcreate=3 where block = $new_block_id "); //for recurring invoice block the fields are always active +ExecuteQuery("update vtiger_field set quickcreate=3 where fieldname='createdtime' or fieldname='modifiedtime'"); +ExecuteQuery("update vtiger_field set quickcreate=3 where tabid in ($invoicetabid,$salesordertabid,$purchaseorder,$quotes,$faqtabid)"); +ExecuteQuery("update vtiger_field set quickcreate=1 where fieldname in ('subject','account_id','bill_street','ship_street') and tabid= $invoicetabid"); +ExecuteQuery("update vtiger_field set quickcreate=1 where fieldname in ('subject','account_id','bill_street','ship_street') and tabid= $salesordertabid"); +ExecuteQuery("update vtiger_field set quickcreate=1 where fieldname in ('subject','vendor_id','bill_street','ship_street') and tabid = $purchaseorder"); +ExecuteQuery("update vtiger_field set quickcreate=1 where fieldname in ('subject','account_id','bill_street','ship_street') and tabid= $quotes"); + +ExecuteQuery("update vtiger_field set masseditable=0 where tabid = $documents_tab_id or fieldname ='createdtime' or fieldname = 'modifiedtime'"); +ExecuteQuery("update vtiger_field set typeofdata='V~O',presence=0 where uitype=4"); +ExecuteQuery("update vtiger_field set quickcreate=3,masseditable=0 where uitype=4 AND displaytype=2"); +ExecuteQuery("update vtiger_field set quickcreate=3 where fieldname='imagename'"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('website','phone') and tabid = $accounttabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('closingdate','campaigntype','expectedresponse','product_id','campaignstatus') and tabid = $campaigntabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('firstname','phone','email') and tabid = $contacttabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('firstname','phone','email','company') and tabid = $leadtabid "); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('closingdate','sales_stage','amount','account_id') and tabid = $potentialtabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('active') and tabid = $pricebooktabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('discontinued','unit_price') and tabid = $producttabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('phone','email') and tabid = $vendortabid"); +ExecuteQuery("update vtiger_field set quickcreate=2,presence=2 where fieldname in('ticket_title','ticketstatus') and tabid = $helpdesktabid"); +$faqbasicblock = getBlockId($faqtabid,'LBL_FAQ_INFORMATION'); + +ExecuteQuery("update vtiger_field set block = $faqbasicblock ,sequence = 7 where fieldname = 'question' and tabid = $faqtabid"); +ExecuteQuery("update vtiger_field set block = $faqbasicblock ,sequence = 8 where fieldname = 'faq_answer' and tabid = $faqtabid"); + +/* Added support for setting a custom view as default per user basis */ +ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_user_module_preferences (userid int, tabid int, default_cvid int, primary key(userid, tabid), CONSTRAINT fk_1_vtiger_user_module_preferences FOREIGN KEY (userid) REFERENCES vtiger_users (id) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT fk_2_vtiger_user_module_preferences FOREIGN KEY (tabid) REFERENCES vtiger_tab (tabid) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* home page related changes */ +if(columnExists("homeorder", "vtiger_users")){ + ExecuteQuery("alter table vtiger_users drop column homeorder"); +} +if(columnExists("tagcloud_view", "vtiger_users")){ + ExecuteQuery("alter table vtiger_users drop column tagcloud_view"); +} +if(columnExists("defhomeview", "vtiger_users")){ + ExecuteQuery("alter table vtiger_users drop column defhomeview"); +} +ExecuteQuery("create table vtiger_home_layout (userid int(19), layout int(19)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + +/* Add Invoices to the related list of Contacts */ +ExecuteQuery("INSERT INTO vtiger_relatedlists VALUES(".$adb->getUniqueID('vtiger_relatedlists').",". getTabid('Contacts').",".getTabid('Invoice').",'get_invoices',12,'Invoice',0, 'add')"); + +/* For Webservices Support */ +require_once 'include/Webservices/Utils.php'; +webserviceMigration(); + +/* Install Vtlib Compliant Modules */ +installMandatoryModules(); +require_once('include/utils/installVtlibSelectedModules.php'); + +/*adding B2C model support*/ +ExecuteQuery("alter table vtiger_potential change accountid related_to int(19)"); +$sql = "select fieldid from vtiger_field where tabid=? and columnname=?"; +$result = $adb->pquery($sql, array(getTabid('Potentials'), 'accountid')); +$fieldid = $adb->query_result($result,0,"fieldid"); +ExecuteQuery("update vtiger_field set uitype='10', typeofdata='V~M', columnname='related_to', fieldname='related_to',fieldlabel='Related To', presence=0 where fieldid=$fieldid"); +ExecuteQuery("insert into vtiger_fieldmodulerel (fieldid, module, relmodule, status, sequence) values ($fieldid, 'Potentials', 'Accounts', NULL, 0), ($fieldid, 'Potentials', 'Contacts', NULL, 1)"); + +ExecuteQuery("update vtiger_cvcolumnlist set columnname='vtiger_potential:related_to:related_to:Potentials_Related_To:V' where columnname='vtiger_account:accountname:accountname:Potentials_Account_Name:V'"); + +// Function to call installation of mandatory modules +function installMandatoryModules(){ + + if ($handle = opendir('packages/5.1.0/mandatory')) { + + while (false !== ($file = readdir($handle))) { + $filename_arr = explode(".", $file); + $packagename = $filename_arr[0]; + if (!empty($packagename)) { + $packagepath = "packages/5.1.0/mandatory/$file"; + installVtlibModule($packagename, $packagepath); + } + } + closedir($handle); + } +} + +// Function to populate Links +function populateLinks() { + include_once('vtlib/Vtiger/Module.php'); + + // Links for Accounts module + $moduleInstance = Vtiger_Module::getInstance('Accounts'); + // Detail View Custom link + $moduleInstance->addLink( + 'DETAILVIEWBASIC', 'LBL_ADD_NOTE', + 'index.php?module=Documents&action=EditView&return_module=$MODULE$&return_action=DetailView&return_id=$RECORD$&parent_id=$RECORD$', + 'themes/images/bookMark.gif' + ); + $moduleInstance->addLink('DETAILVIEWBASIC', 'LBL_SHOW_ACCOUNT_HIERARCHY', 'index.php?module=Accounts&action=AccountHierarchy&accountid=$RECORD$'); + + $moduleInstance2 = Vtiger_Module::getInstance('Leads'); + $moduleInstance2->addLink( + 'DETAILVIEWBASIC', 'LBL_ADD_NOTE', + 'index.php?module=Documents&action=EditView&return_module=$MODULE$&return_action=DetailView&return_id=$RECORD$&parent_id=$RECORD$', + 'themes/images/bookMark.gif' + ); + + $moduleInstance3 = Vtiger_Module::getInstance('Contacts'); + $moduleInstance3->addLink( + 'DETAILVIEWBASIC', 'LBL_ADD_NOTE', + 'index.php?module=Documents&action=EditView&return_module=$MODULE$&return_action=DetailView&return_id=$RECORD$&parent_id=$RECORD$', + 'themes/images/bookMark.gif' + ); +} + +/* For Webservices Support */ +function webserviceMigration(){ + global $adb; + require_once 'include/utils/CommonUtils.php'; + require_once 'include/Webservices/Utils.php'; + $fieldTypeInfo = array('picklist'=>array(15,16),'text'=>array(19,20,21,24),'autogenerated'=>array(3),'phone'=>array(11), + 'multipicklist'=>array(33),'url'=>array(17),'skype'=>array(85),'boolean'=>array(56,156), + 'owner'=>array(53),'file'=>array(61,28)); + $referenceMapping = array("50"=>array("Accounts"),"51"=>array("Accounts"),"57"=>array("Contacts"),"58"=>array("Campaigns"), + "73"=>array("Accounts"),"75"=>array("Vendors"),"76"=>array("Potentials"),"78"=>array("Quotes"), + "80"=>array("SalesOrder"),"81"=>array("Vendors"),"101"=>array("Users"),"52"=>array("Users"), + "357"=>array("Contacts","Accounts","Leads","Users","Vendors"),"59"=>array("Products"), + "66"=>array("Leads","Accounts","Potentials","HelpDesk"),"77"=>array("Users"),"68"=>array("Contacts","Accounts"), + "117"=>array('Currency'),"116"=>array('Currency'),'26'=>array('DocumentFolders'),'10'=>array()); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_fieldtype(fieldtypeid integer(19) not null auto_increment,uitype varchar(30)not null,fieldtype varchar(200) not null,PRIMARY KEY(fieldtypeid),UNIQUE KEY uitype_idx (uitype)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_referencetype(fieldtypeid integer(19) not null,type varchar(25) not null,PRIMARY KEY(fieldtypeid,type), CONSTRAINT `fk_1_vtiger_referencetype` FOREIGN KEY (`fieldtypeid`) REFERENCES `vtiger_ws_fieldtype` (`fieldtypeid`) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_userauthtoken(userid integer(19) not null,token varchar(25) not null,expiretime INTEGER(19),PRIMARY KEY(userid,expiretime),UNIQUE KEY userid_idx (userid)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + ExecuteQuery("alter table vtiger_users add column accesskey varchar(36);"); + $fieldid = $adb->getUniqueID("vtiger_field"); + $usersTabId = getTabid("Users"); + $user_adv_block_id = getBlockId($usersTabId,'LBL_USER_ADV_OPTIONS'); + ExecuteQuery("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($usersTabId,$fieldid,'accesskey','vtiger_users',1,3,'accesskey','Webservice Access Key',1,0,0,100,2,$user_adv_block_id,2,'V~O',1,null,'BAS',0,'Webservice Access Key');"); + + foreach($referenceMapping as $uitype=>$referenceArray){ + $success = true; + $result = $adb->pquery("insert into vtiger_ws_fieldtype(uitype,fieldtype) values(?,?)",array($uitype,"reference")); + if(!is_object($result)){ + $success=false; + } + $result = $adb->pquery("select * from vtiger_ws_fieldtype where uitype=?",array($uitype)); + $rowCount = $adb->num_rows($result); + for($i=0;$i<$rowCount;$i++){ + $fieldTypeId = $adb->query_result($result,$i,"fieldtypeid"); + foreach($referenceArray as $index=>$referenceType){ + $result = $adb->pquery("insert into vtiger_ws_referencetype(fieldtypeid,type) values(?,?)",array($fieldTypeId,$referenceType)); + if(!is_object($result)){ + echo "failed for: $referenceType, uitype: $fieldTypeId"; + $success=false; + } + } + } + if(!$success){ + echo "Migration Query Failed"; + break; + } + } + + foreach($fieldTypeInfo as $type=>$uitypes){ + foreach($uitypes as $uitype){ + $result = $adb->pquery("insert into vtiger_ws_fieldtype(uitype,fieldtype) values(?,?)",array($uitype,$type)); + if(!is_object($result)){ + "Query for fieldtype details($uitype:uitype,$type:fieldtype)"; + } + } + } + + $sql = "select * from vtiger_users"; + $updateQuery = "update vtiger_users set accesskey=? where id=?"; + $result = $adb->pquery($sql,array()); + $rowCount = $adb->num_rows($result); + for($i=0;$i<$rowCount;$i++){ + $userId = $adb->query_result($result,$i,"id"); + $insertResult = $adb->pquery($updateQuery,array(vtws_generateRandomAccessKey(16),$userId)); + if(!is_object($insertResult)){ + echo "failed for user: ".$adb->query_result($result,$i,"user_name"); + break; + } + } + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_entity(id integer(11) not null auto_increment PRIMARY + KEY,name varchar(25) not null UNIQUE,handler_path varchar(255) NOT NULL,handler_class varchar(64) NOT NULL, + ismodule int(3) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_entity_name(entity_id integer(11) not null PRIMARY + KEY,name_fields varchar(50),index_field varchar(50),table_name varchar(50)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + + $names = vtws_getModuleNameList(); + $moduleHandler = array('file'=>'include/Webservices/VtigerModuleOperation.php', + 'class'=>'VtigerModuleOperation'); + foreach ($names as $tab){ + if(in_array($tab,array('Rss','Webmails','Recyclebin'))){ + continue; + } + $entityId = $adb->getUniqueID("vtiger_ws_entity"); + $adb->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)', + array($entityId,$tab,$moduleHandler['file'],$moduleHandler['class'],1)); + } + $entityId = $adb->getUniqueID("vtiger_ws_entity"); + $adb->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)', + array($entityId,'Events',$moduleHandler['file'],$moduleHandler['class'],1)); + $entityId = $adb->getUniqueID("vtiger_ws_entity"); + $adb->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)', + array($entityId,'Users',$moduleHandler['file'],$moduleHandler['class'],1)); + + vtws_addDefaultActorTypeEntity('Groups',array('fieldNames'=>'groupname', + 'indexField'=>'groupid','tableName'=>'vtiger_groups')); + ExecuteQuery("CREATE TABLE IF NOT EXISTS `vtiger_ws_entity_tables` (`webservice_entity_id` int(11) NOT NULL ,`table_name` varchar(50) NOT NULL , PRIMARY KEY (`webservice_entity_id`,`table_name`), CONSTRAINT `fk_1_vtiger_ws_actor_tables` FOREIGN KEY (`webservice_entity_id`) REFERENCES `vtiger_ws_entity` (`id`) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_entity_fieldtype(fieldtypeid integer(19) not null auto_increment,table_name varchar(50) not null,field_name varchar(50) not null,fieldtype varchar(200) not null,PRIMARY KEY(fieldtypeid),UNIQUE KEY vtiger_idx_1_tablename_fieldname (table_name,field_name)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_entity_referencetype(fieldtypeid integer(19) not null,type varchar(25) not null,PRIMARY KEY(fieldtypeid,type), CONSTRAINT `vtiger_fk_1_actors_referencetype` FOREIGN KEY (`fieldtypeid`) REFERENCES `vtiger_ws_entity_fieldtype` (`fieldtypeid`) ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + require_once("include/Webservices/WebServiceError.php"); + require_once 'include/Webservices/VtigerWebserviceObject.php'; + $webserviceObject = VtigerWebserviceObject::fromName($adb,'Groups'); + ExecuteQuery("insert into vtiger_ws_entity_tables(webservice_entity_id,table_name) values ({$webserviceObject->getEntityId()},'vtiger_groups')"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS vtiger_ws_operation(operationid int(11) not null auto_increment PRIMARY KEY,name varchar(128) + not null UNIQUE,handler_path varchar(255),handler_method varchar(64), type varchar(8) not null,prelogin int(3) not null, KEY vtiger_idx_ws_oepration_prelogin (prelogin)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + ExecuteQuery("CREATE TABLE IF NOT EXISTS `vtiger_ws_operation_parameters` (`operationid` int(11) NOT NULL, `name` varchar(128) NOT NULL, + `type` varchar(64) NOT NULL, sequence int(11) not null,PRIMARY KEY (`operationid`,`name`), CONSTRAINT + `vtiger_fk_1_ws_operation_params` FOREIGN KEY (`operationid`) REFERENCES `vtiger_ws_operation` (`operationid`) + ON DELETE CASCADE) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); + $operationMeta = array( + "login"=>array( + "include"=>array( + "include/Webservices/Login.php" + ), + "handler"=>"vtws_login", + "params"=>array( + "username"=>"String", + "accessKey"=>"String" + ), + "prelogin"=>1, + "type"=>"POST" + ), + "retrieve"=>array( + "include"=>array( + "include/Webservices/Retrieve.php" + ), + "handler"=>"vtws_retrieve", + "params"=>array( + "id"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "create"=>array( + "include"=>array( + "include/Webservices/Create.php" + ), + "handler"=>"vtws_create", + "params"=>array( + "elementType"=>"String", + "element"=>"encoded" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "update"=>array( + "include"=>array( + "include/Webservices/Update.php" + ), + "handler"=>"vtws_update", + "params"=>array( + "element"=>"encoded" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "delete"=>array( + "include"=>array( + "include/Webservices/Delete.php" + ), + "handler"=>"vtws_delete", + "params"=>array( + "id"=>"String" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "sync"=>array( + "include"=>array( + "include/Webservices/GetUpdates.php" + ), + "handler"=>"vtws_sync", + "params"=>array( + "modifiedTime"=>"DateTime", + "elementType"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "query"=>array( + "include"=>array( + "include/Webservices/Query.php" + ), + "handler"=>"vtws_query", + "params"=>array( + "query"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "logout"=>array( + "include"=>array( + "include/Webservices/Logout.php" + ), + "handler"=>"vtws_logout", + "params"=>array( + "sessionName"=>"String" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "listtypes"=>array( + "include"=>array( + "include/Webservices/ModuleTypes.php" + ), + "handler"=>"vtws_listtypes", + "params"=>array(), + "prelogin"=>0, + "type"=>"GET" + ), + "getchallenge"=>array( + "include"=>array( + "include/Webservices/AuthToken.php" + ), + "handler"=>"vtws_getchallenge", + "params"=>array( + "username"=>"String" + ), + "prelogin"=>1, + "type"=>"GET" + ), + "describe"=>array( + "include"=>array( + "include/Webservices/DescribeObject.php" + ), + "handler"=>"vtws_describe", + "params"=>array( + "elementType"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "extendsession"=>array( + "include"=>array( + "include/Webservices/ExtendSession.php" + ), + "handler"=>"vtws_extendSession", + 'params'=>array(), + "prelogin"=>1, + "type"=>"POST" + ) + ); + $createOperationQuery = "insert into vtiger_ws_operation(operationid,name,handler_path,handler_method,type,prelogin) + values (?,?,?,?,?,?);"; + $createOperationParamsQuery = "insert into vtiger_ws_operation_parameters(operationid,name,type,sequence) + values (?,?,?,?);"; + foreach ($operationMeta as $operationName => $operationDetails) { + $operationId = $adb->getUniqueID("vtiger_ws_operation"); + $result = $adb->pquery($createOperationQuery,array($operationId,$operationName,$operationDetails['include'], + $operationDetails['handler'],$operationDetails['type'],$operationDetails['prelogin'])); + $params = $operationDetails['params']; + $sequence = 1; + foreach ($params as $paramName => $paramType) { + $result = $adb->pquery($createOperationParamsQuery,array($operationId,$paramName,$paramType,$sequence++)); + } + } + + vtws_addDefaultActorTypeEntity('Currency',array('fieldNames'=>'currency_name', + 'indexField'=>'id','tableName'=>'vtiger_currency_info')); + require_once 'include/Webservices/VtigerWebserviceObject.php'; + $webserviceObject = VtigerWebserviceObject::fromName($adb,'Currency'); + ExecuteQuery("insert into vtiger_ws_entity_tables(webservice_entity_id,table_name) values ({$webserviceObject->getEntityId()},'vtiger_currency_info')"); + + vtws_addDefaultActorTypeEntity('DocumentFolders',array('fieldNames'=>'foldername', + 'indexField'=>'folderid','tableName'=>'vtiger_attachmentsfolder')); + $webserviceObject = VtigerWebserviceObject::fromName($adb,'DocumentFolders'); + ExecuteQuery("insert into vtiger_ws_entity_tables(webservice_entity_id,table_name) values ({$webserviceObject->getEntityId()},'vtiger_attachmentsfolder')"); + + $success = true; + $fieldTypeId = $adb->getUniqueID("vtiger_ws_entity_fieldtype"); + $result = $adb->pquery("insert into vtiger_ws_entity_fieldtype(fieldtypeid,table_name,field_name,fieldtype) values(?,?,?,?);", + array($fieldTypeId,'vtiger_attachmentsfolder','createdby',"reference")); + if(!is_object($result)){ + echo "failed fo init
    "; + $success=false; + } + $result = $adb->pquery("insert into vtiger_ws_entity_referencetype(fieldtypeid,type) values(?,?)",array($fieldTypeId,'Users')); + if(!is_object($result)){ + echo "failed for: Users, fieldtypeid: $fieldTypeId"; + $success=false; + } + if(!$success){ + echo "Migration Query Failed"; + } + +} + ExecuteQuery("ALTER TABLE vtiger_notes MODIFY filename varchar(200)"); + +$todoid = getTabid('Calendar'); +$eventid = getTabid('Events'); +// Assigned To field should always come in quickcreate otherwise smownerid will not be filled +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 4 WHERE fieldname = 'assigned_user_id' AND tabid = $accounttabid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 6 WHERE fieldname = 'assigned_user_id' AND tabid = $leadtabid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 6 WHERE fieldname = 'assigned_user_id' AND tabid = $contacttabid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 6 WHERE fieldname = 'assigned_user_id' AND tabid = $potentialtabid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 7 WHERE fieldname = 'assigned_user_id' AND tabid = $campaigntabid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 4 WHERE fieldname = 'assigned_user_id' AND tabid = $helpdesktabid"); +Executequery("UPDATE vtiger_field set quickcreatesequence = 3 WHERE fieldname = 'ticketpriorities' AND tabid = $helpdesktabid"); +Executequery("UPDATE vtiger_field set quickcreatesequence = 2 WHERE fieldname = 'ticketstatus' AND tabid = $helpdesktabid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 4 WHERE fieldname ='assigned_user_id' AND tabid = $todoid"); +Executequery("UPDATE vtiger_field set quickcreate = 0,quickcreatesequence = 6 WHERE fieldname ='assigned_user_id' AND tabid = $eventid"); + + +include_once('modules/Utilities/Currencies.php'); + +ExecuteQuery("CREATE TABLE vtiger_currencies(currencyid INTEGER(19),currency_name varchar(200),currency_code varchar(50),currency_symbol varchar(11)) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); +foreach($currencies as $key=>$value){ + ExecuteQuery("insert into vtiger_currencies values(".$adb->getUniqueID("vtiger_currencies").",'$key','".$value[0]."','".$value[1]."')"); +} +$cur_result = $adb->query("SELECT * from vtiger_currency_info"); +for($i=0;$i<$adb->num_rows($cur_result);$i++){ + $cur_symbol = $adb->query_result($cur_result,$i,"currency_symbol"); + $cur_code = $adb->query_result($cur_result,$i,"currency_code"); + $cur_name = $adb->query_result($cur_result,$i,"currency_name"); + $cur_id = $adb->query_result($cur_result,$i,"id"); + $currency_exists = $adb->pquery("SELECT * from vtiger_currencies WHERE currency_code=?",array($cur_code)); + if($adb->num_rows($currency_exists)>0){ + $currency_name = $adb->query_result($currency_exists,0,"currency_name"); + ExecuteQuery("UPDATE vtiger_currency_info SET vtiger_currency_info.currency_name = '$currency_name' WHERE id=$cur_id"); + } else { + ExecuteQuery("insert into vtiger_currencies values(".$adb->getUniqueID("vtiger_currencies").",'$cur_name','$cur_code','$cur_symbol')"); + } +} +Executequery("UPDATE vtiger_products set handler = 1 WHERE handler = 0"); + +//Emails fields +$email_Tabid = getTabid('Emails'); +$blockid = $adb->getUniqueID('vtiger_blocks'); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($email_Tabid,".$adb->getUniqueID("vtiger_field").",'from_email','vtiger_emaildetails',1,12,'from_email','From',1,2,0,100,1,$blockid,3,'V~M',3,NULL,'BAS',0,NULL)"); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($email_Tabid,".$adb->getUniqueID("vtiger_field").",'to_email','vtiger_emaildetails',1,8,'saved_toid','To',1,2,0,100,2,$blockid,1,'V~M',3,NULL,'BAS',0,NULL)"); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($email_Tabid,".$adb->getUniqueID("vtiger_field").",'cc_email','vtiger_emaildetails',1,8,'ccmail','CC',1,2,0,1000,3,$blockid,1,'V~O',3,NULL,'BAS',0,NULL)"); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($email_Tabid,".$adb->getUniqueID("vtiger_field").",'bcc_email','vtiger_emaildetails',1,8,'bccmail','BCC' ,1,2,0,1000,4,$blockid,1,'V~O',3,NULL,'BAS',0,NULL)"); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($email_Tabid,".$adb->getUniqueID("vtiger_field").",'idlists','vtiger_emaildetails',1,1,'parent_id','Parent ID' ,1,2,0,1000,5,$blockid,3,'V~O',3,NULL,'BAS',0,NULL)"); +$adb->query("insert into vtiger_field (tabid, fieldid, columnname, tablename, generatedtype, uitype, fieldname, fieldlabel, readonly, presence, selected, maximumlength, sequence, block, displaytype, typeofdata, quickcreate, quickcreatesequence, info_type, masseditable, helpinfo) values($email_Tabid,".$adb->getUniqueID("vtiger_field").",'email_flag','vtiger_emaildetails',1,16,'email_flag','Email Flag' ,1,2,0,1000,6,$blockid,3,'V~O',3,NULL,'BAS',0,NULL)"); + +require_once('include/Zend/Json.php'); +$json = new Zend_Json(); + +$result = $adb->query("SELECT * FROM vtiger_emaildetails"); +$rows = $adb->num_rows($result); +for($i=0 ; $i<$rows ;$i++) { + $emailid = $adb->query_result($result,$i,'emailid'); + $to = $adb->query_result($result,$i,'to_email'); + $cc = $adb->query_result($result,$i,'cc_email'); + $bcc = $adb->query_result($result,$i,'bcc_email'); + + $to = ereg_replace("###",",",$to); + $to = str_replace('&lt;','<',$to); + $to = str_replace('&gt;','>',$to); + $to = explode(',',$to); + $to_json = $json->encode($to); + + $cc = str_replace('&lt;','<',$cc); + $cc = str_replace('&gt;','>',$cc); + $cc = ereg_replace("###",",",$cc); + $cc = explode(',',$cc); + $cc_json = $json->encode($cc); + + $bcc = str_replace('&lt;','<',$bcc); + $bcc = str_replace('&gt;','>',$bcc); + $bcc = ereg_replace("###",",",$bcc); + $bcc = explode(',',$bcc); + $bcc_json = $json->encode($bcc); + + $adb->pquery("UPDATE vtiger_emaildetails set to_email = ?, cc_email= ?, bcc_email= ? WHERE emailid = ?",array($to_json,$cc_json,$bcc_json,$emailid)); +} + +//Reports Migration Handling for Older reports - STARTS + +updateReportColumns("vtiger_selectcolumn"); +updateReportColumns("vtiger_relcriteria"); + +function updateReportColumns($table){ + global $adb; + $report_update_array = array( + "vtiger_campaign"=>"(vtiger_reportmodules.primarymodule='Potentials' OR vtiger_reportmodules.secondarymodules = 'Potentials') AND $table.columnname LIKE '%vtiger_campaign%'", + "vtiger_vendorRel"=>"$table.columnname LIKE '%vtiger_vendorRel%'", + "vtiger_potentialRel"=>"$table.columnname LIKE '%vtiger_potentialRel%'", + ); + + foreach($report_update_array as $key=>$where){ + $query = "SELECT vtiger_report.reportid as reportid,$table.columnname AS columnname FROM vtiger_report INNER JOIN $table ON $table.queryid = vtiger_report.reportid INNER JOIN vtiger_reportmodules ON vtiger_reportmodules.reportmodulesid = vtiger_report.reportid WHERE $where"; + $result = $adb->query($query); + if($adb->num_rows($result) > 0){ + for($i=0;$i<$adb->num_rows($result);$i++){ + $reportid = $adb->query_result($result,$i,"reportid"); + $colname = $adb->query_result($result,$i,"columnname"); + $column_array = split(":",$colname); + $column = split("_",$column_array[2]); + $mod_name = $column[0]; + $newcolname = str_replace("$key",$key."$mod_name",$colname); + ExecuteQuery("UPDATE $table SET columnname = '".$newcolname."' WHERE queryid = ".$reportid." AND columnname = '".$colname."'"); + } + } + } + $query = "SELECT vtiger_reportmodules.primarymodule as primarymodule, vtiger_report.reportid as reportid,$table.columnname AS columnname FROM vtiger_report INNER JOIN $table ON $table.queryid = vtiger_report.reportid INNER JOIN vtiger_reportmodules ON vtiger_reportmodules.reportmodulesid = vtiger_report.reportid WHERE $table.columnname LIKE 'vtiger_products%:products_description:%'"; + $result = $adb->query($query); + if($adb->num_rows($result) > 0){ + for($i=0;$i<$adb->num_rows($result);$i++){ + $pri_module = $adb->query_result($result,$i,"reportid"); + $reportid = $adb->query_result($result,$i,"reportid"); + $colname = $adb->query_result($result,$i,"columnname"); + $column_array = split(":",$colname); + if($pri_module!="Products"){ + $column_array[0]='vtiger_crmentityProducts'; + $column_array[1]='description'; + } else { + $column_array[0]='vtiger_crmentity'; + $column_array[1]='description'; + } + $newcolname = $column_array[0].":".$column_array[1].":".$column_array[2].":".$column_array[3].":".$column_array[4]; + ExecuteQuery("UPDATE $table SET columnname = '".$newcolname."' WHERE queryid = ".$reportid." AND columnname = '".$colname."'"); + } + } + $query = "SELECT vtiger_reportmodules.primarymodule as primarymodule, vtiger_report.reportid as reportid,$table.columnname AS columnname FROM vtiger_report INNER JOIN $table ON $table.queryid = vtiger_report.reportid INNER JOIN vtiger_reportmodules ON vtiger_reportmodules.reportmodulesid = vtiger_report.reportid WHERE $table.columnname LIKE 'vtiger_accountPotentials%:accountname:%:account_id:%'"; + $result = $adb->query($query); + if($adb->num_rows($result) > 0){ + for($i=0;$i<$adb->num_rows($result);$i++){ + $reportid = $adb->query_result($result,$i,"reportid"); + $colname = $adb->query_result($result,$i,"columnname"); + $column_array = split(":",$colname); + $column_array[0]='vtiger_potential'; + $column_array[1]='related_to'; + $column_array[2]='Potentials_Related_To'; + $column_array[3]='related_to'; + $newcolname = $column_array[0].":".$column_array[1].":".$column_array[2].":".$column_array[3].":".$column_array[4]; + ExecuteQuery("UPDATE $table SET columnname = '".$newcolname."' WHERE queryid = ".$reportid." AND columnname = '".$colname."'"); + } + } +} +//ENDS + +ExecuteQuery("ALTER TABLE vtiger_inventoryproductrel ADD COLUMN lineitem_id int(19) AUTO_INCREMENT UNIQUE"); + +ExecuteQuery("update vtiger_field set typeofdata='V~M' where fieldname='sales_stage' and tabid =$potentialtabid"); + +ExecuteQuery("update vtiger_cvcolumnlist set columnname ='vtiger_emaildetails:to_email:saved_toid:Emails_To:V' where columnname ='vtiger_crmentity:smownerid:assigned_user_id:Emails_Sender:V'"); + +// for Workflow in settings page of every module + $module_manager_id = getSettingsBlockId('LBL_MODULE_MANAGER'); + $result = $adb->pquery("SELECT max(sequence) AS maxseq FROM vtiger_settings_field WHERE blockid = ?",array($module_manager_id)); + $maxseq = $adb->query_result($result,0,'maxseq'); + if($maxseq < 0 || $maxseq == NULL){ + $maxseq=1; + } + $adb->pquery("INSERT INTO vtiger_settings_field (fieldid, blockid, name, iconpath, description, linkto, sequence) VALUES (?,?,?,?,?,?,?)",array($adb->getUniqueID('vtiger_settings_field'), $module_manager_id, 'LBL_WORKFLOW_LIST', 'settingsWorkflow.png', 'LBL_AVAILABLE_WORKLIST_LIST', 'index.php?module=com_vtiger_workflow&action=workflowlist', $maxseq)); + + +$migrationlog->debug("\n\nDB Changes from 5.0.4 to 5.1.0 RC -------- Ends \n\n"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/504rc_to_504.php b/oss/vtiger/trunk/modules/Migration/DBChanges/504rc_to_504.php new file mode 100644 index 00000000..bfa6eb33 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/504rc_to_504.php @@ -0,0 +1,355 @@ +debug("\n\nDB Changes from 5.0.4rc to 5.0.4 -------- Starts \n\n"); + +//Increased the size of salution field for Leads module +ExecuteQuery("alter table vtiger_leaddetails modify column salutation varchar(50)"); + +//Added to handle the crypt_type in users table. From 5.0.4 onwards the default crypt type will be MD5. But for existing users crypt type will be empty untill they change their password. Once the existing users change the password then their crypt type will be set as MD5 +ExecuteQuery("alter table vtiger_users add column crypt_type varchar(20) not null default 'MD5'"); +ExecuteQuery("update vtiger_users set crypt_type=''"); + +//In 503 to 504rc release we have included the role based picklist migration but the sequence tables for corresponding picklists are not handled. Now we are handling the sequence tables +//Popullating arry with picklist field names +$picklist_arr = array('leadsource'=>'leadsourceid','accounttype'=>'accounttypeid','industry'=>'industryid','leadstatus'=>'leadstatusid','rating'=>'rating_id','opportunity_type'=>'opptypeid','salutationtype'=>'salutationid','sales_stage'=>'sales_stage_id','ticketstatus'=>'ticketstatus_id','ticketpriorities'=>'ticketpriorities_id','ticketseverities'=>'ticketseverities_id','ticketcategories'=>'ticketcategories_id','eventstatus'=>'eventstatusid','taskstatus'=>'taskstatusid','taskpriority'=>'taskpriorityid','manufacturer'=>'manufacturerid','productcategory'=>'productcategoryid','faqcategories'=>'faqcategories_id','usageunit'=>'usageunitid','glacct'=>'glacctid','quotestage'=>'quotestageid','carrier'=>'carrierid','faqstatus'=>'faqstatus_id','invoicestatus'=>'invoicestatusid','postatus'=>'postatusid','sostatus'=>'sostatusid','campaigntype'=>'campaigntypeid','campaignstatus'=>'campaignstatusid','expectedresponse'=>'expectedresponseid'); + +$custom_result = $adb->query("select fieldname from vtiger_field where (uitype=15 or uitype=33) and fieldname like '%cf_%'"); +$numrow = $adb->num_rows($custom_result); +for($i=0; $i < $numrow; $i++) +{ + $fieldname=$adb->query_result($custom_result,$i,'fieldname'); + $picklist_arr[$fieldname] = $adb->query_result($custom_result,$i,'fieldname')."id"; +} + +foreach($picklist_arr as $picklistname => $picklistidname) +{ + $result = $adb->query("select max(".$picklistidname.") as id from vtiger_".$picklistname); + $max_count = 1; + if ($adb->num_rows($result) > 0) { + $max_count = $adb->query_result($result,0,'id'); + if ($max_count <= 0) $max_count = 1; + } + $adb->query("drop table if exists vtiger_".$picklistname."_seq"); + $adb->query("create table vtiger_".$picklistname."_seq (id integer(11))"); + $adb->query("insert into vtiger_".$picklistname."_seq (id) values(".$max_count.")"); + + //In 5.0.3 to 5.0.4 RC migration, for some utf8 character picklist values, picklist_valueid is set as 0 because of query instead of pquery + $result = $adb->query("select * from vtiger_$picklistname where picklist_valueid=0"); + $numrow = $adb->num_rows($result); + for($i=0; $i < $numrow; $i++) + { + $picklist_array_values[$picklistname][] = decode_html($adb->query_result($result,$i,$picklistname)); + } + + //we have retrieved the picklist values to which the picklist_valueid is 0. So we can delete those entries + $adb->query("delete from vtiger_$picklistname where picklist_valueid=0"); + + $temp_array = $picklist_array_values[$picklistname]; + if(is_array($temp_array)) + foreach($temp_array as $ind => $picklist_value) + { + $picklist_autoincrementid = $adb->getUniqueID($picklistname);//auto increment for each picklist table + $picklist_valueid = getUniquePicklistID();//unique value id for each picklist value + + $picklistquery = "insert into vtiger_$picklistname values(?,?,?,?) "; + $adb->pquery($picklistquery, array($picklist_autoincrementid, $picklist_value, 1, $picklist_valueid)); + + //get the picklist's unique id from vtiger_picklist table + $res = $adb->query("select * from vtiger_picklist where name='$picklistname'"); + $picklistid = $adb->query_result($res, 0, 'picklistid'); + + //we have to insert the picklist value in vtiger_role2picklist table for each available roles + $sql="select roleid from vtiger_role"; + $role_result = $adb->query($sql); + $numrows = $adb->num_rows($role_result); + + for($k=0; $k < $numrows; $k++) + { + $roleid = $adb->query_result($role_result,$k,'roleid'); + + //get the max sortid for each picklist + $res = $adb->query("select max(sortid)+1 sortid from vtiger_role2picklist where roleid = '$roleid' and picklistid ='$picklistid'"); + $sortid = $adb->query_result($res, 0, 'sortid'); + + $query = "insert into vtiger_role2picklist values(?,?,?,?)"; + $adb->pquery($query, array($roleid, $picklist_valueid, $picklistid, $sortid)); + } + } +} + +//When we change the ticket description from troubletickets table to crmentity table we have handled in customview but missed in reports - #4968 +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_crmentity:description:HelpDesk_Description:description:V' where columnname='vtiger_troubletickets:description:HelpDesk_Description:description:V'"); +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_crmentityHelpDesk:description:HelpDesk_Description:description:V' where columnname='vtiger_troubletickets:description:HelpDesk_Description:description:V'"); +ExecuteQuery("update vtiger_reportsortcol set columnname='vtiger_crmentityHelpDesk:description:HelpDesk_Description:description:V' where columnname='vtiger_troubletickets:description:HelpDesk_Description:description:V'"); + +//Some fields in customview related tables are changed in latest version but not handled in migration +//Array format is -- oldvalue => newvalue - old values will be updated with new values +//customview related tables to be changed - cvcolumnlist, cvadvfilter +$cv_fields_list = Array( + //campaigns module + "vtiger_campaign:product_id:product_id:Campaigns_Product:V"=>"vtiger_products:productname:productname:Campaigns_Product:V", + "vtiger_campaign:targetsize:targetsize:Campaigns_TargetSize:N"=>"vtiger_campaign:targetsize:targetsize:Campaigns_TargetSize:I", + "vtiger_campaign:budgetcost:budgetcost:Campaigns_Budget_Cost:I"=>"vtiger_campaign:budgetcost:budgetcost:Campaigns_Budget_Cost:N", + "vtiger_campaign:actualcost:actualcost:Campaigns_Actual_Cost:I"=>"vtiger_campaign:actualcost:actualcost:Campaigns_Actual_Cost:N", + "vtiger_campaign:expectedrevenue:expectedrevenue:Campaigns_Expected_Revenue:I"=>"vtiger_campaign:expectedrevenue:expectedrevenue:Campaigns_Expected_Revenue:N", + "vtiger_campaign:expectedsalescount:expectedsalescount:Campaigns_Expected_Sales_Count:N"=>"vtiger_campaign:expectedsalescount:expectedsalescount:Campaigns_Expected_Sales_Count:I", + "vtiger_campaign:actualsalescount:actualsalescount:Campaigns_Actual_Sales_Count:N"=>"vtiger_campaign:actualsalescount:actualsalescount:Campaigns_Actual_Sales_Count:I", + //calendar module + "vtiger_recurringevents:recurringtype:recurringtype:Calendar_Recurrence:V"=>"vtiger_activity:recurringtype:recurringtype:Calendar_Recurrence:O", + "vtiger_activity:time_start::Calendar_Start_Time:V"=>"vtiger_activity:time_start::Calendar_Start_Time:I", + "vtiger_activity:time_end:time_end:Calendar_End_Time:V"=>"vtiger_activity:time_end:time_end:Calendar_End_Time:T", + "activity:date_start:date_start:Activities_Start_Date_&_Time:DT"=>"vtiger_activity:date_start:date_start:Calendar_Start_Date_&_Time:DT", + //Calendar Module + "vtiger_activity:activitytype:activitytype:Calendar_Activity_Type:C"=>"vtiger_activity:activitytype:activitytype:Calendar_Activity_Type:V", + //Campaign Module + "vtiger_campaign:product_id:product_id:Campaigns_Product:I"=>"vtiger_products:productname:productname:Campaigns_Product:V", + "vtiger_campaign:expectedresponsecount:expectedresponsecount:Campaigns_Expected_Response_Count:N"=>"vtiger_campaign:expectedresponsecount:expectedresponsecount:Campaigns_Expected_Response_Count:I", + "vtiger_campaign:actualresponsecount:actualresponsecount:Campaigns_Actual_Response_Count:N"=>"vtiger_campaign:actualresponsecount:actualresponsecount:Campaigns_Actual_Response_Count:I", + //Contacts Module + "vtiger_contactsubdetails:birthday:birthday:Contacts_Birthdate:V"=>"vtiger_contactsubdetails:birthday:birthday:Contacts_Birthdate:D", + //Leads Module + "vtiger_leaddetails:noofemployees:noofemployees:Leads_No_Of_Employees:V"=>"vtiger_leaddetails:noofemployees:noofemployees:Leads_No_Of_Employees:I", + //Potentials Module + "vtiger_potential:campaignid:campaignid:Potentials_Campaign_Source:N"=>"vtiger_potential:campaignid:campaignid:Potentials_Campaign_Source:V", + //FAQ Module + "vtiger_faq:product_id:product_id:Faq_Product_Name:I"=>"vtiger_faq:product_id:product_id:Faq_Product_Name:V", + //Products Module + "vtiger_products:qtyinstock:qtyinstock:Products_Qty_In_Stock:I"=>"vtiger_products:qtyinstock:qtyinstock:Products_Qty_In_Stock:NN", + "vtiger_products:handler:assigned_user_id:Products_Handler:I"=>"vtiger_products:handler:assigned_user_id:Products_Handler:V", + //Vendors Module + "vtiger_vendor:email:email:Vendors_Email:E"=>"vtiger_vendor:email:email:Vendors_Email:V", + //Price Books Module + "vtiger_pricebook:active:active:PriceBooks_Active:V"=>"vtiger_pricebook:active:active:PriceBooks_Active:C", + //Quotes Module + "vtiger_quotes:potentialid:potential_id:Quotes_Potential_Name:I"=>"vtiger_quotes:potentialid:potential_id:Quotes_Potential_Name:V", + "vtiger_quotes:inventorymanager:assigned_user_id1:Quotes_Inventory_Manager:I"=>"vtiger_quotes:inventorymanager:assigned_user_id1:Quotes_Inventory_Manager:V", + ); + +foreach($cv_fields_list as $oldval => $newval) +{ + ExecuteQuery("update vtiger_cvcolumnlist set columnname='$newval' where columnname = '$oldval'"); + ExecuteQuery("update vtiger_cvadvfilter set columnname='$newval' where columnname = '$oldval'"); +} + +//Some fields in report related tables are changed in latest version but not handled in migration +//Report related tables to be changed - selectcolumn, relcriteria, reportsortcol +//Array format is -- oldvalue => newvalue - old values will be updated with new values +$report_fields_list = Array( + //Calendar module + "vtiger_recurringevents:recurringtype:Calendar_Recurrence:recurringtype:O"=>"vtiger_activity:recurringtype:Calendar_Recurrence:recurringtype:O", + //Campaign module + "vtiger_campaign:targetsize:Campaigns_TargetSize:targetsize:N"=>"vtiger_campaign:targetsize:Campaigns_TargetSize:targetsize:I", + "vtiger_campaign:budgetcost:Campaigns_Budget_Cost:budgetcost:I"=>"vtiger_campaign:budgetcost:Campaigns_Budget_Cost:budgetcost:N", + "vtiger_campaign:actualcost:Campaigns_Actual_Cost:actualcost:I"=>"vtiger_campaign:actualcost:Campaigns_Actual_Cost:actualcost:N", + "vtiger_campaign:expectedrevenue:Campaigns_Expected_Revenue:expectedrevenue:I"=>"vtiger_campaign:expectedrevenue:Campaigns_Expected_Revenue:expectedrevenue:N", + "vtiger_campaign:expectedsalescount:Campaigns_Expected_Sales_Count:expectedsalescount:N"=>"vtiger_campaign:expectedsalescount:Campaigns_Expected_Sales_Count:expectedsalescount:I", + "vtiger_campaign:actualsalescount:Campaigns_Actual_Sales_Count:actualsalescount:N"=>"vtiger_campaign:actualsalescount:Campaigns_Actual_Sales_Count:actualsalescount:I", + "vtiger_campaign:expectedresponsecount:Campaigns_Expected_Response_Count:expectedresponsecount:N"=>"vtiger_campaign:expectedresponsecount:Campaigns_Expected_Response_Count:expectedresponsecount:I", + "vtiger_campaign:actualresponsecount:Campaigns_Actual_Response_Count:actualresponsecount:N"=>"vtiger_campaign:actualresponsecount:Campaigns_Actual_Response_Count:actualresponsecount:I", + "vtiger_crmentityRelCalendar:setype:Calendar_Related_To:parent_id:I"=>"vtiger_crmentityRelCalendar:setype:Calendar_Related_To:parent_id:V", + "vtiger_contactdetailsCalendar:lastname:Calendar_Contact_Name:contact_id:I"=>"vtiger_contactdetailsCalendar:lastname:Calendar_Contact_Name:contact_id:V", + //Calendar Module + "activity:date_start:Activities_Start_Date_&_Time:date_start:DT"=>"vtiger_activity:date_start:Calendar_Start_Date_&_Time:date_start:DT", + "vtiger_activity:activitytype:Calendar_Activity_Type:activitytype:C"=>"vtiger_activity:activitytype:Calendar_Activity_Type:activitytype:V", + //"vtiger_activity:status:Calendar_Status:taskstatus:V"=>"vtiger_activity:status:Calendar_Status:taskstatus:V", + //Campaign Module + "vtiger_campaign:product_id:Campaigns_Product:product_id:I"=>"vtiger_products:productname:Campaigns_Product:productname:V", + "vtiger_campaign:expectedresponsecount:Campaigns_Expected_Response_Count:expectedresponsecount:N"=>"vtiger_campaign:expectedresponsecount:Campaigns_Expected_Response_Count:expectedresponsecount:I", + "vtiger_campaign:actualresponsecount:Campaigns_Actual_Response_Count:actualresponsecount:N"=>"vtiger_campaign:actualresponsecount:Campaigns_Actual_Response_Count:actualresponsecount:I", + //Contacts Module + "vtiger_contactsubdetails:birthday:Contacts_Birthdate:birthday:V"=>"vtiger_contactsubdetails:birthday:Contacts_Birthdate:birthday:D", + //Leads Module + "vtiger_leaddetails:noofemployees:Leads_No_Of_Employees:noofemployees:V"=>"vtiger_leaddetails:noofemployees:Leads_No_Of_Employees:noofemployees:I", + //Potentials Module + "vtiger_potential:campaignid:Potentials_Campaign_Source:campaignid:N"=>"vtiger_potential:campaignid:Potentials_Campaign_Source:campaignid:V", + //FAQ Module + "vtiger_faq:product_id:Faq_Product_Name:product_id:I"=>"vtiger_faq:product_id:Faq_Product_Name:product_id:V", + //Products Module + "vtiger_products:qtyinstock:Products_Qty_In_Stock:qtyinstock:I"=>"vtiger_products:qtyinstock:Products_Qty_In_Stock:qtyinstock:NN", + "vtiger_products:handler:Products_Handler:assigned_user_id:I"=>"vtiger_products:handler:Products_Handler:assigned_user_id:V", + //Quotes Module + "vtiger_quotes:potentialid:Quotes_Potential_Name:potential_id:I"=>"vtiger_quotes:potentialid:Quotes_Potential_Name:potential_id:V", + "vtiger_quotes:inventorymanager:Quotes_Inventory_Manager:assigned_user_id1:I"=>"vtiger_quotes:inventorymanager:Quotes_Inventory_Manager:assigned_user_id1:V", + ); + +foreach($report_fields_list as $oldval => $newval) +{ + ExecuteQuery("update vtiger_selectcolumn set columnname='$newval' where columnname='$oldval'"); + ExecuteQuery("update vtiger_relcriteria set columnname='$newval' where columnname='$oldval'"); + ExecuteQuery("update vtiger_reportsortcol set columnname='$newval' where columnname='$oldval'"); +} + + +//we have removed the Team field in quotes and added a new custom field for Team. So we can remove that field from reports (we have changed this field name in customview related tables in 503 - 504rc migration) +ExecuteQuery("delete from vtiger_selectcolumn where columnname='vtiger_quotes:team:Quotes_Team:team:V'"); +ExecuteQuery("delete from vtiger_relcriteria where columnname='vtiger_quotes:team:Quotes_Team:team:V'"); +ExecuteQuery("delete from vtiger_reportsortcol where columnname='vtiger_quotes:team:Quotes_Team:team:V'"); + +//Update the webmail password with encryption +update_webmail_password(); +function update_webmail_password() +{ + global $adb,$migrationlog; + $migrationlog->debug("\nInside update_webmail_password() function starts\n\n"); + require_once("modules/Users/Users.php"); + $res_set = $adb->query('select * from vtiger_mail_accounts'); + $user_obj = new Users(); + while($row = $adb->fetchByAssoc($res_set)) + { + $adb->query("update vtiger_mail_accounts set mail_password = '".$user_obj->changepassword($row['mail_password'])."' where mail_username='".$row['mail_username']."'"); + } + $migrationlog->debug("\nInside update_webmail_password() function ends\n"); +} + +//Modified to increase the length of the outgoinfg server(smtp) servername, username and password +ExecuteQuery("alter table vtiger_systems change column server_username server_username varchar(100)"); +ExecuteQuery("alter table vtiger_systems change column server server varchar(100)"); +ExecuteQuery("alter table vtiger_systems change column server_password server_password varchar(100)"); + +//In our whole product, the picklist table columns and the corresponding picklists storage column in entity tables are changed to varchar(200) +$picklist_query_array = Array( + "alter table vtiger_account modify account_type varchar(200) default NULL", + "alter table vtiger_activity modify activitytype varchar(200) default NULL", + "alter table vtiger_users modify activity_view varchar(200) default NULL", + "alter table vtiger_campaign modify campaignstatus varchar(200) default NULL", + "alter table vtiger_campaign modify campaigntype varchar(200) default NULL", + "alter table vtiger_quotes modify carrier varchar(200) default NULL", + "alter table vtiger_purchaseorder modify carrier varchar(200) default NULL", + "alter table vtiger_salesorder modify carrier varchar(200) default NULL", + "alter table vtiger_users modify date_format varchar(200) default NULL", + "alter table vtiger_activity modify duration_minutes varchar(200) default NULL", + "alter table vtiger_activity drop key activity_status_eventstatus_idx, add key activity_status_idx(status)", + "alter table vtiger_activity modify eventstatus varchar(200) default NULL", + "alter table vtiger_campaign modify expectedresponse varchar(200) default NULL", + "alter table vtiger_faqcategories modify faqcategories varchar(200) default NULL", + "alter table vtiger_faq modify category varchar(200) default NULL", + "alter table vtiger_faqstatus modify faqstatus varchar(200) default NULL", + "alter table vtiger_faq modify status varchar(200) default NULL", + "alter table vtiger_vendor modify glacct varchar(200) default NULL", + "alter table vtiger_account modify industry varchar(200) default NULL", + "alter table vtiger_leaddetails modify industry varchar(200) default NULL", + "alter table vtiger_leaddetails modify leadsource varchar(200) default NULL", + "alter table vtiger_contactsubdetails modify leadsource varchar(200) default NULL", + "alter table vtiger_potential modify leadsource varchar(200) default NULL", + "alter table vtiger_users modify lead_view varchar(200) default NULL", + "alter table vtiger_products modify manufacturer varchar(200) default NULL", + "alter table vtiger_potential modify potentialtype varchar(200) default NULL", + "alter table vtiger_products modify productcategory varchar(200) default NULL", + "alter table vtiger_account modify rating varchar(200) default NULL", + "alter table vtiger_leaddetails modify rating varchar(200) default NULL", + "alter table vtiger_activity modify recurringtype varchar(200) default NULL", + "alter table vtiger_potential modify sales_stage varchar(200) default NULL", + "alter table vtiger_leaddetails modify salutation varchar(200) default NULL", + "alter table vtiger_contactdetails modify salutation varchar(200) default NULL", + "alter table vtiger_taskpriority modify taskpriority varchar(200) default NULL", + "alter table vtiger_activity modify priority varchar(200) default NULL", + "alter table vtiger_taskstatus modify taskstatus varchar(200) default NULL", + "alter table vtiger_activity modify status varchar(200) default NULL", + "alter table vtiger_ticketcategories modify ticketcategories varchar(200) default NULL", + "alter table vtiger_troubletickets modify category varchar(200) default NULL", + "alter table vtiger_ticketpriorities modify ticketpriorities varchar(200) default NULL", + "alter table vtiger_troubletickets modify priority varchar(200) default NULL", + "alter table vtiger_ticketseverities modify ticketseverities varchar(200) default NULL", + "alter table vtiger_troubletickets modify severity varchar(200) default NULL", + "alter table vtiger_ticketstatus modify ticketstatus varchar(200) default NULL", + "alter table vtiger_troubletickets modify status varchar(200) default NULL", + ); +foreach($picklist_query_array as $query) +{ + ExecuteQuery($query); +} + +// Modified to change the comparison datatype from Integer to Varchar for Account name +ExecuteQuery("update vtiger_relcriteria set columnname='vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V' where columnname='vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:I'"); +ExecuteQuery("update vtiger_selectcolumn set columnname='vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V' where columnname='vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:I'"); + +// Modified to change the typeofdata for hour_format, start_hour and end_hour to 'V~O' instead of 'I~O' +ExecuteQuery("update vtiger_field set typeofdata = 'V~O' where tablename='vtiger_users' and fieldname in ('hour_format','start_hour','end_hour')"); + +//Since we don't have field level access for Users and RSS modules we have to delete if there is any entry for these modules in vtiger_profile2field table +$adb->query("delete from vtiger_profile2field where tabid=29"); +$adb->query("delete from vtiger_profile2field where tabid=24"); + +// Modified the typeofdata for all module email field & custom email field in Custom View & Reports. +typeOfDataChanges(); +function typeOfDataChanges() +{ + global $adb,$migrationlog; + $migrationlog->debug("\nInside typeOfDataChanges() function Starts\n\n"); + + $field_table_sql="select columnname,fieldname from vtiger_field where uitype=13"; + $result=$adb->query($field_table_sql); + $num_rows = $adb->num_rows($result); + for($k=0; $k < $num_rows; $k++) + { + $columnname=$adb->query_result($result,$k,'columnname'); + $fieldname=$adb->query_result($result,$k,'fieldname'); + $tablename_array = array('vtiger_cvcolumnlist','vtiger_cvadvfilter','vtiger_selectcolumn','vtiger_relcriteria','vtiger_reportsortcol'); + foreach($tablename_array as $tablename) + { + $custom_sql="select columnname from ".$tablename." where columnname like '%cf%' or columnname like '%email%'"; + $custom_result = $adb->query($custom_sql); + $num_rows2 = $adb->num_rows($custom_result); + for($l=0; $l < $num_rows2; $l++) + { + $table_columnname=$adb->query_result($custom_result,$l,'columnname'); + $values = explode(':',$table_columnname); + if($columnname == $values[1] && $fieldname == $values[2]) + { + ExecuteQuery("update ".$tablename." set columnname='".$values[0].":".$values[1].":".$values[2].":".$values[3].":E' where columnname='".$values[0].":".$values[1].":".$values[2].":".$values[3].":V'"); + } + if($columnname == $values[1] && $fieldname == $values[3]) + { + ExecuteQuery("update ".$tablename." set columnname='".$values[0].":".$values[1].":".$values[2].":".$values[3].":E' where columnname='".$values[0].":".$values[1].":".$values[2].":".$values[3].":V'"); + } + } + } + } + $migrationlog->debug("\nInside typeOfDataChanges() function Ends\n\n"); +} +//Added to remove the unwanted \n characters from inventory notification schedulers +$result=$adb->query("select notificationid,notificationbody from vtiger_inventorynotification"); + +for($i=0;$i<$adb->num_rows($result);$i++) +{ + $body=decode_html($adb->query_result($result,$i,'notificationbody')); + $body=str_replace('\n','', $body); + $notificationid=$adb->query_result($result,$i,'notificationid'); + $adb->pquery("update vtiger_inventorynotification set notificationbody=? where notificationid=?", array($body, $notificationid)); +} +//In 5.0.4, support start and end date notification scheduler should be defaultly active. If it is inactive previouly then we have to change them as active +ExecuteQuery("update vtiger_notificationscheduler set active=1 where schedulednotificationid in (5,6)"); + +//Query added to modify the date_format field length in vtiger_users table +ExecuteQuery("alter table vtiger_users modify date_format varchar(200) default NULL"); +// Updated the sequence number of taskstatus for the ticket #5027 +ExecuteQuery("update vtiger_field set sequence = 8 where columnname = 'status' and tablename = 'vtiger_activity' and fieldname = 'taskstatus' and uitype = 111"); + +$arr=$adb->getColumnNames("vtiger_users"); +if(!in_array("internal_mailer", $arr)) +{ + $adb->pquery("alter table vtiger_users add column internal_mailer int(3) NOT NULL default '1'", array()); +} + +global $dbname; +include("modules/Migration/HTMLtoUTF8Conversion.php"); + +$migrationlog->debug("\n\nDB Changes from 5.0.4rc to 5.0.4 -------- Ends \n\n"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/DBChanges/510rc_to_510.php b/oss/vtiger/trunk/modules/Migration/DBChanges/510rc_to_510.php new file mode 100644 index 00000000..d8d1d87c --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/DBChanges/510rc_to_510.php @@ -0,0 +1,72 @@ +debug("\n\nDB Changes from 5.1.0 RC to 5.1.0 -------- Starts \n\n"); + +require_once('vtlib/Vtiger/Package.php'); +require_once('vtlib/Vtiger/Module.php'); +$package = new Vtiger_Package(); + +ExecuteQuery("DELETE vtiger_cvcolumnlist FROM vtiger_cvcolumnlist INNER JOIN vtiger_customview WHERE vtiger_cvcolumnlist.columnname LIKE '%vtiger_notes:filename%' AND vtiger_customview.cvid = vtiger_cvcolumnlist.cvid AND vtiger_customview.entitytype='HelpDesk'"); +ExecuteQuery("DELETE vtiger_cvcolumnlist FROM vtiger_cvcolumnlist INNER JOIN vtiger_customview WHERE (vtiger_cvcolumnlist.columnname LIKE '%parent_id%' OR vtiger_cvcolumnlist.columnname LIKE '%vtiger_contactdetails%') AND vtiger_customview.cvid = vtiger_cvcolumnlist.cvid AND vtiger_customview.entitytype='Documents'"); + +ExecuteQuery("DELETE vtiger_cvadvfilter FROM vtiger_cvadvfilter INNER JOIN vtiger_customview WHERE vtiger_cvadvfilter.columnname LIKE '%vtiger_notes:filename%' AND vtiger_customview.cvid = vtiger_cvadvfilter.cvid AND vtiger_customview.entitytype='HelpDesk'"); +ExecuteQuery("DELETE vtiger_cvadvfilter FROM vtiger_cvadvfilter INNER JOIN vtiger_customview WHERE (vtiger_cvadvfilter.columnname LIKE '%parent_id%' OR vtiger_cvadvfilter.columnname LIKE '%vtiger_contactdetails%') AND vtiger_customview.cvid = vtiger_cvadvfilter.cvid AND vtiger_customview.entitytype='Documents'"); + +// Update PBXManager module files +$moduleInstance = Vtiger_Module::getInstance('PBXManager'); +$package->initUpdate($moduleInstance, 'packages/5.1.0/mandatory/PBXManager.zip', true); + +// Update ServiceContracts module files +$moduleInstance = Vtiger_Module::getInstance('ServiceContracts'); +$package->initUpdate($moduleInstance, 'packages/5.1.0/mandatory/ServiceContracts.zip', true); + +// Update Services module files +$moduleInstance = Vtiger_Module::getInstance('Services'); +$package->initUpdate($moduleInstance, 'packages/5.1.0/mandatory/Services.zip', true); + +// Install/Update Optional modules +require_once('include/utils/installVtlibSelectedModules.php'); + +// Fixed issue with Calendar duration calculation +ExecuteQuery("ALTER TABLE vtiger_activity MODIFY duration_hours VARCHAR(200)"); + +$result = $adb->query("SELECT activityid,date_start,due_date, time_start,time_end FROM vtiger_activity WHERE activitytype NOT IN ('Task','Emails')"); +$noofrows = $adb->num_rows($result); +for($index=0;$index<$noofrows;$index++){ + $activityid = $adb->query_result($result,$index,'activityid'); + $date_start = $adb->query_result($result,$index,'date_start'); + $time_start = $adb->query_result($result,$index,'time_start'); + $due_date = $adb->query_result($result,$index,'due_date'); + $time_end = $adb->query_result($result,$index,'time_end'); + + $start_date = split("-",$date_start); + $end_date = split("-",$due_date); + $start_time = split(":",$time_start); + $end_time = split(":",$time_end); + + $start = mktime(intval($start_time[0]),intval($start_time[1]),0,intval($start_date[1]),intval($start_date[2]),intval($start_date[0])); + $end = mktime(intval($end_time[0]),intval($end_time[1]),0,intval($end_date[1]),intval($end_date[2]),intval($end_date[0])); + + $duration_in_minutes = floor(($end-$start)/(60));//get the difference between start time and end time in minutes + $hours = floor($duration_in_minutes/60); + $minutes = $duration_in_minutes%60; + $adb->pquery("UPDATE vtiger_activity SET duration_hours=?, duration_minutes=? WHERE activityid=?",array($hours, $minutes,$activityid)); +} + +$migrationlog->debug("\n\nDB Changes from 5.1.0 RC to 5.1.0 -------- Ends \n\n"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/HTMLtoUTF8Conversion.php b/oss/vtiger/trunk/modules/Migration/HTMLtoUTF8Conversion.php new file mode 100644 index 00000000..f4cd1bd2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/HTMLtoUTF8Conversion.php @@ -0,0 +1,156 @@ +
    Started UTF8 Conversion
    '; + +//echo ''; +//This function will convert all the html values in the database into utf-8 values +//echo ''; +$query = " ALTER DATABASE ".$dbname." DEFAULT CHARACTER SET utf8"; +//echo ""; +$adb->query($query); +$query = "SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0"; +//echo ""; +$adb->query($query); +$tables_res = $adb->query("show tables"); +while($row = $adb->fetch_array($tables_res)) +{ + //echo ""; + $query =" LOCK TABLES `".$row[0]."` WRITE "; + //echo ""; + $adb->query($query); + + $query =" ALTER TABLE ".$row[0]." CONVERT TO CHARACTER SET utf8 "; + //echo ""; + $adb->query($query); + + $query =" UNLOCK TABLES "; + //echo ""; + $adb->query($query); + + //echo ""; +} +$query = " SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS "; +//echo ""; +$adb->query($query); +//echo '
    Setting the character set as utf8 and collation as utf8_general_ci for all tables and Databases.
    ".$query."
    ".$query."
    LOCKING TABLE$queryUNLOCKING TABLE
    ".$query."
    '; + +convert_html2utf8_db(); + +/** +* Function to convert html values to its original character available in a database +* This function can called at any time after the migration +* It get all the tables and its VARCHAR/TEXT/LONGTEXT fields from the DB +* Converts the html-values to its original character and restore it. +**/ +function convert_html2utf8_db() +{ + global $adb,$log; + //Getting all the tables from the current database. + $alltables = $adb->get_tables(); + $log->debug("Started HTML to UTF-8 Conversion"); + $values=Array(); + //Tables for which conversion to utf8 not required. + $skip_tables=Array('vtiger_sharedcalendar', 'vtiger_potcompetitorrel', 'vtiger_users2group', 'vtiger_group2grouprel', 'vtiger_group2role', 'vtiger_group2rs', 'vtiger_campaigncontrel', 'vtiger_campaignleadrel', 'vtiger_cntactivityrel', 'vtiger_crmentitynotesrel', 'vtiger_salesmanactivityrel', 'vtiger_vendorcontactrel', 'vtiger_salesmanticketrel', 'vtiger_seactivityrel', 'vtiger_seticketsrel', 'vtiger_senotesrel', 'vtiger_profile2globalpermissions', 'vtiger_profile2standardpermissions', 'vtiger_profile2field', 'vtiger_role2profile', 'vtiger_profile2utility', 'vtiger_activityproductrel', 'vtiger_pricebookproductrel', 'vtiger_activity_reminder', 'vtiger_actionmapping', 'vtiger_org_share_action2tab', 'vtiger_datashare_relatedmodule_permission', 'vtiger_tmp_read_user_sharing_per', 'vtiger_tmp_read_group_sharing_per', 'vtiger_tmp_write_user_sharing_per', 'vtiger_tmp_write_group_sharing_per', 'vtiger_tmp_read_user_rel_sharing_per', 'vtiger_tmp_read_group_rel_sharing_per', 'vtiger_tmp_write_user_rel_sharing_per', 'vtiger_tmp_write_group_rel_sharing_per', 'vtiger_role2picklist', 'vtiger_freetagged_objects', 'vtiger_tab', 'vtiger_blocks', 'vtiger_group2role', 'vtiger_group2rs'); + + //echo ''; + //echo ''; + + for($i=0;$iquery("SHOW COLUMNS FROM $table"); + while ($row = $adb->fetch_array($result)) + { + //Getting the primary key column of the table. + if($row['key'] == 'PRI') + { + $values[$table]['key'][]=$row['field']; + } + //And Getting columns of type varchar, text and longtext. + if(stristr($row['type'],'varchar') != '' || stristr($row['type'],'text') != '' || stristr($row['type'],'longtext') != '') + { + $values[$table]['columns'][] = $row['field']; + } + } + } + } + + $final_array=$values; + foreach($final_array as $tablename=>$value) + { + //Going to update values in the table. + $key = $value['key']; + $cols = $value['columns']; + if($cols != "" && $key != "") + { + if(count($key) > 1) + $key_list = implode(", ", $key); + else + $key_list = $key[0]; + + if(count($cols) > 1) + $col_list = implode(", ", $cols); + else + $col_list = $cols[0]; + //Getting the records available in the table. + $query="SELECT $key_list, $col_list FROM $tablename"; + $res1 = $adb->query($query); + $val = Array(); + $id = Array(); + // echo ' + // + // '; + $log->debug("Converting values in the table :".$tablename); + //Sending the current status to the browser + for($k=0; $k < $adb->num_rows($res1); $k++) + { + $whereStr = ""; + for($l=0; $l < count($key); $l++) + { + $id[$l] = $adb->query_result($res1, $k, $key[$l]); + if($l != 0) + $whereStr .= " and "; + $whereStr .= $key[$l]."=?"; + } + $updateStr = ""; + for($j=0; $j < count($cols); $j++) + { + //Converting the html values to utf8 chars + //echo "
    Updating the value of ".$cols[$j]." column with utf8 value"; + $val[$j] = html_to_utf8(decode_html($adb->query_result($res1, $k, $cols[$j]))); + if($j != 0) + $updateStr .= ", "; + $updateStr .= $cols[$j]."=?"; + } + $updateQ = "UPDATE $tablename SET $updateStr where $whereStr"; + $params = array($val, $id); + $adb->pquery($updateQ, $params); + } + // echo ' + // + // '; + //Sending the current status to the browser + } + } +// echo '
    Started converting data from HTML to UTF-8
    Updating the values in the table '.$tablename.'Completed
    '; +// echo '


    Conversion completed.
    '; + $log->debug("HTML to UTF-8 Conversion has been completed"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Migration/Migration.php b/oss/vtiger/trunk/modules/Migration/Migration.php new file mode 100644 index 00000000..8999753a --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/Migration.php @@ -0,0 +1,472 @@ + Take a dump of old database +//Step : 2 => Drop the New Database +//Step : 3 => Create the New Database +//Step : 4 => Put the old dump into the New Database +//Step : 5 => Modify the new database with the new changes + +class Migration +{ + + var $conn; + var $oldconn; + + //Old Database Parameters + var $old_hostname; + var $old_mysql_port; + var $old_mysql_username; + var $old_mysql_password; + var $old_dbname; + + //New Database Parameters + var $new_hostname; + var $new_mysql_port; + var $new_mysql_username; + var $new_mysql_password; + var $new_dbname; + + /** Constructor with old database and new database connections + */ + function Migration($old='',$new='') + { + global $migrationlog; + $migrationlog->debug("Inside the constructor Migration."); + + $this->oldconn = $old; + $this->conn = $new; + $migrationlog->debug("Database Object has been created."); + } + + /** function used to set the Old database parameters in the migration object properties + * @param string $hostname - old database hostname + * @param int $mysql_port - old database mysql port number + * @param string $mysql_username - old database mysql user name + * @param string $mysql_password - old database mysql password + * @param string $dbname - old database name + * @return void + */ + function setOldDatabaseParams($hostname,$mysql_port,$mysql_username,$mysql_password,$dbname) + { + global $migrationlog; + $migrationlog->debug("Inside the function setOldDatabaseParams($hostname,$mysql_port,$mysql_username,$mysql_password,$dbname)"); + + $this->old_hostname = $hostname; + $this->old_mysql_port = $mysql_port; + $this->old_mysql_username = $mysql_username; + $this->old_mysql_password = $mysql_password; + $this->old_dbname = $dbname; + + $migrationlog->debug("Old Database Parameters has been set."); + } + + /** function used to set the Current ie., new 5.0 database parameters in the migration object properties + * @param string $hostname - new database hostname + * @param int $mysql_port - new database mysql port number + * @param string $mysql_username - new database mysql user name + * @param string $mysql_password - new database mysql password + * @param string $dbname - new database name + * @return void + */ + function setNewDatabaseParams($hostname,$mysql_port,$mysql_username,$mysql_password,$dbname) + { + global $migrationlog; + $migrationlog->debug("Inside the function setNewDatabaseParams($hostname,$mysql_port,$mysql_username,$mysql_password,$dbname)"); + + $this->new_hostname = $hostname; + $this->new_mysql_port = $mysql_port; + $this->new_mysql_username = $mysql_username; + $this->new_mysql_password = $mysql_password; + $this->new_dbname = $dbname; + + $migrationlog->debug("New Database Parameters has been set."); + } + + /** function used to take the database dump + * @param string $host_name - host name in where the database is available + * @param int $mysql_port - mysql port number + * @param string $mysql_username - mysql user name + * @param string $mysql_password - mysql password + * @param string $dbname - database name + * @return string $dump_filename - return the dump filename + */ + function takeDatabaseDump($host_name,$mysql_port,$mysql_username,$mysql_password,$dbname) + { + global $migrationlog; + $migrationlog->debug("Inside the function takeDatabaseDump($host_name,$mysql_port,$mysql_username,$mysql_password,$dbname). Going to take the specified database dump..."); + + $dump_filename = 'dump_'.$dbname.'.txt'; + + if($mysql_password != '') + { + $password_str = " -p".$mysql_password; + } + else + { + $password_str = ''; + } + + //This if is used when we cannot access mysql from vtiger root directory + if($_SESSION['set_server_mysql_path'] != '') + { + $current_working_dir = getcwd(); + $server_mysql_path = $_SESSION['set_server_mysql_path']; + + $dump_str = "mysqldump -u".$mysql_username.$password_str." -h ".$host_name." --port=".$mysql_port." ".$dbname." >> ".$dump_filename; + $migrationlog->debug("Server path set. Dump string to execute ==> $dump_str"); + + chdir ($server_mysql_path); + + exec("echo 'set FOREIGN_KEY_CHECKS = 0;' > ".$dump_filename); + exec($dump_str); + exec("echo 'set FOREIGN_KEY_CHECKS = 1;' >> ".$dump_filename); + + exec('cp "'.$server_mysql_path.'\\'.$dump_filename.'" "'.$current_working_dir.'\\'.$dump_filename).'"'; + chdir ($current_working_dir); + } + else + { + $migrationlog->debug("Dump string to execute ==> mysqldump -u".$mysql_username." -h ".$host_name.$password_str." --port=".$mysql_port." ".$dbname." >> ".$dump_filename); + + exec("echo 'set FOREIGN_KEY_CHECKS = 0;' > ".$dump_filename); + exec("mysqldump -u".$mysql_username." -h ".$host_name.$password_str." --port=".$mysql_port." ".$dbname." >> ".$dump_filename); + exec("echo 'set FOREIGN_KEY_CHECKS = 1;' >> ".$dump_filename); + } + + $_SESSION['migration_log'] .= '
    '.$dbname.' Database Dump has been taken and the file is ==> '.$dump_filename; + $migrationlog->debug("
    $dbname Database Dump has been taken and the file is ==> $dump_filename"); + + return $dump_filename; + } + + /** function used to drop the database + * @param object $conn - adodb object which is connected with the current(new) database + * @param string $dbname - database name which we want to drop + * @return void + */ + function dropDatabase($conn,$dbname) + { + global $migrationlog; + $migrationlog->debug("Inside the function dropDatabase(".get_class($conn).",".$dbname."). Going to drop the database - $dbname"); + $sql = "drop database ".$dbname; + $conn->query($sql); + + $migrationlog->debug("Database ($dbname) has been dropped."); + $_SESSION['migration_log'] .= '
    '.$dbname.' Database has been dropped.'; + } + + /** function used to create the database + * @param object $conn - adodb object which is connected with the current(new) database + * @param string $dbname - database name which we want to drop + * @return void + */ + function createDatabase($conn,$dbname) + { + global $migrationlog; + $migrationlog->debug("Inside the function createDatabase(".get_class($conn).",".$dbname."). Going to create the database - $dbname"); + + $sql = "create database ".$dbname; + $conn->query($sql); + + $_SESSION['migration_log'] .= '
    '.$dbname.' Database has been created.'; + $migrationlog->debug("Database ($dbname) has been dropped."); + + //Added to avoid the No Database Selected error when execute the queries + $conn->connect(); + } + + /** function used to apply the dump data to a database + * @param string $host_name - host name + * @param int $mysql_port - mysql port number + * @param string $mysql_username - mysql user name + * @param string $mysql_password - mysql password + * @param string $dbname - database name to which we want to apply the dump + * @param string $dumpfile - dump file which contains the data dump of a database + * @return void + */ + function applyDumpData($host_name,$mysql_port,$mysql_username,$mysql_password,$dbname,$dumpfile) + { + global $migrationlog; + $migrationlog->debug("Inside the function applyDumpData($host_name,$mysql_port,$mysql_username,$mysql_password,$dbname,$dumpfile)."); + + if($mysql_password != '') + { + $password_str = " --password=".$mysql_password; + } + else + { + $password_str = ''; + } + + //This if is used when we cannot access mysql from vtiger root directory + if($_SESSION['set_server_mysql_path'] != '') + { + $current_working_dir = getcwd(); + $server_mysql_path = $_SESSION['set_server_mysql_path']; + + $dump_str = "mysql --user=".$mysql_username.$password_str." -h ".$host_name." --force --port=".$mysql_port." ".$dbname." < ".$dumpfile; + $migrationlog->debug("MySQL server path set. Dump string to apply ==> $dump_str"); + + //exec("path = $server_mysql_path"); + chdir ($server_mysql_path); + + exec($dump_str); + + chdir ($current_working_dir); + } + else + { + exec("mysql --user=".$mysql_username." -h ".$host_name." --force --port=".$mysql_port.$password_str." ".$dbname." < ".$dumpfile); + $migrationlog->debug("Dump string to apply ==> mysql --user=$mysql_username -h $host_name --force --port=$mysql_port $password_str $dbname < $dumpfile"); + } + + $_SESSION['migration_log'] .= '
    Database Dump has been applied to the '.$dbname.' Database from '.$dumpfile.''; + $migrationlog->debug("
    Database Dump has been applied to the $dbname database from $dumpfile "); + } + + + /** function used to get the tabid + * @param string $module - module to which we want to get the tabid + * @return int $tabid - return the tabid of the module + */ + function localGetTabID($module) + { + global $conn; + + $sql = "select tabid from vtiger_tab where name='".$module."'"; + $result = $conn->query($sql); + $tabid= $conn->query_result($result,0,"tabid"); + + return $tabid; + } + + /** function used to get the table count of the new database + * @return int $tables - return the number of tables available in the new database + */ + function getTablesCountInNewDatabase() + { + global $migrationlog; + $migrationlog->debug("Inside the function getTablesCountInNewDatabase()"); + $newconn = @mysql_connect($this->new_hostname.':'.$this->new_mysql_port,$this->new_mysql_username,$this->new_mysql_password); + $tables = @mysql_num_rows(mysql_list_tables($this->new_dbname,$newconn)); + + $migrationlog->debug("Number of Tables in New Database = $tables"); + return $tables; + } + + /** function used to get the table count of the old database + * @return int $tables - return the number of tables available in the old database + */ + function getTablesCountInOldDatabase() + { + global $migrationlog; + $migrationlog->debug("Inside the function getTablesCountInOldDatabase()"); + $oldconn = @mysql_connect($this->old_hostname.':'.$this->old_mysql_port,$this->old_mysql_username,$this->old_mysql_password); + $tables = @mysql_num_rows(mysql_list_tables($this->old_dbname,$oldconn)); + + $migrationlog->debug("Number of Tables in Old Database = $tables"); + return $tables; + } + + /** function used to modify the database from old version to match with new version + * @param object $conn - adodb object which is connected with the current(new) database + * @return void + */ + function modifyDatabase($conn) + { + global $migrationlog; + $migrationlog->debug("Inside the function modifyDatabase(".get_class($conn).")"); + $migrationlog->debug("\n\n\nMickie ---- Starts"); + + $_SESSION['migration_log'] .= "
    The current database is going to be modified by executing the following queries...
    "; + + //Added variables to get the queries list and count + $query_count = 1; + $success_query_count = 1; + $failure_query_count = 1; + $success_query_array = Array(); + $failure_query_array = Array(); + + //To handle the file includes for each and every version + //Here we have to decide which files should be included, where the files will be added newly for every public release + //In this included file we have included modules/Migration/DBChanges/42P2_to_50.php which will apply the db changes upto 5.0. + include("modules/Migration/MigrationInfo.php"); + + $migrationlog->debug("Mickie ---- Ends\n\n\n"); + } + + /** function used to run the migration process based on the option selected and values given + * @param int $same_databases - 1 if both databases are same otherwise 0 + * @param string $option - selected migration option (dbsource or dumpsource) + * @param string $old_dump_file_name - dump file name of the old database which is optional when we use dbsource + * @return void + */ + function migrate($same_databases, $option, $old_dump_file_name='') + { + //1. Migration Procedure -- when we give the Source Database values + //Step : 1 => Take a dump of old database + //Step : 2 => Drop the New Database + //Step : 3 => Create the New Database + //Step : 4 => Put the old dump into the New Database + //Step : 5 => Modify the new database with the new changes + + //2. Migration Procedure -- when we give the Database dump file + //Step : 1 => Drop the New Database + //Step : 2 => Create the New Database + //Step : 3 => Put the dump into the New Database + //Step : 4 => Modify the new database with the new changes + + global $migrationlog; + global $conn; + $migrationlog->debug("Database Migration from Old Database to the Current Database Starts."); + $migrationlog->debug("Migration Option = $option"); + + //Set the old database parameters + $old_host_name = $this->old_hostname; + $old_mysql_port = $this->old_mysql_port; + $old_mysql_username = $this->old_mysql_username; + $old_mysql_password = $this->old_mysql_password; + $old_dbname = $this->old_dbname; + + //Set the new database parameters + $new_host_name = $this->new_hostname; + $new_mysql_port = $this->new_mysql_port; + $new_mysql_username = $this->new_mysql_username; + $new_mysql_password = $this->new_mysql_password; + $new_dbname = $this->new_dbname; + + //This will be done when we give the Source Database details + if($option == 'dbsource') + { + //Take the dump of the old Database + $migrationlog->debug("Going to take the old Database Dump."); + $dump_file = $this->takeDatabaseDump($old_host_name,$old_mysql_port,$old_mysql_username,$old_mysql_password,$old_dbname); + + //check the file size is greater than 10000 bytes (~app) and if yes then continue else goto step1 + if(is_file($dump_file) && filesize($dump_file) > 10000) + { + $_SESSION['migration_log'] .= "Source database dump taken successfully."; + } + else + { + echo '
    The Source database dump taken may not contain all values. So please use other option.'; + include("modules/Migration/MigrationStep1.php"); + exit; + } + } + elseif($option == 'dumpsource') + { + $dump_file = $old_dump_file_name; + } + + //if old db and new db are different then take new db dump + if($old_dbname != $new_dbname) + { + //This is to take dump of the new database for backup purpose + $migrationlog->debug("Going to take the current Database Dump."); + $new_dump_file = $this->takeDatabaseDump($new_host_name,$new_mysql_port,$new_mysql_username,$new_mysql_password,$new_dbname); + + //check the file size is greater than 10000 bytes (~app) and if yes then continue else goto step1 + if(is_file($new_dump_file) && filesize($new_dump_file) > 10000) + { + $_SESSION['migration_log'] .= "Current database dump taken successfully."; + } + else + { + $_SESSION['migration_log'] .= '
    The Current database dump taken may not contain all values. So may not be reload the current database if any problem occurs in migration. If the migration not completed please rename the install.php and install folder and run the install.php'; + //include("modules/Migration/MigrationStep1.php"); + //exit; + } + + } + + + $continue_process = 1; + if($same_databases == 1) + { + $_SESSION['migration_log'] .= '
    Same databases are used. so skip the process of drop and create the current database.'; + } + else + { + $_SESSION['migration_log'] .= '
    Databases are different. So drop the Current Database and create. Also apply the dump of Old Database'; + //Drop the current(latest) Database + $migrationlog->debug("Going to Drop the current Database"); + $this->dropDatabase($conn,$new_dbname); + + //Create the new current(latest) Database + $migrationlog->debug("Going to Create the current Database"); + $this->createDatabase($conn,$new_dbname); + + //Apply the dump of the old database to the current database + $migrationlog->debug("Going to apply the old database dump to the new database."); + $this->applyDumpData($new_host_name,$new_mysql_port,$new_mysql_username,$new_mysql_password,$new_dbname,$dump_file); + + //get the number of tables in new database + $new_tables_count = $this->getTablesCountInNewDatabase(); + + //get the number of tables in old database + $old_tables_count = $this->getTablesCountInOldDatabase(); + + //if tables are missing after apply the dump, then alert the user and quit + if(($new_tables_count != $old_tables_count && $option == 'dbsource') || ($new_tables_count < 180 && $option == 'dumpsource')) + { + $migrationlog->debug("New Database tables not equal to Old Database tables count. Reload the current database again and quit."); + + $continue_process = 0; + $msg = "The dump may not be applied correctly. Tables exist in 4.2.3 database : $old_tables_count. Tables exist in current database after apply the dump : $new_tables_count"; + ?> + + debug("Going to modify the current database which is now as old database setup"); + $this->modifyDatabase($conn); + + $migrationlog->debug("Database Modifications Ends......"); + $migrationlog->debug("Database Migration from Old Database to the Current Database has been Finished."); + } + else + { + //Drop the current(latest) Database + $migrationlog->debug("Problem in migration. so going to Restore the current Database"); + $migrationlog->debug("Going to Drop the current Database"); + $this->dropDatabase($conn,$new_dbname); + + //Create the new current(latest) Database + $migrationlog->debug("Going to Create the current Database"); + $this->createDatabase($conn,$new_dbname); + + //Reload the new db dump and quit + $migrationlog->debug("Going to apply the new backup db dump"); + $this->applyDumpData($new_host_name,$new_mysql_port,$new_mysql_username,$new_mysql_password,$new_dbname,$new_dump_file); + + //Return to Step1 + echo '
    Dump could not be applied correctly. so your previous database restored.'; + include("modules/Migration/MigrationStep1.php"); + } + + //Now we should recalculate the user and sharing privileges + RecalculateSharingRules(); + } + +} + + + +?> diff --git a/oss/vtiger/trunk/modules/Migration/MigrationCheck.php b/oss/vtiger/trunk/modules/Migration/MigrationCheck.php new file mode 100644 index 00000000..47a1890a --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/MigrationCheck.php @@ -0,0 +1,422 @@ +is_admin != 'on') +{ + die("

    ".$app_strings['LBL_PERMISSION']." ".$app_strings['LBL_GO_BACK'].".
    "); +} + +include("config.inc.php"); +$migration_log = ''; + +//Added for Migration Log +$migrationlog =& LoggerManager::getLogger('MIGRATION'); + +//new database values get from the current vtigerCRM's config.php +global $dbconfig; +$new_host_name = $dbconfig['db_hostname']; +$new_mysql_username = $dbconfig['db_username']; +$new_mysql_password = $dbconfig['db_password']; +$new_dbname = $dbconfig['db_name']; + +//this is to check whether the user_privileges folder has write permission +if(!is_writable($root_directory."user_privileges/")) +{ + echo "
    Please give read/write permission to user_privileges folder."; + include("modules/Migration/MigrationStep1.php"); + exit; +} + +//this is to check whether the mysql path is needed and has been entered or not +if($_REQUEST['getmysqlpath'] == 1 && $_REQUEST['server_mysql_path'] != '') +{ + $mysql_path_found = false; + $server_mysql_path = $_REQUEST['server_mysql_path']; + if(is_file($server_mysql_path."/mysqldump")) + { + $mysql_path_found = true; + @session_unregister('set_server_mysql_path'); + $_SESSION['set_server_mysql_path'] = $server_mysql_path; + $migration_log .='MySQL Dump file has found in ==> '.$server_mysql_path; + } + elseif(substr($_ENV["OS"],0,3) == "Win" && is_file($server_mysql_path."\mysqldump.exe")) + { + $mysql_path_found = true; + @session_unregister('set_server_mysql_path'); + $_SESSION['set_server_mysql_path'] = $server_mysql_path; + $migration_log .='MySQL Dump file has found in ==> '.$server_mysql_path; + } + + if(!$mysql_path_found && $_REQUEST['migration_option'] != 'alter_db_details') + { + //header("Location: index.php?module=Migration&action=MigrationStep1&parenttab=Settings"); + echo '
    MySQL dump file is not exist in the specified MySQL Server Path'; + include("modules/Migration/MigrationStep1.php"); + exit; + } +} +$migrationlog->debug("$migration_log"); +//echo '
    Proceed with migration'; + + +$migrationlog->debug("Migration Option - ".$_REQUEST['migration_option']); +include("modules/Migration/Migration.php"); +if($_REQUEST['migration_option'] == 'db_details') +{ + //Source MySQL database details have been given. + //old database values + $old_host_name = $_REQUEST['old_host_name']; + $old_mysql_port = $_REQUEST['old_port_no']; + $old_mysql_username = $_REQUEST['old_mysql_username']; + $old_mysql_password = $_REQUEST['old_mysql_password']; + $old_dbname = $_REQUEST['old_dbname']; + + $migrationlog->debug("old host name = ".$old_host_name); + $migrationlog->debug("old MySQL port = ".$old_mysql_port); + $migrationlog->debug("old MySQL username = ".$old_mysql_username); + $migrationlog->debug("old MySQL password = ".$old_mysql_password); + $migrationlog->debug("old db name = ".$old_dbname); + + //make a connection with the old database + $oldconn = @mysql_connect($old_host_name.":".$old_mysql_port,$old_mysql_username,$old_mysql_password); + + //make a connection with the new database + $newconn = @mysql_connect($new_host_name,$new_mysql_username,$new_mysql_password); + + if(!$oldconn) + { + echo '
    Source Database Server cannot be connected'; + $continue1 = 0; + } + elseif(!$newconn) + { + echo '
    Current working Database Server cannot be connected'; + $continue1 = 0; + } + else + { + $migration_log .= ' Database Servers can be connected. Can proceed with migration'; + $migrationlog->debug("Database Servers can be connected. continue1 = 1"); + $continue1 = 1; + } + + if($continue1 == 1) + { + //check whether the specified databases are exist or not + $olddb_exist = @mysql_select_db($old_dbname,$oldconn); + //$newdb_exist = @mysql_select_db($new_dbname,$oldconn); + if(!$olddb_exist) + { + echo '
    Source Database does not exist'; + $continue2 = 0; + } + //elseif(!$newdb_exist) + //{ + // echo '
    New Database is not exist'; + // $continue2 = 0; + //} + else + { + $migration_log .= '
    Required databases exist'; + $migrationlog->debug("Required databases exist. continue2 = 1"); + $continue2 = 1; + } + } + + if($continue2 == 1) + { + //Check whether the vtiger_table are exist in the databases or not + $old_tables = @mysql_num_rows(mysql_list_tables($old_dbname,$oldconn)); + //$new_tables = @mysql_num_rows(mysql_list_tables($new_dbname)); + + if(!$old_tables) + { + echo '
    Tables do not exist in the Source Database'; + $continue3 = 0; + } + /* if(!$new_tables) + { + echo '
    Tables are not exist in New Database'; + $continue3 = 0; + } + */ + else + { + $migration_log .= '
    Tables exist in both the Databases'; + $migrationlog->debug("Tables exist in the database. continue3 = 1"); + $continue3 = 1; + } + } + + //To check whether the two databases are same + if($continue3 == 1) + { + $new_host = explode(":",$new_host_name); + + if($old_host_name == $new_host[0] && $old_mysql_port == $new_host[1] && $old_mysql_username == $new_mysql_username && $old_mysql_password == $new_mysql_password && $old_dbname == $new_dbname) + { + echo '
    Both the databases are the same.'; + $continue4 = 1;//change the value to 0 if you don't want to proceed with the same database + $same_databases = 1; + } + else + { + $continue4 = 1; + $same_databases = 0; + } + } + + //$continue1 -- Database servers can be connected + //$continue2 -- Database exists in the servers + //$continue3 -- Tables are exist in the databases + //$continue4 -- Two databases are not same + + if($continue1 == 1 && $continue2 == 1 && $continue3 == 1 && $continue4 == 1) + { + $migrationlog->debug("Going to migrate..."); + + $new_host = explode(":",$new_host_name); + + $conn = new PearDatabase("mysql",$new_host_name,$new_dbname,$new_mysql_username,$new_mysql_password); + $conn->connect(); + + $migrationlog->debug("MICKIE ==> Option = DB details. From the given DB details we will migrate."); + + @session_unregister('migration_log'); + $_SESSION['migration_log'] = $migration_log; + if($conn) + { + $migrationlog->debug("Pear Database object created. Going to create migration object."); + + $obj = new Migration('',$conn); + $obj->setOldDatabaseParams($old_host_name,$old_mysql_port,$old_mysql_username,$old_mysql_password,$old_dbname); + $obj->setNewDatabaseParams($new_host[0],$new_host[1],$new_mysql_username,$new_mysql_password,$new_dbname); + $obj->migrate($same_databases,'dbsource'); + } + else + { + echo '
    Cannot make a connection with the current database setup.'; + include("modules/Migration/MigrationStep1.php"); + } + } + else + { + echo '
    ERROR!!!!!!Please check the input values, unable to proceed.'; + include("modules/Migration/MigrationStep1.php"); + } + + +} +elseif($_REQUEST['migration_option'] == 'dump_details') +{ + $old_dump_details = $_FILES['old_dump_filename']; + $old_dump_filename = $old_dump_details['name']; + $migrationlog->debug("Dump file name ==> $old_dump_filename"); + + //MySQL Dump file details has given + if($old_dump_details['size'] != 0 && is_file($old_dump_details['tmp_name'])) + { + $gotostep1 = 0; + //apply this dump file to the new database + $checkDumpFileAndApply = 1; + } + else + { + $gotostep1 = 1; + if($old_dump_details['error'] == 2 || $old_dump_details['error'] == 1) + { + $invalid_dump = 1; + $errormessage = "Sorry, the uploaded file exceeds the maximum filesize limit. Try other option."; + } + elseif($old_dump_details['error'] == 4 || $old_dump_details['size'] == 0 || !is_file($old_dump_details['tmp_name'])) + { + $invalid_dump = 1; + $errormessage = "Please enter a valid Dump file."; + } + $migrationlog->debug("Dump file error no = ".$old_dump_details['error']); + } + + if($gotostep1 == 1) + { + if($invalid_dump == 1) + { + echo "
    $errormessage"; + } + include("modules/Migration/MigrationStep1.php"); + exit; + } + + if($checkDumpFileAndApply == 1) + { + //TODO - Check whether the given file is Dump file and then apply to the new database + $migration_log .= '
    Going to apply the Dump file to the new database.'; + + //If the dump is valid and going to migrate then we should move the browsed dump file to root directory + global $root_directory; + move_uploaded_file($old_dump_details['tmp_name'],$root_directory.$old_dump_details['name']); + + include("config.inc.php"); + global $dbconfig; + + $new_host_name = $dbconfig['db_hostname']; + $new_dbname = $dbconfig['db_name']; + $new_mysql_username = $dbconfig['db_username']; + $new_mysql_password = $dbconfig['db_password']; + + $conn = new PearDatabase("mysql",$new_host_name,$new_dbname,$new_mysql_username,$new_mysql_password); + $conn->connect(); + + $migrationlog->debug("MICKIE ==> Option = Dump File. Selected Dump File will be applied to the new database"); + + @session_unregister('migration_log'); + $_SESSION['migration_log'] = $migration_log; + if($conn) + { + $migrationlog->debug("Pear Database object created. Going to create migration object."); + + $obj = new Migration('',$conn); + + $new_host = explode(":",$new_host_name); + $temp_new_host_name = $new_host[0]; + $new_mysql_port = $new_host[1]; + + $obj->setNewDatabaseParams($new_host[0],$new_host[1],$new_mysql_username,$new_mysql_password,$new_dbname); + $obj->migrate(0,'dumpsource',$old_dump_filename); + } + } + +} +elseif($_REQUEST['migration_option'] == 'alter_db_details') +{ + //old database values + $old_host_name = $_REQUEST['alter_old_host_name']; + $old_mysql_port = $_REQUEST['alter_old_port_no']; + $old_mysql_username = $_REQUEST['alter_old_mysql_username']; + $old_mysql_password = $_REQUEST['alter_old_mysql_password']; + $old_dbname = $_REQUEST['alter_old_dbname']; + + $migrationlog->debug("old host name = ".$old_host_name); + $migrationlog->debug("old MySQL port = ".$old_mysql_port); + $migrationlog->debug("old MySQL username = ".$old_mysql_username); + $migrationlog->debug("old MySQL password = ".$old_mysql_password); + $migrationlog->debug("old db name = ".$old_dbname); + + //make a connection with the old database + $oldconn = @mysql_connect($old_host_name.":".$old_mysql_port,$old_mysql_username,$old_mysql_password); + + if(!$oldconn) + { + echo '
    Source Database Server cannot be connected'; + $continue1 = 0; + } + else + { + $migration_log .= ' Database Server can be connected. Can proceed with migration'; + $migrationlog->debug("Database server connected. continue1 = 1"); + $continue1 = 1; + } + + if($continue1 == 1) + { + //check whether the specified databases are exist or not + $olddb_exist = @mysql_select_db($old_dbname,$oldconn); + + if(!$olddb_exist) + { + echo '
    Source Database does not exist'; + $continue2 = 0; + } + else + { + $migration_log .= '
    Required database exist'; + $migrationlog->debug("Database exist. continue2 = 1"); + $continue2 = 1; + } + } + + if($continue2 == 1) + { + //Check whether the vtiger_table are exist in the databases or not + $old_tables = @mysql_num_rows(mysql_list_tables($old_dbname,$oldconn)); + + if(!$old_tables) + { + echo '
    Tables do not exist in the Source Database'; + $continue3 = 0; + } + else + { + $migration_log .= '
    Tables exist in the Database'; + $migrationlog->debug("Tables exist. continue3 = 1"); + $continue3 = 1; + } + } + + //$continue1 -- Database server can be connected + //$continue2 -- Database exists in the server + //$continue3 -- Tables are exist in the database + + if($continue1 == 1 && $continue2 == 1 && $continue3 == 1) + { + + $conn = new PearDatabase("mysql",$old_host_name.":".$old_mysql_port,$old_dbname,$old_mysql_username,$old_mysql_password); + $conn->connect(); + + $migrationlog->debug("MICKIE ==> Option = Alter DB details. From the given DB details we will migrate."); + + @session_unregister('migration_log'); + $_SESSION['migration_log'] = $migration_log; + if($conn) + { + $migrationlog->debug("Database object created. Going to create Migration object"); + + $obj = new Migration('',$conn); + $obj->setOldDatabaseParams($old_host_name,$old_mysql_port,$old_mysql_username,$old_mysql_password,$old_dbname); + //$obj->migrate($same_databases,'dbsource'); + $obj->modifyDatabase($conn); + } + else + { + echo '
    Cannot make a connection with the current database setup'; + include("modules/Migration/MigrationStep1.php"); + } + } + else + { + echo '
    ERROR!!!!!!Please check the input values, unable to proceed.'; + include("modules/Migration/MigrationStep1.php"); + } +} +else +{ + //Return to the MigrationStep1 + include("modules/Migration/MigrationStep1.php"); + exit; +} + +?> + + + + diff --git a/oss/vtiger/trunk/modules/Migration/MigrationInfo.php b/oss/vtiger/trunk/modules/Migration/MigrationInfo.php new file mode 100644 index 00000000..d07ec8a1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/MigrationInfo.php @@ -0,0 +1,309 @@ + + + + + + + + + + + + +

    + Settings > Migrate from Previous Version +
    +
     
    + + + + + + + +
    + + + + + + + + + + + + + +
    + Migrate From Previous Version
    + Update your new vtiger CRM 5 database with the data from previous installation
    + To Start, follow the instructions below +
    + Migration Results +


    +
    + + + + + +
    Migration is in progress. Please wait...
    + Your old data is now moving into new vtiger CRM
    +
    + + +
    + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Destination(Current) Database +
    + Host Name + + new_hostname; ?> +
    + MySQL Port No + + new_mysql_port; ?> +
    + MySQL Username + + new_mysql_username; ?> +
    + MYSQL Password + + new_mysql_password); ?> +
    + DB Name + + new_dbname; ?> +
    + +
      + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Source Database +
    + Host Name + + old_hostname; ?> +
    + MySQL Port No + + old_mysql_port; ?> +
    + MySQL Username + + old_mysql_username; ?> +
    + MYSQL Password + + old_mysql_password); ?> +
    + DB Name + + old_dbname; ?> +
    + +
    + +
    + + + Migration Process Log +
    + + +
    + +

    + + Migration Queries Log +
    + + + + + + + + + + + + + + debug("Mickie ---- Patch Process ---- Starts \n\n\n"); + + //This will be used in PatchApply.php file. if this is not set we can't proceed + $source_version = '50'; + $continue_42P2 = true; + + //Now we have to include PatchApply.php which will include necessary patch files + include("modules/Migration/PatchApply.php"); + + $migrationlog->debug("Mickie ---- Patch Process ---- Ends \n\n\n"); + + + + ?> +
    +
    These following queries are executed to modify the 4.2.3/4.2 Patch2 database to 5.0 database. +
    Status Object Suceess/Failure Query
    +
    + + +

    + + Failed Queries Log +
    + + '.$failed_query.''; + ?> +
    + +

    + + + + + + + + + + + + + + + +
    + Total Number of queries executed : + + +
    + Queries Successed : + + + + +
    + Queries Failed : + + + + +
    + + + +
    + + Note : Please copy and archive the failed queries log. This may help in future references.

    +
     
    +
    + + + +
    +
    +
    +
    + +
     
    diff --git a/oss/vtiger/trunk/modules/Migration/MigrationStep0.php b/oss/vtiger/trunk/modules/Migration/MigrationStep0.php new file mode 100644 index 00000000..4edac241 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/MigrationStep0.php @@ -0,0 +1,70 @@ +is_admin != 'on') +{ + die("

    ".$app_strings['LBL_PERMISSION']." ".$app_strings['LBL_GO_BACK'].".
    "); +} + +// Remove the MigrationStep0.tpl file from Smarty cache +$migration_tpl_file = get_smarty_compiled_file('MigrationStep0.tpl'); +if ($migration_tpl_file != null) unlink($migration_tpl_file); + +global $adb,$default_charset,$theme; + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty(); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("MODULE","Migration"); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +if($adb->isPostgres()) + $db_status='1'; +else + $db_status=check_db_utf8_support($adb); + +$config_status=get_config_status(); + +$smarty->assign("DB_CHARSET", get_db_charset($adb)); +$smarty->assign("DB_STATUS", $db_status); +$smarty->assign("CONFIG_CHARSET", $default_charset); +$smarty->assign("CONFIG_STATUS", $config_status); + +$data_conversion_msg = array( + /* php: utf8, d: utf8 */ + '1' => array('msg1'=> '', 'msg2' => '', 'checked' => 'true'), + '2' => array('msg1'=> "To have complete UTF-8 support:-
    1. Set \$default_charset='UTF-8'; in config.inc.php
    2. Select the check box below for database charset handling and data conversion.
    ", + 'msg2' => 'To continue without UTF-8 support, keep the above option unchecked.', 'checked' => 'false'), + '3' => array('msg1'=> "To have complete UTF-8 support, we recommend you to set \$default_charset='UTF-8'; in config.inc.php.", + 'msg2' => "Select the above check box after changing the config file, if you need UTF-8 data conversion (Unicode support).", + 'checked' => 'false'), + '4' => array('msg1'=> "UTF-8 should be enabled for database to have complete unicode support. This will be handled in data conversion to UTF-8.", + 'msg2' => "De-select the above check box, if you do not need UTF-8 data conversion (Unicode support will be inconsistent).", + 'checked' => 'true')); + +$db_migration_status = getMigrationCharsetFlag(); + +if ($db_migration_status == MIG_CHARSET_PHP_UTF8_DB_UTF8) { + header("Location: index.php?module=Migration&action=index&parenttab=Settings"); +} + +$smarty->assign("CONVERSION_MSG", $data_conversion_msg[$db_migration_status]); + +$smarty->display("MigrationStep0.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Migration/MigrationStep1.php b/oss/vtiger/trunk/modules/Migration/MigrationStep1.php new file mode 100644 index 00000000..a52a6125 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/MigrationStep1.php @@ -0,0 +1,137 @@ +is_admin != 'on') +{ + die("

    ".$app_strings['LBL_PERMISSION']." ".$app_strings['LBL_GO_BACK'].".
    "); +} + +//To get the Current installed MySQL path +include("connection.php"); +$vtiger_home = $_ENV["VTIGER_HOME"]; +$mysqldir = $mysql_dir; + +if(is_file($mysqldir."/bin/mysqldump")) +{ + $installed_mysql_path = $mysqldir."/bin/mysqldump"; + $getmysqlpath = 0; +} +elseif(is_file($vtiger_home."/mysql/bin/mysqldump")) +{ + $installed_mysql_path = $vtiger_home."/mysql/bin/mysqldump"; + $getmysqlpath = 0; +} +elseif(substr($_ENV["OS"],0,3) == "Win") +{ + if(is_file($vtiger_home.'\mysql\bin\mysql.exe')) + { + $installed_mysql_path = $vtiger_home.'\mysql\bin\mysqldump.exe'; + @session_unregister('set_server_mysql_path'); + $_SESSION['set_server_mysql_path'] = $vtiger_home.'\mysql\bin'; + $getmysqlpath = 0; + } + else + { + $getmysqlpath = 1; + } +} +else +{ + $getmysqlpath = 1; + + if($_REQUEST['migration_option'] == 'alter_db_details') + $showmysqlpath = 'none'; + else + $showmysqlpath = 'block'; +} + + + +require_once('Smarty_setup.php'); + +global $app_strings,$app_list_strings,$mod_strings,$theme,$currentModule; + +$smarty = new vtigerCRM_Smarty(); + + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("MODULE","Migration"); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +$smarty->assign("DB_DETAILS_CHECKED", 'checked'); +$smarty->assign("SHOW_DB_DETAILS", 'block'); + +//Based on this $getmysqlpath variable we should get the mysql path from the user +$smarty->assign("GET_MYSQL_PATH",$getmysqlpath); +$smarty->assign("SHOW_MYSQL_PATH",$showmysqlpath); + +//this is to set the entered values when we could not proceed the migration and return to step1 +if($_REQUEST['migration_option'] != '') +{ + if($_REQUEST['migration_option'] == 'db_details') + { + if($_REQUEST['old_host_name'] != '') + $smarty->assign("OLD_HOST_NAME", $_REQUEST['old_host_name']); + if($_REQUEST['old_port_no'] != '') + $smarty->assign("OLD_PORT_NO", $_REQUEST['old_port_no']); + if($_REQUEST['old_mysql_username'] != '') + $smarty->assign("OLD_MYSQL_USERNAME", $_REQUEST['old_mysql_username']); + if($_REQUEST['old_mysql_password'] != '') + $smarty->assign("OLD_MYSQL_PASSWORD", $_REQUEST['old_mysql_password']); + if($_REQUEST['old_dbname'] != '') + $smarty->assign("OLD_DBNAME", $_REQUEST['old_dbname']); + + if($_REQUEST['server_mysql_path'] != '') + $smarty->assign("SERVER_MYSQL_PATH", $_REQUEST['server_mysql_path']); + } + elseif($_REQUEST['migration_option'] == 'dump_details') + { + $smarty->assign("DUMP_DETAILS_CHECKED", 'checked'); + $smarty->assign("DB_DETAILS_CHECKED", ''); + + $smarty->assign("SHOW_DUMP_DETAILS", 'block'); + $smarty->assign("SHOW_DB_DETAILS", 'none'); + } + else + { + if($_REQUEST['alter_old_host_name'] != '') + $smarty->assign("ALTER_OLD_HOST_NAME", $_REQUEST['alter_old_host_name']); + if($_REQUEST['alter_old_port_no'] != '') + $smarty->assign("ALTER_OLD_PORT_NO", $_REQUEST['alter_old_port_no']); + if($_REQUEST['alter_old_mysql_username'] != '') + $smarty->assign("ALTER_OLD_MYSQL_USERNAME", $_REQUEST['alter_old_mysql_username']); + if($_REQUEST['alter_old_mysql_password'] != '') + $smarty->assign("ALTER_OLD_MYSQL_PASSWORD", $_REQUEST['alter_old_mysql_password']); + if($_REQUEST['alter_old_dbname'] != '') + $smarty->assign("ALTER_OLD_DBNAME", $_REQUEST['alter_old_dbname']); + + if($_REQUEST['server_mysql_path'] != '') + $smarty->assign("SERVER_MYSQL_PATH", $_REQUEST['server_mysql_path']); + + $smarty->assign("DB_DETAILS_CHECKED", ''); + $smarty->assign("DUMP_DETAILS_CHECKED", ''); + $smarty->assign("ALTER_DB_DETAILS_CHECKED", 'checked'); + + $smarty->assign("SHOW_DB_DETAILS", 'none'); + $smarty->assign("SHOW_DUMP_DETAILS", 'none'); + $smarty->assign("SHOW_ALTER_DB_DETAILS", 'block'); + } +} + +$smarty->display("MigrationStep1.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/PatchApply.php b/oss/vtiger/trunk/modules/Migration/PatchApply.php new file mode 100644 index 00000000..029a05ef --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/PatchApply.php @@ -0,0 +1,197 @@ +is_admin != 'on') +{ + die("

    ".$app_strings['LBL_PERMISSION']." ".$app_strings['LBL_GO_BACK'].".
    "); +} + +include("modules/Migration/versions.php"); +$migrationlog =& LoggerManager::getLogger('MIGRATION'); + +//global $vtiger_current_version; +if($_REQUEST['source_version'] != '') + $source_version = $_REQUEST['source_version']; + +//echo '
    Source Version = '.$source_version.'
    Current Version = '.$current_version; + +if(!isset($source_version) || empty($source_version)) +{ + //If source version is not set then we cannot proceed + echo "
    Source Version is not set. Please provide the Source Version and contiune the Patch Process"; + exit; +} + +$reach = 0; +foreach($versions as $version => $label) +{ + if($version == $source_version || $reach == 1) + { + $reach = 1; + $temp[] = $version; + } +} +$temp[] = $current_version; + +if(!isset($continue_42P2))//This variable is used in MigrationInfo.php to avoid display the table tag +{ + echo "
    Going to apply the Database Changes...
    "; + //echo ''; + echo '
    '; +} + +//Here we have to decide the database object to which we have to run the migration queries +//For options 1 and 2 we need to execute the queries in current database ie., adb object +//But for option 3, we have to run the queries in given 4.2.3 database ie., conn object +//This session variable should be used in all patch files(which contains the queries) so that based on the option selected the queries will be executed in the corresponding database. ie., in all patch files we have to assign this session object to adb and conn objects +global $adb; +if($_REQUEST['migration_option'] == 'alter_db_details') + $_SESSION['adodb_current_object'] = $conn; +else + $_SESSION['adodb_current_object'] = $adb; + + +for($patch_count=0;$patch_count ".$temp[$patch_count+1]." Database changes -- Starts.".$end_tag; + + include($filename);//include the file which contains the corresponding db changes + + echo $start_tag.$temp[$patch_count]." ==> ".$temp[$patch_count+1]." Database changes -- Ends.".$end_tag; + } + elseif(isset($temp[$patch_count+1])) + { + echo $empty_tag.$start_tag."There is no Database Changes from ".$temp[$patch_count]." ==> ".$temp[$patch_count+1].$end_tag; + } + else + { + //No file available or Migration not provided for this release + //echo '
    No Migration / No File ==> '.$filename; + } + if($adb->isMySQL()) { + @include_once('modules/Migration/Performance/'.$temp[$patch_count+1].'_mysql.php'); + } elseif($adb->isPostgres()) { + @include_once('modules/Migration/Performance/'.$temp[$patch_count+1].'_postgres.php'); + } +} + + if(getMigrationCharsetFlag() == MIG_CHARSET_PHP_UTF8_DB_UTF8) + { + echo '


    '; + include("modules/Migration/HTMLtoUTF8Conversion.php"); + } + +if(!isset($continue_42P2))//This variable is used in MigrationInfo.php to avoid display the table tag +{ + echo ''; + echo '

    Failed Queries Log +
    '; + + if(is_array($failure_query_array)) + foreach($failure_query_array as $failed_query) + echo '
    '.$failed_query.';'; + else + echo '
    No queries failed during Patch Update.'; + + echo '
    '; + //echo "Failed Queries ==>
    ";print_r($failure_query_array);echo '
    '; +} + + +//HANDLE HERE - Mickie +//Here we have to update the version in table. so that when we do migration next time we will get the version +global $vtiger_current_version; +$res = $adb->pquery("select * from vtiger_version", array()); +if($adb->num_rows($res)) +{ + $res = $adb->pquery("update vtiger_version set old_version=?,current_version=?", array($versions[$source_version], $vtiger_current_version)); +} +else +{ + $adb->pquery("insert into vtiger_version (id, old_version, current_version) values ('', ?, ?);", array($versions[$source_version], $vtiger_current_version)); +} + +//If currency name in config.inc.php file and currency name in vtiger_currency_info table is differ then we have to change in config.inc.php file +$mig_currency = $adb->query_result($adb->pquery("select currency_name from vtiger_currency_info", array()),0,'currency_name'); +if($currency_name != $mig_currency) +{ + echo "

    NOTE:

    Please change the base currency name as '$mig_currency' in config.inc.php ie., change the variable currency name as $"."currency_name = '$mig_currency' in config.inc.php file.


    "; +} + +echo ' + + + + +
     
    +
    + + + +
    +


    '; + +perform_post_migration_activities(); + +//Function used to execute the query and display the success/failure of the query +function ExecuteQuery($query) +{ + global $adb; + global $conn, $query_count, $success_query_count, $failure_query_count, $success_query_array, $failure_query_array; + global $migrationlog; + + //For third option migration we have to use the $conn object because the queries should be executed in 4.2.3 db + if($_REQUEST['migration_option'] == 'alter_db_details') + $status = $conn->query($query); + else + $status = $adb->query($query); + + $query_count++; + if(is_object($status)) + { + echo ' + + '.get_class($status).' + S + '.$query.' + '; + $success_query_array[$success_query_count++] = $query; + $migrationlog->debug("Query Success ==> $query"); + } + else + { + echo ' + + '.$status.' + F + '.$query.' + '; + $failure_query_array[$failure_query_count++] = $query; + $migrationlog->debug("Query Failed ==> $query \n Error is ==> [".$adb->database->ErrorNo()."]".$adb->database->ErrorMsg()); + } +} + + +?> diff --git a/oss/vtiger/trunk/modules/Migration/deleteCustomFields.php b/oss/vtiger/trunk/modules/Migration/deleteCustomFields.php new file mode 100644 index 00000000..7b8ad017 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/deleteCustomFields.php @@ -0,0 +1,57 @@ +"columnname", + "vtiger_cvstdfilter"=>"columnname", + "vtiger_cvadvfilter"=>"columnname", + "vtiger_selectcolumn"=>"columnname", + "vtiger_relcriteria"=>"columnname", + "vtiger_reportsortcol"=>"columnname", + "vtiger_reportdatefilter"=>"datecolumnname", + "vtiger_reportsummary"=>"columnname", + ); + + +foreach($tables_array as $tablename => $columnname) +{ + $query = "select $columnname from $tablename where $columnname like '%:cf_%'"; + $result = $conn->query($query); + $noofrows = $conn->num_rows($result); + + for($i=0;$i<$noofrows;$i++) + { + //First get the fieldname from the result + $col_value = $conn->query_result($result,$i,$columnname); + $fieldname = substr($col_value,strpos($col_value,':cf_')+1,6); + + //Now check whether this field is available in field table + $sql1 = "select fieldid from vtiger_field where fieldname='".$fieldname."' and vtiger_field.presence in (0,2)"; + $result1 = $conn->query($sql1); + $noofrows1 = $conn->num_rows($result1); + $fieldid = $conn->query_result($result1,0,"fieldid"); + + //if there is no field then we have to delete that field entries + if($noofrows1 == 0 && !isset($fieldid)) + { + //Now we have to delete that customfield from the $tablename + Execute("delete from $tablename where $columnname like '%:".$fieldname.":%'"); + } + } +} + + + +?> diff --git a/oss/vtiger/trunk/modules/Migration/index.php b/oss/vtiger/trunk/modules/Migration/index.php new file mode 100644 index 00000000..ebd43fb0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/index.php @@ -0,0 +1,134 @@ +is_admin != 'on') +{ + die("

    ".$app_strings['LBL_PERMISSION']." ".$app_strings['LBL_GO_BACK'].".
    "); +} + +// Remove the Migration.tpl file from Smarty cache +$migration_tpl_file = get_smarty_compiled_file('Migration.tpl'); +if ($migration_tpl_file != null) unlink($migration_tpl_file); + +if(getMigrationCharsetFlag() != MIG_CHARSET_PHP_UTF8_DB_UTF8 && !isset($_REQUEST['migration_charstcheck'])) +{ + include('modules/Migration/MigrationStep0.php'); + exit; +} + +include("modules/Migration/versions.php"); +require_once('Smarty_setup.php'); +global $app_strings,$app_list_strings,$mod_strings,$theme,$currentModule; +include("vtigerversion.php"); +//Check the current version before starting migration. If the current versin is latest, then we wont allow to do 5.x migration. But here we must allow for 4.x migration. Because 4.x migration can be done with out changing the current database. -Shahul +$status=true; +$exists=$adb->query("show create table vtiger_version"); +if($exists) +{ + $result = $adb->query("select * from vtiger_version"); + $dbversion = $adb->query_result($result, 0, 'current_version'); + if($dbversion == $vtiger_current_version) + { + $status=false; + } + +} +if(!$adb->isPostgres()) { + if(isset($_REQUEST['dbconversionutf8'])) { + if($_REQUEST['dbconversionutf8'] == 'yes') { + $query = " ALTER DATABASE ".$dbconfig['db_name']." DEFAULT CHARACTER SET utf8"; + $adb->query($query); + } + } +} + +//Added to check config variables($CALENDAR_DISPLAY = 'true',$CHAT_DISPLAY = 'true';) is present or Not +global $CALENDAR_DISPLAY,$CHAT_DISPLAY; +$cal_status =false; +$chat_status =false; +$final_status =false; +$disp_msg = ''; + +if(isset($CALENDAR_DISPLAY)) + $cal_status = true; +if(isset($CHAT_DISPLAY)) + $chat_status = true; + +if($cal_status == false && $chat_status == true) +{ + $final_status = false; + $disp_msg = 'The $CALENDAR_DISPLAY variable not available in the config.inc.php file .
    Please add the following line at the end of the file config.inc.php before starting migration.
    '; + $disp_msg .= ' $CALENDAR_DISPLAY = '."'true'; "; +} +else if($cal_status == true && $chat_status == false) +{ + $final_status = false; + $disp_msg = 'The $CHAT_DISPLAY variable not available in the config.inc.php file .
    Please add the following line at the end of the file config.inc.php before starting migration.
    '; + $disp_msg .= '$CHAT_DISPLAY ='." 'true'; "; +} +else if($cal_status == false && $chat_status == false) +{ + $final_status = false; + $disp_msg = 'The $CALENDAR_DISPLAY, $CHAT_DISPLAY variables are not available in the config.inc.php file .
    Please add the following lines at the end of the file config.inc.php before starting migration.
    '; + $disp_msg .= ' $CALENDAR_DISPLAY = '."'true';
    ".'$CHAT_DISPLAY = '." 'true'; "; +} +else if($cal_status == true && $chat_status == true) + $final_status = true; + +if(!$final_status) +{ + echo '
    + + +
    '; + echo ' '; + echo $disp_msg; + echo '

    Kindly do the necessary changes in config.inc.php and click on the "Proceed" button to proceed with the Migration.
    '; + echo '

    + + + +
    '; + exit; + +} + + +$smarty = new vtigerCRM_Smarty(); + +$smarty->assign("MIG_CHECK", $status); +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("MODULE","Migration"); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +$source_versions = ""; + +$smarty->assign("SOURCE_VERSION", $source_versions); +global $vtiger_current_version; +$smarty->assign("CURRENT_VERSION", $vtiger_current_version); + +$smarty->display("Migration.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Migration/language/en_us.lang.php b/oss/vtiger/trunk/modules/Migration/language/en_us.lang.php new file mode 100644 index 00000000..3c4dec91 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/language/en_us.lang.php @@ -0,0 +1,100 @@ +'Enter Values to Migrate Data from Source to Current (Latest) vtigerCRM ', +'LBL_CURRENT_VT_MYSQL_EXIST'=>'Current vtiger\'s MySQL Exist in', +'LBL_THIS_MACHINE'=>'This Machine', +'LBL_DIFFERENT_MACHINE'=>'Different Machine', +'LBL_CURRENT_VT_MYSQL_PATH'=>'Current vtiger\'s MySQL path', +'LBL_SOURCE_VT_MYSQL_DUMPFILE'=>'vtiger Source Dump File name', +'LBL_NOTE_TITLE'=>'Note:', +'LBL_NOTES_LIST1'=>'If Current MySQL Exist in the Same Machine then enter the MySQL Path (or) you can enter the Dump file if you have.', +'LBL_NOTES_LIST2'=>'If Current MySQL Exist in different Machine then enter the (Source) Dump filename with the full Path.', +'LBL_NOTES_DUMP_PROCESS'=>'To take Database dump please execute the following command from inside the mysql/bin directory +
    mysqldump --user="mysql_username" --password="mysql-password" -h "hostname" --port="mysql_port" "database_name" > dump_filename +
    add SET FOREIGN_KEY_CHECKS = 0; -- at the start of the dump file +
    add SET FOREIGN_KEY_CHECKS = 1; -- at the end of the dump file', +'LBL_NOTES_LIST3'=>'Give the MySQL path like /home/crm/vtigerCRM4_5/mysql', +'LBL_NOTES_LIST4'=>'Give the Dump filename with full Path like /home/fullpath/4_2_dump.txt', + +'LBL_CURRENT_MYSQL_PATH_FOUND'=>'Current installation\'s MySQL path has been found.', +'LBL_SOURCE_HOST_NAME'=>'Source Host Name :', +'LBL_SOURCE_MYSQL_PORT_NO'=>'Source MySql Port No :', +'LBL_SOURCE_MYSQL_USER_NAME'=>'Source MySql User Name :', +'LBL_SOURCE_MYSQL_PASSWORD'=>'Source MySql Password :', +'LBL_SOURCE_DB_NAME'=>'Source Database Name :', +'LBL_MIGRATE'=>'Migrate to Current Version', +//Added after 5 Beta +'LBL_UPGRADE_VTIGER'=>'Upgrade vtiger CRM Database', +'LBL_UPGRADE_FROM_VTIGER_423'=>'Upgrade database from vtiger CRM 4.2.3 to 5.0.0', +'LBL_SETTINGS'=>'Settings', +'LBL_STEP'=>'Step', +'LBL_SELECT_SOURCE'=>'Select Source', +'LBL_STEP1_DESC'=>'To Start database migration, you must specify the format in which the old data is available', +'LBL_RADIO_BUTTON1_TEXT'=>'I have access to vtiger CRM live database system', +'LBL_RADIO_BUTTON1_DESC'=>'This option requires you to have the host machine\'s ( where the DB is stored ) address and DB access details. Both local and remote systems are supported in this method. Refer documentation for Help.', +'LBL_RADIO_BUTTON2_TEXT'=>'I have access to vtiger CRM archived database dump', +'LBL_RADIO_BUTTON2_DESC'=>'This option requires database dump available locally in the same machine in which you are upgrading. You cannot access data dump from a different machine (remote database server). Refer documentation for Help.', +'LBL_RADIO_BUTTON3_TEXT'=>'I have a new database with 4.2.3 Data', +'LBL_RADIO_BUTTON3_DESC'=>'This option requires vtiger CRM 4.2.3 database system details, including database server ID, user name, and password. You cannot access data dump from a different machine (remote database server).', + +'LBL_HOST_DB_ACCESS_DETAILS'=>'Host Database Access Details', +'LBL_MYSQL_HOST_NAME_IP'=>'MySQL Host Name or IP Address : ', +'LBL_MYSQL_PORT'=>'MySQL Port Number : ', +'LBL_MYSQL_USER_NAME'=>'MySql User Name : ', +'LBL_MYSQL_PASSWORD'=>'MySql Password : ', +'LBL_DB_NAME'=>'Database Name : ', + +'LBL_LOCATE_DB_DUMP_FILE'=>'Locate Database Dump File', +'LBL_DUMP_FILE_LOCATION'=>'Dump File Location : ', + +'LBL_RADIO_BUTTON3_PROCESS'=>'Please do not specify the 4.2.3 database details. This option will alter the given database directly. +
    It is strongly recommended that to do the following. +
    1. Take a dump of your 4.2.3 database +
    2. Create new database (Better is to create a database in the server where your vtiger 5.0 Database is running.) +
    3. Apply this 4.2.3 dump to this new database. +
    Now give this new database access details. This migration will modify this Database to fit with the 5.0 Schema. +Then you can give this Database name in config.inc.php file to use this Database ie., $dbconfig[\'db_name\'] = \'new db name\';', + +'LBL_ENTER_MYSQL_SERVER_PATH'=>'Enter MySQL Server Path', +'LBL_SERVER_PATH_DESC'=>'MySQL path in the server like /home/5beta/vtigerCRM5_beta/mysql/bin or c:\Program Files\mysql\bin', +'LBL_MYSQL_SERVER_PATH'=>'MySQL Server Path : ', +'LBL_MIGRATE_BUTTON'=>'Migrate', +'LBL_CANCEL_BUTTON'=>'Cancel', +'LBL_UPGRADE_FROM_VTIGER_5X'=>'Upgrade database from vtiger CRM 5.x to next version', +'LBL_PATCH_OR_MIGRATION'=>'you must specify the source database version (Patch update or Migration)', +//Added for java script alerts +'ENTER_SOURCE_HOST' => 'Please enter the Source Host Name', +'ENTER_SOURCE_MYSQL_PORT' => 'Please enter the Source MySql Port Number', +'ENTER_SOURCE_MYSQL_USER' => 'Please enter the Source MySql User Name', +'ENTER_SOURCE_DATABASE' => 'Please enter the Source Database Name', +'ENTER_SOURCE_MYSQL_DUMP' => 'Please enter the Valid MySQL Dump File', +'ENTER_HOST' => 'Please enter the Host Name', +'ENTER_MYSQL_PORT' => 'Please enter the MySql Port Number', +'ENTER_MYSQL_USER' => 'Please enter the MySql User Name', +'ENTER_DATABASE' => 'Please enter the Database Name', +'SELECT_ANYONE_OPTION' => 'Please select any one option', +'ENTER_CORRECT_MYSQL_PATH' => 'Please enter the Correct MySQL Path', + +); + + + + + + +?> diff --git a/oss/vtiger/trunk/modules/Migration/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Migration/language/zh_cn.lang.php new file mode 100644 index 00000000..b39a0e44 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/language/zh_cn.lang.php @@ -0,0 +1,96 @@ + '输入升级数据,从 来源版本 升级到 最新版本的vtigerCRM ', +'LBL_CURRENT_VT_MYSQL_EXIST' => '目前 vtiger 的数据库存在于', + 'LBL_THIS_MACHINE' => '这台机器', + 'LBL_DIFFERENT_MACHINE' => '不同机器', + 'LBL_CURRENT_VT_MYSQL_PATH' => '目前 vtiger 的数据库路径', + 'LBL_SOURCE_VT_MYSQL_DUMPFILE' => 'vtiger 来源版本 汇出资料的文件名称', + 'LBL_NOTE_TITLE' => '备注:', + 'LBL_NOTES_LIST1' => '如果目前的数据库是在同一台机器,输入数据库路径(或)输入汇出数据的文件名称。', + 'LBL_NOTES_LIST2' => '如果目前的数据库存在于不同机器,输入(来源)汇出数据的文件名称与完整路径。', + 'LBL_NOTES_DUMP_PROCESS' => '要将数据库汇出,请参考下面指令:
    mysqldump --user="mysql_username" --password="mysql-password" -h "hostname" --port="mysql_port" "database_name" > dump_filename
    新增 SET_FOREIGN_KEY_CHECKS = 0; -- 到档案开始的地方
    新增 SET_FOREIGN_KEY_CHECKS = 1; -- 到档案结束的地方', + 'LBL_NOTES_LIST3' => '提供数据库的路径,像是 /home/crm/vtigerCRM4_5/mysql', + 'LBL_NOTES_LIST4' => '提供汇出数据的档案路径,像是 /home/fullpath/4_2_dump.txt', + + 'LBL_CURRENT_MYSQL_PATH_FOUND' => '找到目前版本的数据库路径。', + 'LBL_SOURCE_HOST_NAME' => '来源主机名称:', + 'LBL_SOURCE_MYSQL_PORT_NO' => '来源数据库连接端口:', + 'LBL_SOURCE_MYSQL_USER_NAME' => '来源数据库账号:', + 'LBL_SOURCE_MYSQL_PASSWORD' => '来源数据库密码:', + 'LBL_SOURCE_DB_NAME' => '来源数据库名称:', + 'LBL_MIGRATE' => '升级到最新版本', +//Added after 5 Beta +'LBL_UPGRADE_VTIGER' => '升级 vtiger CRM 数据库', + 'LBL_UPGRADE_FROM_VTIGER_423' => '将数据库从 vtiger CRM 4.2.3 升级到 5.0.0', + 'LBL_SETTINGS' => '设定', + 'LBL_STEP' => '步骤', + 'LBL_SELECT_SOURCE' => '选择来源', + 'LBL_STEP1_DESC' => '要开始数据库移转,您必须指定旧有数据的格式', + 'LBL_RADIO_BUTTON1_TEXT' => '我有 vtiger CRM 数据库系统的权限', + 'LBL_RADIO_BUTTON1_DESC' => '这个选项需要主机(数据库所在)地址与数据库权限细节,这个方法同时支持本地与远程系统,细节请参考文件说明。', + 'LBL_RADIO_BUTTON2_TEXT' => '我有 vtiger CRM 数据库备份', + 'LBL_RADIO_BUTTON2_DESC' => '这个选项需要有数据库备份文件在同一台机器来进行升级,您无法存取不同主机(远程数据库服务器)的备份数据,细节请参考文件说明。', + 'LBL_RADIO_BUTTON3_TEXT' => '我有新的数据库包含 4.2.3 数据', + 'LBL_RADIO_BUTTON3_DESC' => '这个选项需要 vtiger CRM 4.2.3 数据库系统细节,包含服务器编号、账号与密码,您无法存取不同主机(远程数据库服务器)的备份数据。', + +'LBL_HOST_DB_ACCESS_DETAILS' => '主机数据库存取权限', + 'LBL_MYSQL_HOST_NAME_IP' => 'MySQL 主机名称或IP地址:', + 'LBL_MYSQL_PORT' => 'MySQL 连接埠编号:', + 'LBL_MYSQL_USER_NAME' => 'MySql 账号:', + 'LBL_MYSQL_PASSWORD' => 'MySql 密码:', + 'LBL_DB_NAME' => '数据库名称:', + + 'LBL_LOCATE_DB_DUMP_FILE' => '数据库备份文件', + 'LBL_DUMP_FILE_LOCATION' => '备份文件位置:', + +'LBL_RADIO_BUTTON3_PROCESS'=>'Please do not specify the 4.2.3 database details. This option will alter the given database directly. +
    It is strongly recommended that to do the following. +
    1. Take a dump of your 4.2.3 database +
    2. Create new database (Better is to create a database in the server where your vtiger 5.0 Database is running.) +
    3. Apply this 4.2.3 dump to this new database. +
    Now give this new database access details. This migration will modify this Database to fit with the 5.0 Schema. +Then you can give this Database name in config.inc.php file to use this Database ie., $dbconfig[\'db_name\'] = \'new db name\';', + 'LBL_ENTER_MYSQL_SERVER_PATH' => '输入 MySQL 服务器路径', +'LBL_SERVER_PATH_DESC' => 'MySQL 在服务器的路径,像是 /home/5beta/vtigerCRM5_beta/mysql/binc:\Program Files\mysql\bin', + 'LBL_MYSQL_SERVER_PATH' => 'MySQL 服务器路径:', + 'LBL_MIGRATE_BUTTON' => '转换', + 'LBL_CANCEL_BUTTON' => '取消', +'LBL_UPGRADE_FROM_VTIGER_5X' => '升级 vtiger CRM 5.x 数据库到下一个版本', + 'LBL_PATCH_OR_MIGRATION' => '您必须指定来源数据库的版本(修补程序更新或是转换)', +//Added for java script alerts +'ENTER_SOURCE_HOST' => '请输入源主机名称', +'ENTER_SOURCE_MYSQL_PORT' => '请输入源主机MYSQL名称', +'ENTER_SOURCE_MYSQL_USER' => '请输入mysql的用户名', +'ENTER_SOURCE_DATABASE' => '请输入数据库密码', +'ENTER_SOURCE_MYSQL_DUMP' => '请输入有效的mysql转储文件', +'ENTER_HOST' => '请输入主机名称', +'ENTER_MYSQL_PORT' => '请输入mysql的端口号', +'ENTER_MYSQL_USER' => '请输入mysql的用户名', +'ENTER_DATABASE' => '请输入数据库名', +'SELECT_ANYONE_OPTION' => '请选择其中的任何一个选项', +'ENTER_CORRECT_MYSQL_PATH' => '请输入正确的mysql路径', + +); + + + + + + +?> diff --git a/oss/vtiger/trunk/modules/Migration/rename_tables.php b/oss/vtiger/trunk/modules/Migration/rename_tables.php new file mode 100644 index 00000000..a77a777a --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/rename_tables.php @@ -0,0 +1,71 @@ +debug("Inside the file rename_tables.php to rename the table names with prefix vtiger_"); + +//Rename all the tables with prefix vtiger_ +$tables_list = $conn->get_tables(); +foreach($tables_list as $index => $tablename) +{ + $sql = "rename table $tablename to $prefix$tablename"; + Execute($sql); +} +//Table renaming ends. + + +//In these following tablename => field we have to add the prefix vtiger_ as they are the tablenames +$change_cols_array = Array( + "cvcolumnlist"=>"columnname", + "cvstdfilter"=>"columnname", + "cvadvfilter"=>"columnname", + "selectcolumn"=>"columnname", + "relcriteria"=>"columnname", + "reportsortcol"=>"columnname", + "reportdatefilter"=>"datecolumnname", + "reportsummary"=>"columnname", + "field"=>"tablename", + ); + +foreach($change_cols_array as $tablename => $columnname) +{ + $result = $conn->query("select $columnname from $prefix$tablename"); + + while($row = $conn->fetch_row($result)) + { + if((!strstr($row[$columnname],$prefix)) && $row[$columnname] !='' && $row[$columnname] != 'none') + { + //for reportsummary we should add prefix in second value ie., after first :(semicolon) + if($tablename == 'reportsummary') + { + $queries_list .= "update $prefix$tablename set $columnname=\"".str_replace("cb:","cb:$prefix",$row[$columnname])."\" where $columnname=\"$row[$columnname]\"&&##"; + } + else + { + $queries_list .= "update $prefix$tablename set $columnname=\"$prefix$row[$columnname]\" where $columnname=\"$row[$columnname]\"&&##"; + } + } + } +} + +$queries_array = explode("&&##",trim($queries_list,"&&##")); + +foreach($queries_array as $index => $query) +{ + Execute($query); +} + + +$migrationlog->debug("End of file rename_tables.php. The table names renamed with prefix vtiger_"); +?> diff --git a/oss/vtiger/trunk/modules/Migration/updateCurrency.php b/oss/vtiger/trunk/modules/Migration/updateCurrency.php new file mode 100644 index 00000000..6f2f7571 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/updateCurrency.php @@ -0,0 +1,79 @@ +println('conversion rate = '.$crate); + + $query = "UPDATE vtiger_currency_info SET conversion_rate=? WHERE id=1"; + $result = $conn->pquery($query, array($crate)); + + //array should be id || vtiger_fieldname => vtiger_tablename + $modules_array = Array( + "accountid||annualrevenue" => "vtiger_account", + + "leadid||annualrevenue" => "vtiger_leaddetails", + + "potentialid||amount" => "vtiger_potential", + + "productid||unit_price" => "vtiger_products", + + "salesorderid||salestax" => "vtiger_salesorder", + "salesorderid||adjustment" => "vtiger_salesorder", + "salesorderid||total" => "vtiger_salesorder", + "salesorderid||subtotal" => "vtiger_salesorder", + + "purchaseorderid||salestax" => "vtiger_purchaseorder", + "purchaseorderid||adjustment" => "vtiger_purchaseorder", + "purchaseorderid||total" => "vtiger_purchaseorder", + "purchaseorderid||subtotal" => "vtiger_purchaseorder", + + "quoteid||tax" => "vtiger_quotes", + "quoteid||adjustment" => "vtiger_quotes", + "quoteid||total" => "vtiger_quotes", + "quoteid||subtotal" => "vtiger_quotes", + + "invoiceid||salestax" => "vtiger_invoice", + "invoiceid||adjustment" => "vtiger_invoice", + "invoiceid||total" => "vtiger_invoice", + "invoiceid||subtotal" => "vtiger_invoice", + ); + + foreach($modules_array as $fielddetails => $table) + { + $temp = explode("||",$fielddetails); + $id_name = $temp[0]; + $fieldname = $temp[1]; + + $res = $conn->query("select $id_name, $fieldname from $table"); + $record_count = $conn->num_rows($res); + + for($i=0;$i<$record_count;$i++) + { + $recordid = $conn->query_result($res,$i,$id_name); + $old_value = $conn->query_result($res,$i,$fieldname); + + //calculate the new value + $new_value = $old_value/$crate;//convertToDollar($old_value,$crate); + $conn->println("old value = $old_value && new value = $new_value"); + + $update_query = "update $table set $fieldname='".$new_value."' where $id_name=$recordid"; + $update_result = $conn->query($update_query); + } + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Migration/versions.php b/oss/vtiger/trunk/modules/Migration/versions.php new file mode 100644 index 00000000..934f2b11 --- /dev/null +++ b/oss/vtiger/trunk/modules/Migration/versions.php @@ -0,0 +1,28 @@ +"5.0", + "501"=>"5.0.1", + "502"=>"5.0.2", + "503rc2"=>"5.0.3 RC2", + "503"=>"5.0.3", + "504rc"=>"5.0.4 RC", + "504"=>"5.0.4", + "510rc"=>"5.1.0 RC", + ); + +$current_version = '510'; + +?> diff --git a/oss/vtiger/trunk/modules/Mobile/Mobile-README b/oss/vtiger/trunk/modules/Mobile/Mobile-README new file mode 100644 index 00000000..b7f7612c --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/Mobile-README @@ -0,0 +1,12 @@ +Project URL: http://code.google.com/p/iui + +Modified version: http://www.k10design.net//iui/iui.js + +Further Customization: + +iui.js ++ Avoided re-fetching link each time by re-writing href after first fetch ++ To get back default behavior use 'nocache' for the link's class attribute + +iui.css ++ Added -moz- specific rules \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/Mobile.Config.php b/oss/vtiger/trunk/modules/Mobile/Mobile.Config.php new file mode 100644 index 00000000..ec74dfe1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/Mobile.Config.php @@ -0,0 +1,19 @@ + 25, + + + 'Cache.Info' => true + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/Mobile.js b/oss/vtiger/trunk/modules/Mobile/Mobile.js new file mode 100644 index 00000000..c4a24d1a --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/Mobile.js @@ -0,0 +1,60 @@ +/*+********************************************************************************** + * 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. + ************************************************************************************/ +if(typeof($) == 'undefined') { + $ = function(id) { + var node = document.getElementById(id); + if(typeof(node) == 'undefined') node = false; + return node; + } + $fnT = function(id1, id2) { + var node1 = $(id1); + var node2 = $(id2); + if(node1) node1.style.display = 'none'; + if(node2) node2.style.display = 'block'; + } + $fnFocus = function(id) { + try { + var node = $(id); + node.focus(); + } catch(error) { + } + } + + $fnAddClass = function(node, toadd) { + var classValue = node.className; + var regex = new RegExp(toadd, "g"); + if(classValue.match(regex) == null) { + classValue += " " + toadd; + node.className = classValue; + } + } + $fnRemoveClass = function(node, toremove) { + var classValue = node.className; + var regex = new RegExp(toremove, "g"); + classValue = classValue.replace(regex, ''); + node.className = classValue; + } + + $fnCheckboxOn = function(idprefix) { + //$fnT((idprefix+'_on'), (idprefix+'_off')); + + var nodeon = $(idprefix+'_on'); + var nodeoff = $(idprefix+'_off'); + if(nodeon) $fnAddClass(nodeon.parentNode, 'hide'); + if(nodeoff) $fnRemoveClass(nodeoff.parentNode, 'hide'); + } + $fnCheckboxOff = function(idprefix) { + //$fnT((idprefix+'_off'), (idprefix+'_on')); + + var nodeon = $(idprefix+'_on'); + var nodeoff = $(idprefix+'_off'); + if(nodeon) $fnRemoveClass(nodeon.parentNode, 'hide'); + if(nodeoff) $fnAddClass(nodeoff.parentNode, 'hide'); + } +} \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/Mobile.php b/oss/vtiger/trunk/modules/Mobile/Mobile.php new file mode 100644 index 00000000..f2a90c46 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/Mobile.php @@ -0,0 +1,82 @@ +retrieveCurrentUserInfoFromFile($current_user_id,"Users"); + } + return $current_user; + } + + static function currentUserName() { + if(isset($_SESSION)) { + return $_SESSION[self::SESSION_LOGIN_USER]; + } + } + + static function currentUserId() { + if(isset($_SESSION)) { + return $_SESSION[self::SESSION_LOGIN_USERID]; + } + } + + static function config($key, $defvalue = false) { + // Defined in the configuration file + global $Module_Mobile_Configuration; + if(isset($Module_Mobile_Configuration) && isset($Module_Mobile_Configuration[$key])) { + return $Module_Mobile_Configuration[$key]; + } + returN $defvalue; + } + + static function authenticate($username, $password, $updateInSession = false) { + $userfocus = CRMEntity::getInstance('Users'); + $userfocus->column_fields['user_name'] = $username; + $authsuccess = $userfocus->doLogin($password); + if($updateInSession) { + $_SESSION[Mobile::SESSION_LOGIN_USER] = $username; + $_SESSION[self::SESSION_LOGIN_USERID] = $userfocus->retrieve_user_id($username); + } + return $authsuccess; + } +} +?> diff --git a/oss/vtiger/trunk/modules/Mobile/MobileAjax.php b/oss/vtiger/trunk/modules/Mobile/MobileAjax.php new file mode 100644 index 00000000..50e0401f --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/MobileAjax.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Mobile/MobileHandler.php b/oss/vtiger/trunk/modules/Mobile/MobileHandler.php new file mode 100644 index 00000000..40dfc172 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/MobileHandler.php @@ -0,0 +1,24 @@ + diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/Detail.php b/oss/vtiger/trunk/modules/Mobile/controllers/Detail.php new file mode 100644 index 00000000..1c0cc1e8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/Detail.php @@ -0,0 +1,24 @@ +assign('ID', $ws_id); + +$moduleInstance = Mobile_Core_Module::fromWSID($ws_id); + +$smarty->assign('_MODULE', $moduleInstance); +$smarty->assign('_RECORD', Mobile_Core_Search::retrieve($ws_id, $moduleInstance)); + +$smarty->display(Mobile::templatePath('Detail.tpl')); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/Home.php b/oss/vtiger/trunk/modules/Mobile/controllers/Home.php new file mode 100644 index 00000000..b4a6783f --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/Home.php @@ -0,0 +1,22 @@ +assign('TITLE', 'vtiger CRM'); + +$smarty->assign('_MODULES', Mobile_Core_Module::listAll(true)); + +$smarty->assign('_ALLSKINS', Mobile_Core_Skin::listAll()); +$smarty->assign('_SELSKIN', Mobile_Core_Skin::selected()); + +$smarty->display(Mobile::templatePath('Home.tpl')); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/List.php b/oss/vtiger/trunk/modules/Mobile/controllers/List.php new file mode 100644 index 00000000..5018d91a --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/List.php @@ -0,0 +1,42 @@ +assign('_MODULE', $moduleInstance); +$smarty->assign('_PAGER', $pagingInstance); + +if($q === '') { + $smarty->assign('_RECORDS', Mobile_Core_Search::entity($moduleInstance, $pagingInstance)); + $smarty->assign('_SEARCH_Q', ''); +} else { + $smarty->assign('_RECORDS', + Mobile_Core_Search::query($moduleInstance, $q, + Mobile_Core_Session::get(Mobile_Core_Search::sessionkey($moduleInstance)), + $pagingInstance + ) + ); +} +$smarty->assign('_SEARCH_Q', $q); + +$smarty->assign('_MODE', vtlib_purify($_REQUEST['mode'])); + +$smarty->display(Mobile::templatePath('List.tpl'));; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/Login.php b/oss/vtiger/trunk/modules/Mobile/controllers/Login.php new file mode 100644 index 00000000..b37820c8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/Login.php @@ -0,0 +1,28 @@ +assign('TITLE', 'vtiger CRM Mobile'); + +if(isset($_REQUEST['username'])) $smarty->assign("_ERR", "Login failed! Try again..."); + +$smarty->display(Mobile::templatePath('Login.tpl')); + + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/Logout.php b/oss/vtiger/trunk/modules/Mobile/controllers/Logout.php new file mode 100644 index 00000000..bec080c1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/Logout.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/Search.php b/oss/vtiger/trunk/modules/Mobile/controllers/Search.php new file mode 100644 index 00000000..756a2152 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/Search.php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/SearchConfig.php b/oss/vtiger/trunk/modules/Mobile/controllers/SearchConfig.php new file mode 100644 index 00000000..c295fa99 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/SearchConfig.php @@ -0,0 +1,42 @@ +$v) { + if(preg_match("/field_(.*)/i", $k, $m)) { + $fieldnames[] = vtlib_purify($m[1]); + } + } + + Mobile_Core_Session::put(Mobile_Core_Search::sessionkey($moduleInstance), $fieldnames); + + header("Location: index.php?action=List&module={$moduleInstance->name}&mode=search"); + +} else { + + $searchfields = Mobile_Core_Session::get(Mobile_Core_Search::sessionkey($moduleInstance)); + if($searchfields === false) { + $searchfields = $moduleInstance->fieldnames(); + } + + $smarty = new vtigerCRM_Smarty(); + $smarty->assign('_MODULE', $moduleInstance); + $smarty->assign("_SEARCHIN", $searchfields); + $smarty->display(Mobile::templatePath('SearchConfig.tpl')); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/controllers/Settings.php b/oss/vtiger/trunk/modules/Mobile/controllers/Settings.php new file mode 100644 index 00000000..a710e26c --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/controllers/Settings.php @@ -0,0 +1,19 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Block.php b/oss/vtiger/trunk/modules/Mobile/core/Block.php new file mode 100644 index 00000000..8ded745b --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Block.php @@ -0,0 +1,36 @@ +pquery(" + SELECT blocklabel, fieldname FROM vtiger_field INNER JOIN vtiger_blocks WHERE + vtiger_field.block = vtiger_blocks.blockid AND vtiger_field.tabid = ? + ORDER BY vtiger_blocks.sequence, vtiger_field.sequence", array(getTabid($moduleName))); + + $blockmap = array(); + + if(!empty($result)) { + while($resultrow = $adb->fetch_array($result)) { + $blocklabel = Mobile::getTranslation($resultrow['blocklabel'], $moduleName); + $blockmap[$blocklabel][] = $resultrow['fieldname']; + } + } + return $blockmap; + + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Cache.php b/oss/vtiger/trunk/modules/Mobile/core/Cache.php new file mode 100644 index 00000000..89045187 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Cache.php @@ -0,0 +1,30 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Field.php b/oss/vtiger/trunk/modules/Mobile/core/Field.php new file mode 100644 index 00000000..201598a3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Field.php @@ -0,0 +1,107 @@ + $v) { + if($k == 'type') { + $this->newtype = 'aaa'; + } + $this->$k = $v; + } + } + + function typeName() { + if(isset($this->type)) { + return $this->type['name']; + } + return false; + } + + function isReferenceType() { + return ($this->typeName() == 'reference'); + } + + function format($rawvalue) { + $datatype = $this->typeName(); + + switch($datatype) { + case 'password': + return '********'; + + case 'reference': + case 'owner': + $refersTo = $this->type['refersTo']; + + // No link to Currency reference information + if(preg_match('/(.*)x(.*)/i', $rawvalue)) { + if(!empty($refersTo)) { + if(in_array('Currency', $this->type['refersTo'])) { + return Mobile_Core_Record::summary($rawvalue); + } + } else { + $summary = Mobile_Core_Record::summary($rawvalue); + return "$summary"; + } + } + break; + + case 'email': + if(!empty($rawvalue)) { + return "$rawvalue"; + } + + case 'phone': + case 'mobile': + if(!empty($rawvalue)) { + return "$rawvalue"; + } + + case 'url': + if(!empty($rawvalue)) { + $targeturl = $rawvalue; + if(!preg_match("/:\/\//i", $rawvalue)) { // Not prefixed yet? + $targeturl = "http://$rawvalue"; + } + return "$rawvalue"; + } + } + return $rawvalue; // "$rawvalue ". var_export($datatype, true) . " "; + } + + static function getEntityFieldnames($moduleInstance) { + // TODO Re-write module name if its Events. + $modulename = $moduleInstance->name; + if($modulename == 'Events') $modulename = 'Calendar'; + + $fieldnames = vtws_getEntityNameFields($modulename); + + $replacemap = array(); + + /* Rewrite the entity fieldname with mapping columnname */ + /* Having fieldname and columnname is preferable */ + if($moduleInstance->name == 'HelpDesk') { + $replacemap['title'] = 'ticket_title'; + } else if($moduleInstance->name == 'Documents') { + $replacemap['title'] = 'notes_title'; + } + + if(!empty($replacemap)) { + foreach($replacemap as $replacekey=>$replacevalue) { + $targetkey = array_search($replacekey, $fieldnames); + if($targetkey !== false) $fieldnames[$targetkey] = $replacevalue; + } + } + return $fieldnames; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/MobileService.php b/oss/vtiger/trunk/modules/Mobile/core/MobileService.php new file mode 100644 index 00000000..cb72dbb5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/MobileService.php @@ -0,0 +1,42 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Module.php b/oss/vtiger/trunk/modules/Mobile/core/Module.php new file mode 100644 index 00000000..15f83455 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Module.php @@ -0,0 +1,153 @@ +name = $name; + $this->isEntity = $isEntity; + $this->label = $label; + $this->singular = $singular; + } + + function entityFields() { + if($this->_entityfields === false) { + $this->_entityfields = Mobile_Core_Field::getEntityFieldnames($this); + } + return $this->_entityfields; + } + + function fields() { + if(empty($this->_fields)) { + $this->_fields = $this->doDescribe(); + } + return $this->_fields; + } + + function fieldnames() { + $fieldinstances = $this->fields(); + $names = array(); + foreach($fieldinstances as $fieldinstance) { + $names[] = $fieldinstance->name; + } + return $names; + } + + function fieldLookup($name) { + $fieldinstances = $this->fields(); + foreach($fieldinstances as $fieldinstance) { + if($fieldinstance->name == $name) { + return $fieldinstance; + } + } + return false; + } + + function fieldValue($name, $rawvalue) { + $fieldinstance = $this->fieldLookup($name); + return ($fieldinstance? $fieldinstance->format($rawvalue) : $rawvalue); + } + + function fieldLabel($name) { + $fieldinstance = $this->fieldLookup($name); + return ($fieldinstance? $fieldinstance->label : $name); + } + + function fieldsGroup() { + if($this->_fieldsgroup === false) { + $this->_fieldsgroup = Mobile_Core_Block::groupFields($this->name); + } + return $this->_fieldsgroup; + } + + function doDescribe() { + $describe = vtws_describe($this->name, MobileService::currentUser()); + $instances = array(); + if(!empty($describe['fields'])) { + foreach($describe['fields'] as $infomap) { + $instance = new Mobile_Core_Field($infomap); + $instances[] = $instance; + } + } + return $instances; + } + + static function getInstance($modulename) { + $cachekey = "module.instance.{$modulename}"; + + $moduleInstance = Mobile_Core_Cache::get($cachekey); + if($moduleInstance === false) { + $moduleInstance = new Mobile_Core_Module($modulename, '', + Mobile::getTranslation($modulename, $modulename), $modulename); + + Mobile_Core_Cache::put($cachekey, $moduleInstance); + } + return $moduleInstance; + } + + static function fromWSID($wsid) { + $cachekey = "module.fromwsid.metainfo.{$wsid}"; + + $metainfo = Mobile_Core_Cache::get($cachekey); + if($metainfo === false) { + global $adb; + $idsplit = vtws_getIdComponents($wsid); + $metainfo = VtigerWebserviceObject::fromId($adb, $idsplit[0]); + Mobile_Core_Cache::put($cachekey, $metainfo); + } + return self::getInstance($metainfo->getEntityName()); + } + + static function listAll($filterOnlyEntity = false) { + + $cachekey = "module.listinfo"; + + $listTypesInfo = Mobile_Core_Cache::get($cachekey); + if($listTypesInfo === false) { + $listTypesInfo = vtws_listtypes(MobileService::currentUser()); + Mobile_Core_Cache::put($cachekey, $listTypesInfo); + } + + $instances = array(); + foreach($listTypesInfo['types'] as $name) { + $info = $listTypesInfo['information'][$name]; + $instance = new self( + $name, $info['isEntity'], $info['label'], $info['singular'] + ); + + $filterOutInstance = false; + if($filterOnlyEntity && (!$instance->isEntity || in_array($name, array('Users')))) { + $filterOutInstance = true; + } + + if(!$filterOutInstance) { + $instances[$name] = $instance; + } + sort($instances); + } + return $instances; + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Paging.php b/oss/vtiger/trunk/modules/Mobile/core/Paging.php new file mode 100644 index 00000000..305a207d --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Paging.php @@ -0,0 +1,69 @@ +_start; + } + + function count() { + return $this->_limit; + } + + function current() { + return $this->_page; + } + + function next() { + return ($this->current()+1); + } + + function previous() { + return ($this->current() < 1? 0 : ($this->current()-1)); + } + + function hasNext($countOnPage) { + return ($countOnPage >= $this->count()); + } + + function hasPrevious() { + return ($this->start() != 0); + } + + function initStart($page) { + + if(empty($page)) $page = 0; + $this->_page = $page; + + if($page < 1) $this->_start = 0; + else $this->_start = ($page * $this->_limit); + } + + static function getInstance($page = 0, $limit = false) { + $instance = new self(); + + if($limit === false) { + $limit = Mobile::config('Navigation.Limit', 2); + } + + $instance->_limit = $limit; + $instance->initStart($page); + return $instance; + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Record.php b/oss/vtiger/trunk/modules/Mobile/core/Record.php new file mode 100644 index 00000000..bb840309 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Record.php @@ -0,0 +1,80 @@ +fields = array(); + + foreach($infomap as $k=>$v) { + if($k == 'id') $this->id = $v; + else $this->fields[$k] = $v; + } + $this->moduleInstance = $moduleInstance; + } + + function lookupBlockFields($blocklabel) { + $fieldblocks = $this->moduleInstance->fieldsGroup(); + if(!empty($fieldblocks)) { + foreach($fieldblocks as $key=>$fieldnames) { + if($key == $blocklabel) { + return $fieldnames; + } + } + } + return false; + } + + function isBlockEmpty($blocklabel, $valuelookup = true) { + $fieldnames = $this->lookupBlockFields($blocklabel); + if(!empty($fieldnames)) { + if($valuelookup) { + foreach($fieldnames as $fieldname) { + $rawvalue = $this->fieldRawValue($fieldname); + if(!empty($rawvalue)) { + return false; + } + } + } + } + return true; + } + + function fieldRawValue($name) { + if(isset($this->fields[$name])) return $this->fields[$name]; + return null; + } + + function fieldValue($name) { + $rawvalue = $this->fieldRawValue($name); + if($this->moduleInstance) return $this->moduleInstance->fieldValue($name, $rawvalue); + return $rawvalue; + } + + function __toString() { + return implode(', ', $this->fields); + } + + static function summary($wsid) { + return vtws_getName($wsid, MobileService::currentUser()); + } + + static function retrieve($wsid, $moduleInstance = false) { + $infomap = vtws_retrieve($wsid, MobileService::currentUser()); + return new self($infomap, $moduleInstance); + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Search.php b/oss/vtiger/trunk/modules/Mobile/core/Search.php new file mode 100644 index 00000000..84175ea1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Search.php @@ -0,0 +1,74 @@ +name}"; + } + + static function retrieve($wsid, $moduleInstance = false) { + return Mobile_Core_Record::retrieve($wsid, $moduleInstance); + } + + static function query($moduleInstance, $input, $fieldnames = false, $paging = false) { + + $entityfields = $moduleInstance->entityFields(); + if(empty($fieldnames)) { + $fieldnames = $moduleInstance->fieldnames(); + } + + $queryString = "SELECT " . implode(',', $entityfields) . " FROM {$moduleInstance->name} "; + $whereCondition = ''; + + foreach($fieldnames as $fieldname) { + if($fieldname == 'id') continue; + + // TODO Skip filename search in documents module. + if($moduleInstance->name == 'Documents' && $fieldname == 'filename') continue; + + $fieldInstance = $moduleInstance->fieldLookup($fieldname); + if($fieldInstance->isReferenceType()) continue; + + + if($whereCondition != '') $whereCondition .= ' OR '; + $whereCondition .= " $fieldname LIKE '%{$input}%' "; + } + + $fullQueryString = "$queryString WHERE $whereCondition"; + + return self::_query($fullQueryString, $paging); + } + + static function entity($moduleInstance, $paging = false) { + $fieldnames = $moduleInstance->entityFields(); + $queryString = "SELECT " . implode(',', $fieldnames) . " FROM {$moduleInstance->name}"; + return self::_query($queryString, $paging); + } + + private static function _query($queryString, $paging = false) { + if($paging !== false) { + $limitClause = " LIMIT {$paging->start()}, {$paging->count()}"; + } + + $queryString .= " $limitClause ;"; + + $qresultRows = vtws_query($queryString, MobileService::currentUser()); + + $resultRows = array(); + foreach($qresultRows as $row) { + $resultRows[] = new Mobile_Core_Record($row, $fieldnames); + } + return $resultRows; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Session.php b/oss/vtiger/trunk/modules/Mobile/core/Session.php new file mode 100644 index 00000000..518571bd --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Session.php @@ -0,0 +1,29 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/core/Skin.php b/oss/vtiger/trunk/modules/Mobile/core/Skin.php new file mode 100644 index 00000000..df4e540c --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/core/Skin.php @@ -0,0 +1,33 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/index.php b/oss/vtiger/trunk/modules/Mobile/index.php new file mode 100644 index 00000000..760434b4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/index.php @@ -0,0 +1,40 @@ + diff --git a/oss/vtiger/trunk/modules/Mobile/language/en_us.lang.php b/oss/vtiger/trunk/modules/Mobile/language/en_us.lang.php new file mode 100644 index 00000000..ad5031df --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/language/en_us.lang.php @@ -0,0 +1,15 @@ + 'Mobile', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/appicon.jpg b/oss/vtiger/trunk/modules/Mobile/resources/images/appicon.jpg new file mode 100644 index 00000000..2646df1a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/appicon.jpg differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_16x16.png new file mode 100644 index 00000000..36180cca Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_24x24.png new file mode 100644 index 00000000..d8729ee1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_32x32.png new file mode 100644 index 00000000..d99e9065 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/add_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_16x16.png new file mode 100644 index 00000000..276d22fe Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_24x24.png new file mode 100644 index 00000000..ba9172ed Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_32x32.png new file mode 100644 index 00000000..cd3b41ed Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/address_book_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_16x16.png new file mode 100644 index 00000000..a3d67e2f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_24x24.png new file mode 100644 index 00000000..49276c39 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_32x32.png new file mode 100644 index 00000000..fd5cb04e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/alert_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_16x16.png new file mode 100644 index 00000000..48fc28ba Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_24x24.png new file mode 100644 index 00000000..23fb325b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_32x32.png new file mode 100644 index 00000000..c2e63d2a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/briefcase_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_16x16.png new file mode 100644 index 00000000..be5793f1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_24x24.png new file mode 100644 index 00000000..42a5644b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_32x32.png new file mode 100644 index 00000000..6f95aa23 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/buildings_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_16x16.png new file mode 100644 index 00000000..1de0315c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_24x24.png new file mode 100644 index 00000000..9ed3f95d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_32x32.png new file mode 100644 index 00000000..6cf50b00 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/calculator_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_16x16.png new file mode 100644 index 00000000..4ba88be0 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_24x24.png new file mode 100644 index 00000000..5ed6bd66 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_32x32.png new file mode 100644 index 00000000..c466358f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/camera_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_16x16.png new file mode 100644 index 00000000..f4f22455 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_24x24.png new file mode 100644 index 00000000..8945459b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_32x32.png new file mode 100644 index 00000000..01ab6ce5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cancel_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_16x16.png new file mode 100644 index 00000000..1302f432 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_24x24.png new file mode 100644 index 00000000..197776a0 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_32x32.png new file mode 100644 index 00000000..88098d98 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/cd_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_16x16.png new file mode 100644 index 00000000..4258f720 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_24x24.png new file mode 100644 index 00000000..fab3b85b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_32x32.png new file mode 100644 index 00000000..d1b60148 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/comment_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_16x16.png new file mode 100644 index 00000000..50941f9d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_24x24.png new file mode 100644 index 00000000..e6bb31e7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_32x32.png new file mode 100644 index 00000000..74ce0029 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/delete_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_16x16.png new file mode 100644 index 00000000..3f4c2b46 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_24x24.png new file mode 100644 index 00000000..c915fd07 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_32x32.png new file mode 100644 index 00000000..12ec52a7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/door_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_16x16.png new file mode 100644 index 00000000..c10021ed Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_24x24.png new file mode 100644 index 00000000..e911e79a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_32x32.png new file mode 100644 index 00000000..fc205f46 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/down_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_16x16.png new file mode 100644 index 00000000..5202bbfe Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_24x24.png new file mode 100644 index 00000000..76559249 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_32x32.png new file mode 100644 index 00000000..cd1386fc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/download_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_16x16.png new file mode 100644 index 00000000..046463d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_24x24.png new file mode 100644 index 00000000..a492e069 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_32x32.png new file mode 100644 index 00000000..ec111b7a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/downloads_folder_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_16x16.png new file mode 100644 index 00000000..88ab8a78 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_24x24.png new file mode 100644 index 00000000..09fca96b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_32x32.png new file mode 100644 index 00000000..13bce47a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/edit_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_16x16.png new file mode 100644 index 00000000..506a7395 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_24x24.png new file mode 100644 index 00000000..5fd44114 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_32x32.png new file mode 100644 index 00000000..efb6673c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/error_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_16x16.png new file mode 100644 index 00000000..d6755b6c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_24x24.png new file mode 100644 index 00000000..5cba82fa Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_32x32.png new file mode 100644 index 00000000..789094bf Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/expand_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_16x16.png new file mode 100644 index 00000000..2ececda3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_24x24.png new file mode 100644 index 00000000..18f9b264 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_32x32.png new file mode 100644 index 00000000..f59c58cc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/file_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_16x16.png new file mode 100644 index 00000000..a429910c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_24x24.png new file mode 100644 index 00000000..b968715d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_32x32.png new file mode 100644 index 00000000..c47d3a13 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/film_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_16x16.png new file mode 100644 index 00000000..76a0ce64 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_24x24.png new file mode 100644 index 00000000..130f5dcf Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_32x32.png new file mode 100644 index 00000000..d09f9bf5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/flag_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_16x16.png new file mode 100644 index 00000000..1b5639f9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_24x24.png new file mode 100644 index 00000000..caee258b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_32x32.png new file mode 100644 index 00000000..11e5e3b8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/folder_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_16x16.png new file mode 100644 index 00000000..06bf2325 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_24x24.png new file mode 100644 index 00000000..79dda505 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_32x32.png new file mode 100644 index 00000000..77ad9b57 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/gear_wheel_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_16x16.png new file mode 100644 index 00000000..1058c100 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_24x24.png new file mode 100644 index 00000000..d96a7dd8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_32x32.png new file mode 100644 index 00000000..3dd02e83 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/globe_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_16x16.png new file mode 100644 index 00000000..2c07cbd1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_24x24.png new file mode 100644 index 00000000..c0eea832 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_32x32.png new file mode 100644 index 00000000..0ee69648 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/hard_disk_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_16x16.png new file mode 100644 index 00000000..743c123a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_24x24.png new file mode 100644 index 00000000..20e3f905 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_32x32.png new file mode 100644 index 00000000..36f12987 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/heart_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_16x16.png new file mode 100644 index 00000000..a7a1e13e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_24x24.png new file mode 100644 index 00000000..60613de7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_32x32.png new file mode 100644 index 00000000..8e004a70 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/help_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_16x16.png new file mode 100644 index 00000000..1cd6c48a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_24x24.png new file mode 100644 index 00000000..6fb54085 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_32x32.png new file mode 100644 index 00000000..1840f9d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/house_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_16x16.png new file mode 100644 index 00000000..c7c5d239 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_24x24.png new file mode 100644 index 00000000..f597d599 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_32x32.png new file mode 100644 index 00000000..e7e12690 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/info_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_16x16.png new file mode 100644 index 00000000..82199cc1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_24x24.png new file mode 100644 index 00000000..301b91c4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_32x32.png new file mode 100644 index 00000000..a7983ea7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/iphone_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_16x16.png new file mode 100644 index 00000000..f130f830 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_24x24.png new file mode 100644 index 00000000..062f6e81 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_32x32.png new file mode 100644 index 00000000..ce543884 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/left_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_16x16.png new file mode 100644 index 00000000..4efb16b7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_24x24.png new file mode 100644 index 00000000..fae7878e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_32x32.png new file mode 100644 index 00000000..fe4d4f40 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lens_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_16x16.png new file mode 100644 index 00000000..a1f1881c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_24x24.png new file mode 100644 index 00000000..b1318c72 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_32x32.png new file mode 100644 index 00000000..f4fbc311 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/line_graph_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_16x16.png new file mode 100644 index 00000000..fb1c925e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_24x24.png new file mode 100644 index 00000000..10fa96cd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_32x32.png new file mode 100644 index 00000000..a3e66a84 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/lock_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_16x16.png new file mode 100644 index 00000000..b5a27344 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_24x24.png new file mode 100644 index 00000000..a968d636 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_32x32.png new file mode 100644 index 00000000..84126723 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/logout_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_16x16.png new file mode 100644 index 00000000..aafca565 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_24x24.png new file mode 100644 index 00000000..5f5072e7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_32x32.png new file mode 100644 index 00000000..1d0efb48 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/magic_wand_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_16x16.png new file mode 100644 index 00000000..3d58fbb6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_24x24.png new file mode 100644 index 00000000..8f042961 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_32x32.png new file mode 100644 index 00000000..c976f306 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/mail_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_16x16.png new file mode 100644 index 00000000..66989454 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_24x24.png new file mode 100644 index 00000000..99eaa974 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_32x32.png new file mode 100644 index 00000000..e85ecee5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/monitor_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_16x16.png new file mode 100644 index 00000000..e4702418 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_24x24.png new file mode 100644 index 00000000..07beee37 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_32x32.png new file mode 100644 index 00000000..19a8ff82 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/move_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_16x16.png new file mode 100644 index 00000000..c6623d86 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_24x24.png new file mode 100644 index 00000000..0f343c76 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_32x32.png new file mode 100644 index 00000000..f40e44e2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/music_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_16x16.png new file mode 100644 index 00000000..7a885afe Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_24x24.png new file mode 100644 index 00000000..bdc65b48 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_32x32.png new file mode 100644 index 00000000..b40dec08 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/network_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_16x16.png new file mode 100644 index 00000000..b205b988 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_24x24.png new file mode 100644 index 00000000..5fcf2d96 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_32x32.png new file mode 100644 index 00000000..3e4e7510 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/no_sound_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_16x16.png new file mode 100644 index 00000000..cb8cc81a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_24x24.png new file mode 100644 index 00000000..c24cfdcc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_32x32.png new file mode 100644 index 00000000..22d2f356 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/picture_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_16x16.png new file mode 100644 index 00000000..5e01d2b5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_24x24.png new file mode 100644 index 00000000..54ff7ec0 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_32x32.png new file mode 100644 index 00000000..b7c7bb4c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/print_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_16x16.png new file mode 100644 index 00000000..52ea1493 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_24x24.png new file mode 100644 index 00000000..2ee07783 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_32x32.png new file mode 100644 index 00000000..4e51d680 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/push_pin_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_16x16.png new file mode 100644 index 00000000..679c8437 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_24x24.png new file mode 100644 index 00000000..29de3bfd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_32x32.png new file mode 100644 index 00000000..a2b516dc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/redo_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_16x16.png new file mode 100644 index 00000000..7a999857 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_24x24.png new file mode 100644 index 00000000..d45b895a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_32x32.png new file mode 100644 index 00000000..53d49beb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/remove_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_16x16.png new file mode 100644 index 00000000..516d24dd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_24x24.png new file mode 100644 index 00000000..dd1cf338 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_32x32.png new file mode 100644 index 00000000..f407531e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/right_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_16x16.png new file mode 100644 index 00000000..dbeec1ae Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_24x24.png new file mode 100644 index 00000000..2f38b03b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_32x32.png new file mode 100644 index 00000000..ceee589f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_add_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_16x16.png new file mode 100644 index 00000000..9d26cc51 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_24x24.png new file mode 100644 index 00000000..bafcff86 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_32x32.png new file mode 100644 index 00000000..98b2b531 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/round_remove_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_16x16.png new file mode 100644 index 00000000..f8bee778 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_24x24.png new file mode 100644 index 00000000..d923b656 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_32x32.png new file mode 100644 index 00000000..e4e8a8a4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/rss_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_16x16.png new file mode 100644 index 00000000..3dd8b6b6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_24x24.png new file mode 100644 index 00000000..3fa2517c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_32x32.png new file mode 100644 index 00000000..2ab8b3ce Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/save_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_16x16.png new file mode 100644 index 00000000..7c32ace8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_24x24.png new file mode 100644 index 00000000..f41ced45 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_32x32.png new file mode 100644 index 00000000..0909b734 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/scissors_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_16x16.png new file mode 100644 index 00000000..5ed4953f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_24x24.png new file mode 100644 index 00000000..f263444b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_32x32.png new file mode 100644 index 00000000..f8832b2f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/script_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_16x16.png new file mode 100644 index 00000000..d9406126 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_24x24.png new file mode 100644 index 00000000..ee79b590 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_32x32.png new file mode 100644 index 00000000..cd6fc12c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/shield_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_16x16.png new file mode 100644 index 00000000..6457c685 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_24x24.png new file mode 100644 index 00000000..50703793 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_32x32.png new file mode 100644 index 00000000..63339d7c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/sound_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_16x16.png new file mode 100644 index 00000000..48ef254a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_24x24.png new file mode 100644 index 00000000..e27e48bd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_32x32.png new file mode 100644 index 00000000..f877c141 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/star_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_16x16.png new file mode 100644 index 00000000..c47bfe56 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_24x24.png new file mode 100644 index 00000000..9bbecfbc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_32x32.png new file mode 100644 index 00000000..080b7ba3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/stop_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_16x16.png new file mode 100644 index 00000000..6f17c742 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_24x24.png new file mode 100644 index 00000000..500800c9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_32x32.png new file mode 100644 index 00000000..74929fa5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tag_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_16x16.png new file mode 100644 index 00000000..a788e912 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_24x24.png new file mode 100644 index 00000000..137e8030 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_32x32.png new file mode 100644 index 00000000..821b1225 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/toolbox_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_16x16.png new file mode 100644 index 00000000..219b55eb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_24x24.png new file mode 100644 index 00000000..f5ed17aa Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_32x32.png new file mode 100644 index 00000000..acfdf1eb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trackback_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_16x16.png new file mode 100644 index 00000000..73ea77e6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_24x24.png new file mode 100644 index 00000000..c169f296 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_32x32.png new file mode 100644 index 00000000..93f19ea4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/trash_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_16x16.png new file mode 100644 index 00000000..cc386eeb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_24x24.png new file mode 100644 index 00000000..0cfea4d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_32x32.png new file mode 100644 index 00000000..72f5572a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/tune_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_16x16.png new file mode 100644 index 00000000..6af7572b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_24x24.png new file mode 100644 index 00000000..01fcfe4a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_32x32.png new file mode 100644 index 00000000..4fb69d83 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/undo_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_16x16.png new file mode 100644 index 00000000..8433c8e4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_24x24.png new file mode 100644 index 00000000..1b01312f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_32x32.png new file mode 100644 index 00000000..3e786f6a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/unlock_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_16x16.png new file mode 100644 index 00000000..90c9717e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_24x24.png new file mode 100644 index 00000000..e63595c5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_32x32.png new file mode 100644 index 00000000..efe27297 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/up_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_16x16.png new file mode 100644 index 00000000..c7484f69 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_24x24.png new file mode 100644 index 00000000..fa985db4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_32x32.png new file mode 100644 index 00000000..5c25f719 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/user_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_16x16.png new file mode 100644 index 00000000..aa1d0e11 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_24x24.png new file mode 100644 index 00000000..ce7efe4d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_32x32.png new file mode 100644 index 00000000..6cb822c4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/warning_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_16x16.png new file mode 100644 index 00000000..98f2aee4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_24x24.png new file mode 100644 index 00000000..0ef8e946 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_32x32.png new file mode 100644 index 00000000..be6bdcf4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/wrench_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_16x16.png new file mode 100644 index 00000000..55e4dec8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_24x24.png new file mode 100644 index 00000000..3174495d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_32x32.png new file mode 100644 index 00000000..c24664fa Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_in_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_16x16.png new file mode 100644 index 00000000..1c7c25e9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_24x24.png new file mode 100644 index 00000000..1b01c871 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_32x32.png new file mode 100644 index 00000000..b8c82932 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/royalblue/zoom_out_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_16x16.png new file mode 100644 index 00000000..83a3020e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_24x24.png new file mode 100644 index 00000000..d3eada1c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_32x32.png new file mode 100644 index 00000000..d53492e2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/add_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_16x16.png new file mode 100644 index 00000000..def0bfbc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_24x24.png new file mode 100644 index 00000000..13feb941 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_32x32.png new file mode 100644 index 00000000..f2e3a8fb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/address_book_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_16x16.png new file mode 100644 index 00000000..cfd731d4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_24x24.png new file mode 100644 index 00000000..07500ad4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_32x32.png new file mode 100644 index 00000000..81434862 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/alert_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_16x16.png new file mode 100644 index 00000000..9d0cfe81 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_24x24.png new file mode 100644 index 00000000..5dc088cc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_32x32.png new file mode 100644 index 00000000..3862da91 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/briefcase_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_16x16.png new file mode 100644 index 00000000..ed63f72d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_24x24.png new file mode 100644 index 00000000..822b31c9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_32x32.png new file mode 100644 index 00000000..ad9178b7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/buildings_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_16x16.png new file mode 100644 index 00000000..22a983e3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_24x24.png new file mode 100644 index 00000000..8ae724c6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_32x32.png new file mode 100644 index 00000000..aa0b77dc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/calculator_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_16x16.png new file mode 100644 index 00000000..0cbb62cb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_24x24.png new file mode 100644 index 00000000..380e8d5d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_32x32.png new file mode 100644 index 00000000..2c7d9e01 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/camera_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_16x16.png new file mode 100644 index 00000000..79da0815 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_24x24.png new file mode 100644 index 00000000..6aa01e41 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_32x32.png new file mode 100644 index 00000000..2a7e82f5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cancel_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_16x16.png new file mode 100644 index 00000000..86e3e20f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_24x24.png new file mode 100644 index 00000000..e15ef465 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_32x32.png new file mode 100644 index 00000000..af220811 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/cd_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_16x16.png new file mode 100644 index 00000000..dc28a08d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_24x24.png new file mode 100644 index 00000000..a3c25915 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_32x32.png new file mode 100644 index 00000000..afb64736 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/comment_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_16x16.png new file mode 100644 index 00000000..37670caa Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_24x24.png new file mode 100644 index 00000000..fc530e8e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_32x32.png new file mode 100644 index 00000000..7e6d5665 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/delete_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_16x16.png new file mode 100644 index 00000000..15726c3f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_24x24.png new file mode 100644 index 00000000..5821ba1b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_32x32.png new file mode 100644 index 00000000..05d0b115 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/door_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_16x16.png new file mode 100644 index 00000000..27f83c92 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_24x24.png new file mode 100644 index 00000000..e273eab7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_32x32.png new file mode 100644 index 00000000..2b6c5c54 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/down_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_16x16.png new file mode 100644 index 00000000..3b7b9158 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_24x24.png new file mode 100644 index 00000000..849bd82a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_32x32.png new file mode 100644 index 00000000..8cb95037 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/download_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_16x16.png new file mode 100644 index 00000000..d0d11f03 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_24x24.png new file mode 100644 index 00000000..18c68845 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_32x32.png new file mode 100644 index 00000000..5cc74afc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/downloads_folder_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_16x16.png new file mode 100644 index 00000000..cb22b815 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_24x24.png new file mode 100644 index 00000000..3ea1818c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_32x32.png new file mode 100644 index 00000000..ae5393c8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/edit_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_16x16.png new file mode 100644 index 00000000..8affbc13 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_24x24.png new file mode 100644 index 00000000..9150b003 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_32x32.png new file mode 100644 index 00000000..3d8fd175 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/error_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_16x16.png new file mode 100644 index 00000000..80634bfe Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_24x24.png new file mode 100644 index 00000000..2686b148 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_32x32.png new file mode 100644 index 00000000..c418e2a8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/expand_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_16x16.png new file mode 100644 index 00000000..109f0b50 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_24x24.png new file mode 100644 index 00000000..99b20fdf Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_32x32.png new file mode 100644 index 00000000..8222a412 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/file_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_16x16.png new file mode 100644 index 00000000..5a358ad9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_24x24.png new file mode 100644 index 00000000..b62537bd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_32x32.png new file mode 100644 index 00000000..d3ba4324 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/film_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_16x16.png new file mode 100644 index 00000000..6da18622 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_24x24.png new file mode 100644 index 00000000..b9d1614f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_32x32.png new file mode 100644 index 00000000..6b2b6722 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/flag_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_16x16.png new file mode 100644 index 00000000..3df5397b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_24x24.png new file mode 100644 index 00000000..60aeffea Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_32x32.png new file mode 100644 index 00000000..ad184f07 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/folder_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_16x16.png new file mode 100644 index 00000000..3bb243ee Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_24x24.png new file mode 100644 index 00000000..8a018f59 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_32x32.png new file mode 100644 index 00000000..71ff0174 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/gear_wheel_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_16x16.png new file mode 100644 index 00000000..22935963 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_24x24.png new file mode 100644 index 00000000..9ba24d27 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_32x32.png new file mode 100644 index 00000000..06b75627 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/globe_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_16x16.png new file mode 100644 index 00000000..2de61e73 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_24x24.png new file mode 100644 index 00000000..064d8a3e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_32x32.png new file mode 100644 index 00000000..0166a050 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/hard_disk_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_16x16.png new file mode 100644 index 00000000..ce360ed1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_24x24.png new file mode 100644 index 00000000..884a73f7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_32x32.png new file mode 100644 index 00000000..eec592d5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/heart_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_16x16.png new file mode 100644 index 00000000..3e0622e4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_24x24.png new file mode 100644 index 00000000..dda8ce21 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_32x32.png new file mode 100644 index 00000000..52ff589b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/help_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_16x16.png new file mode 100644 index 00000000..ab147868 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_24x24.png new file mode 100644 index 00000000..3af24d2e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_32x32.png new file mode 100644 index 00000000..64ca1d22 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/house_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_16x16.png new file mode 100644 index 00000000..35e8ec40 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_24x24.png new file mode 100644 index 00000000..9ca0421b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_32x32.png new file mode 100644 index 00000000..2e62fddc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/info_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_16x16.png new file mode 100644 index 00000000..6896fb93 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_24x24.png new file mode 100644 index 00000000..2bdb1205 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_32x32.png new file mode 100644 index 00000000..14405dec Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/iphone_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_16x16.png new file mode 100644 index 00000000..2263c0ba Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_24x24.png new file mode 100644 index 00000000..91758640 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_32x32.png new file mode 100644 index 00000000..fc826d3d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/left_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_16x16.png new file mode 100644 index 00000000..d6659be3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_24x24.png new file mode 100644 index 00000000..3fb53439 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_32x32.png new file mode 100644 index 00000000..2390d590 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lens_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_16x16.png new file mode 100644 index 00000000..76158bd0 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_24x24.png new file mode 100644 index 00000000..534a2eba Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_32x32.png new file mode 100644 index 00000000..495a3809 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/line_graph_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_16x16.png new file mode 100644 index 00000000..15a6e8a7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_24x24.png new file mode 100644 index 00000000..a6835602 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_32x32.png new file mode 100644 index 00000000..2070d553 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/lock_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_16x16.png new file mode 100644 index 00000000..238c0f31 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_24x24.png new file mode 100644 index 00000000..235cf0c3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_32x32.png new file mode 100644 index 00000000..b0e13857 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/magic_wand_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_16x16.png new file mode 100644 index 00000000..3989617d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_24x24.png new file mode 100644 index 00000000..b6dc2a09 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_32x32.png new file mode 100644 index 00000000..7b37eff9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/mail_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_16x16.png new file mode 100644 index 00000000..8e144e6e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_24x24.png new file mode 100644 index 00000000..d6c0f85f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_32x32.png new file mode 100644 index 00000000..95f31612 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/monitor_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_16x16.png new file mode 100644 index 00000000..ec310dac Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_24x24.png new file mode 100644 index 00000000..3bb01f95 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_32x32.png new file mode 100644 index 00000000..cf9377aa Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/move_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_16x16.png new file mode 100644 index 00000000..7be73d44 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_24x24.png new file mode 100644 index 00000000..ae025d1b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_32x32.png new file mode 100644 index 00000000..2957f23b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/music_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_16x16.png new file mode 100644 index 00000000..4834aae3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_24x24.png new file mode 100644 index 00000000..c2ff016c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_32x32.png new file mode 100644 index 00000000..cb9302d4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/network_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_16x16.png new file mode 100644 index 00000000..a05c6241 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_24x24.png new file mode 100644 index 00000000..01600a96 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_32x32.png new file mode 100644 index 00000000..500ceb60 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/no_sound_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_16x16.png new file mode 100644 index 00000000..6d67fc6c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_24x24.png new file mode 100644 index 00000000..cac60053 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_32x32.png new file mode 100644 index 00000000..b770c086 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/picture_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_16x16.png new file mode 100644 index 00000000..eb40521e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_24x24.png new file mode 100644 index 00000000..8cb5be27 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_32x32.png new file mode 100644 index 00000000..c683fba7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/print_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_16x16.png new file mode 100644 index 00000000..0bca17b7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_24x24.png new file mode 100644 index 00000000..5ba651b3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_32x32.png new file mode 100644 index 00000000..18e494f7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/push_pin_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_16x16.png new file mode 100644 index 00000000..b6b89710 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_24x24.png new file mode 100644 index 00000000..b6857ab3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_32x32.png new file mode 100644 index 00000000..d4a98771 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/redo_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_16x16.png new file mode 100644 index 00000000..f7069837 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_24x24.png new file mode 100644 index 00000000..3329c9c2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_32x32.png new file mode 100644 index 00000000..b8806fde Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/remove_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_16x16.png new file mode 100644 index 00000000..15d0a130 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_24x24.png new file mode 100644 index 00000000..f53486e9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_32x32.png new file mode 100644 index 00000000..2ad3725b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/right_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_16x16.png new file mode 100644 index 00000000..b9585fb1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_24x24.png new file mode 100644 index 00000000..eb76846c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_32x32.png new file mode 100644 index 00000000..b6d51034 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_add_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_16x16.png new file mode 100644 index 00000000..ac001c0d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_24x24.png new file mode 100644 index 00000000..c882c2ec Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_32x32.png new file mode 100644 index 00000000..05285c49 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/round_remove_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_16x16.png new file mode 100644 index 00000000..3e9f4984 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_24x24.png new file mode 100644 index 00000000..38e36024 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_32x32.png new file mode 100644 index 00000000..d1087d57 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/rss_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_16x16.png new file mode 100644 index 00000000..b661ce63 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_24x24.png new file mode 100644 index 00000000..3934b5c5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_32x32.png new file mode 100644 index 00000000..e619e231 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/save_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_16x16.png new file mode 100644 index 00000000..1280ae85 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_24x24.png new file mode 100644 index 00000000..9b9d00eb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_32x32.png new file mode 100644 index 00000000..f8091a28 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/scissors_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_16x16.png new file mode 100644 index 00000000..74d7ee30 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_24x24.png new file mode 100644 index 00000000..f46d5769 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_32x32.png new file mode 100644 index 00000000..fb4ab94b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/script_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_16x16.png new file mode 100644 index 00000000..62a77bd9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_24x24.png new file mode 100644 index 00000000..4765c418 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_32x32.png new file mode 100644 index 00000000..c3f174f1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/shield_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_16x16.png new file mode 100644 index 00000000..67b795c0 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_24x24.png new file mode 100644 index 00000000..c175bef3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_32x32.png new file mode 100644 index 00000000..700794db Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/sound_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_16x16.png new file mode 100644 index 00000000..06f46a26 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_24x24.png new file mode 100644 index 00000000..e6c032b8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_32x32.png new file mode 100644 index 00000000..cd1da402 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/star_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_16x16.png new file mode 100644 index 00000000..e6780b33 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_24x24.png new file mode 100644 index 00000000..ca5b881e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_32x32.png new file mode 100644 index 00000000..0dfd2adb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/stop_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_16x16.png new file mode 100644 index 00000000..1cef10d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_24x24.png new file mode 100644 index 00000000..4e59e303 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_32x32.png new file mode 100644 index 00000000..f984b590 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tag_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_16x16.png new file mode 100644 index 00000000..4c537057 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_24x24.png new file mode 100644 index 00000000..4e2a6f92 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_32x32.png new file mode 100644 index 00000000..54646b69 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/toolbox_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_16x16.png new file mode 100644 index 00000000..15bf23a8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_24x24.png new file mode 100644 index 00000000..21c72057 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_32x32.png new file mode 100644 index 00000000..fd916c2e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trackback_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_16x16.png new file mode 100644 index 00000000..63ee95fd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_24x24.png new file mode 100644 index 00000000..ab757426 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_32x32.png new file mode 100644 index 00000000..b02082b6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/trash_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_16x16.png new file mode 100644 index 00000000..1ac2d16b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_24x24.png new file mode 100644 index 00000000..9e590d73 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_32x32.png new file mode 100644 index 00000000..50866e21 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/tune_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_16x16.png new file mode 100644 index 00000000..24e91370 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_24x24.png new file mode 100644 index 00000000..e2bbcabf Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_32x32.png new file mode 100644 index 00000000..617b8760 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/undo_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_16x16.png new file mode 100644 index 00000000..7df69c0d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_24x24.png new file mode 100644 index 00000000..eb230391 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_32x32.png new file mode 100644 index 00000000..defc8b46 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/unlock_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_16x16.png new file mode 100644 index 00000000..aec1d61a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_24x24.png new file mode 100644 index 00000000..ee7b7fa0 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_32x32.png new file mode 100644 index 00000000..a1380c60 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/up_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_16x16.png new file mode 100644 index 00000000..aebe21fb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_24x24.png new file mode 100644 index 00000000..c6c6e37d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_32x32.png new file mode 100644 index 00000000..70be31f1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/user_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_16x16.png new file mode 100644 index 00000000..3438ad27 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_24x24.png new file mode 100644 index 00000000..c88e1e4f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_32x32.png new file mode 100644 index 00000000..6103442a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/warning_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_16x16.png new file mode 100644 index 00000000..8616bac6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_24x24.png new file mode 100644 index 00000000..2539f31b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_32x32.png new file mode 100644 index 00000000..29fa82b5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/wrench_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_16x16.png new file mode 100644 index 00000000..8632b0c5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_24x24.png new file mode 100644 index 00000000..c14a1846 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_32x32.png new file mode 100644 index 00000000..9e640d42 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_in_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_16x16.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_16x16.png new file mode 100644 index 00000000..da49d013 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_16x16.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_24x24.png new file mode 100644 index 00000000..b5c3bafc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_32x32.png new file mode 100644 index 00000000..ee6aefaf Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/white/zoom_out_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/add_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/add_24x24.png new file mode 100644 index 00000000..eef02d96 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/add_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/add_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/add_32x32.png new file mode 100644 index 00000000..e85a26ed Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/add_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/address_book_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/address_book_24x24.png new file mode 100644 index 00000000..390a8112 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/address_book_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/address_book_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/address_book_32x32.png new file mode 100644 index 00000000..901ced56 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/address_book_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/alert_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/alert_24x24.png new file mode 100644 index 00000000..35635899 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/alert_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/alert_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/alert_32x32.png new file mode 100644 index 00000000..06d84a23 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/alert_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/briefcase_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/briefcase_24x24.png new file mode 100644 index 00000000..0365ad04 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/briefcase_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/briefcase_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/briefcase_32x32.png new file mode 100644 index 00000000..d298bc54 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/briefcase_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/buildings_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/buildings_24x24.png new file mode 100644 index 00000000..1cefa0e8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/buildings_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/buildings_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/buildings_32x32.png new file mode 100644 index 00000000..fb481042 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/buildings_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/calculator_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/calculator_24x24.png new file mode 100644 index 00000000..e1fdb219 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/calculator_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/calculator_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/calculator_32x32.png new file mode 100644 index 00000000..f0c64f36 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/calculator_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/camera_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/camera_24x24.png new file mode 100644 index 00000000..be81d3d4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/camera_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/camera_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/camera_32x32.png new file mode 100644 index 00000000..389f59f1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/camera_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cancel_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cancel_24x24.png new file mode 100644 index 00000000..533562b8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cancel_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cancel_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cancel_32x32.png new file mode 100644 index 00000000..970959c8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cancel_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cd_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cd_24x24.png new file mode 100644 index 00000000..d1e818d6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cd_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cd_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cd_32x32.png new file mode 100644 index 00000000..06da49a7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/cd_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/comment_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/comment_24x24.png new file mode 100644 index 00000000..f5635e8b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/comment_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/comment_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/comment_32x32.png new file mode 100644 index 00000000..33d1393d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/comment_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/delete_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/delete_24x24.png new file mode 100644 index 00000000..a3c04354 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/delete_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/delete_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/delete_32x32.png new file mode 100644 index 00000000..b8720da5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/delete_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/door_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/door_24x24.png new file mode 100644 index 00000000..55126401 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/door_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/door_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/door_32x32.png new file mode 100644 index 00000000..3785efae Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/door_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/down_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/down_arrow_24x24.png new file mode 100644 index 00000000..632f37f4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/down_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/down_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/down_arrow_32x32.png new file mode 100644 index 00000000..bf1e7be1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/down_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/download_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/download_24x24.png new file mode 100644 index 00000000..8f7a61d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/download_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/download_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/download_32x32.png new file mode 100644 index 00000000..5ff1c2ba Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/download_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/downloads_folder_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/downloads_folder_24x24.png new file mode 100644 index 00000000..7247c889 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/downloads_folder_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/downloads_folder_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/downloads_folder_32x32.png new file mode 100644 index 00000000..444a1994 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/downloads_folder_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/edit_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/edit_24x24.png new file mode 100644 index 00000000..20023a1f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/edit_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/edit_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/edit_32x32.png new file mode 100644 index 00000000..86486ecd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/edit_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/error_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/error_24x24.png new file mode 100644 index 00000000..c9592289 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/error_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/error_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/error_32x32.png new file mode 100644 index 00000000..57bc53ce Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/error_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/expand_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/expand_24x24.png new file mode 100644 index 00000000..06dd62a8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/expand_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/expand_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/expand_32x32.png new file mode 100644 index 00000000..515e4ff4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/expand_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/file_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/file_24x24.png new file mode 100644 index 00000000..93034573 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/file_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/file_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/file_32x32.png new file mode 100644 index 00000000..043cb47f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/file_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/film_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/film_24x24.png new file mode 100644 index 00000000..fbc9f6b2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/film_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/film_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/film_32x32.png new file mode 100644 index 00000000..5ddb207e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/film_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/flag_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/flag_24x24.png new file mode 100644 index 00000000..ccb50f6d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/flag_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/flag_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/flag_32x32.png new file mode 100644 index 00000000..b279f0c2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/flag_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/folder_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/folder_24x24.png new file mode 100644 index 00000000..3cb407df Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/folder_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/folder_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/folder_32x32.png new file mode 100644 index 00000000..dfe129a8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/folder_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/gear_wheel_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/gear_wheel_24x24.png new file mode 100644 index 00000000..7e7f6f66 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/gear_wheel_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/gear_wheel_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/gear_wheel_32x32.png new file mode 100644 index 00000000..4e65663b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/gear_wheel_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/globe_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/globe_24x24.png new file mode 100644 index 00000000..2f36be98 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/globe_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/globe_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/globe_32x32.png new file mode 100644 index 00000000..a0dc1260 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/globe_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/hard_disk_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/hard_disk_24x24.png new file mode 100644 index 00000000..ebe2ff43 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/hard_disk_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/hard_disk_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/hard_disk_32x32.png new file mode 100644 index 00000000..5b5cadbb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/hard_disk_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/heart_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/heart_24x24.png new file mode 100644 index 00000000..16e96cf4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/heart_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/heart_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/heart_32x32.png new file mode 100644 index 00000000..fe7cedf6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/heart_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/help_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/help_24x24.png new file mode 100644 index 00000000..4759baf4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/help_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/help_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/help_32x32.png new file mode 100644 index 00000000..4651888c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/help_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/house_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/house_24x24.png new file mode 100644 index 00000000..a21f076a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/house_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/house_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/house_32x32.png new file mode 100644 index 00000000..5fe380c4 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/house_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/info_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/info_24x24.png new file mode 100644 index 00000000..ff96127f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/info_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/info_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/info_32x32.png new file mode 100644 index 00000000..72835211 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/info_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/iphone_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/iphone_24x24.png new file mode 100644 index 00000000..e765eeba Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/iphone_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/iphone_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/iphone_32x32.png new file mode 100644 index 00000000..5751d891 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/iphone_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/left_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/left_arrow_24x24.png new file mode 100644 index 00000000..89af104d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/left_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/left_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/left_arrow_32x32.png new file mode 100644 index 00000000..66077273 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/left_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lens_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lens_24x24.png new file mode 100644 index 00000000..b8bf9b2d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lens_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lens_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lens_32x32.png new file mode 100644 index 00000000..4e526938 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lens_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/line_graph_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/line_graph_24x24.png new file mode 100644 index 00000000..62a87c1d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/line_graph_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/line_graph_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/line_graph_32x32.png new file mode 100644 index 00000000..ccdc9bc5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/line_graph_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lock_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lock_24x24.png new file mode 100644 index 00000000..0dab2b8b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lock_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lock_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lock_32x32.png new file mode 100644 index 00000000..2d08a753 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/lock_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/logout_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/logout_24x24.png new file mode 100644 index 00000000..be20f1c5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/logout_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/logout_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/logout_32x32.png new file mode 100644 index 00000000..0c04c654 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/logout_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/magic_wand_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/magic_wand_24x24.png new file mode 100644 index 00000000..d33b544a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/magic_wand_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/magic_wand_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/magic_wand_32x32.png new file mode 100644 index 00000000..3d44fe3f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/magic_wand_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/mail_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/mail_24x24.png new file mode 100644 index 00000000..42189d42 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/mail_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/mail_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/mail_32x32.png new file mode 100644 index 00000000..807ca2d1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/mail_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/monitor_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/monitor_24x24.png new file mode 100644 index 00000000..e0cd1a3d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/monitor_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/monitor_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/monitor_32x32.png new file mode 100644 index 00000000..198887dc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/monitor_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/move_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/move_24x24.png new file mode 100644 index 00000000..debc7f0f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/move_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/move_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/move_32x32.png new file mode 100644 index 00000000..f052f000 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/move_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/music_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/music_24x24.png new file mode 100644 index 00000000..9be7aa41 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/music_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/music_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/music_32x32.png new file mode 100644 index 00000000..dee4de95 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/music_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/network_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/network_24x24.png new file mode 100644 index 00000000..3a2ed245 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/network_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/network_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/network_32x32.png new file mode 100644 index 00000000..6907ba89 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/network_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/no_sound_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/no_sound_24x24.png new file mode 100644 index 00000000..999d71f1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/no_sound_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/no_sound_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/no_sound_32x32.png new file mode 100644 index 00000000..9217fe05 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/no_sound_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/picture_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/picture_24x24.png new file mode 100644 index 00000000..fe9267b3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/picture_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/picture_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/picture_32x32.png new file mode 100644 index 00000000..3e21f51e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/picture_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/print_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/print_24x24.png new file mode 100644 index 00000000..1a2e589d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/print_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/print_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/print_32x32.png new file mode 100644 index 00000000..7ec5befb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/print_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/push_pin_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/push_pin_24x24.png new file mode 100644 index 00000000..350bc434 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/push_pin_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/push_pin_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/push_pin_32x32.png new file mode 100644 index 00000000..a70adae2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/push_pin_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/redo_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/redo_24x24.png new file mode 100644 index 00000000..5ec1087a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/redo_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/redo_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/redo_32x32.png new file mode 100644 index 00000000..ab6a8053 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/redo_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/remove_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/remove_24x24.png new file mode 100644 index 00000000..3f953825 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/remove_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/remove_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/remove_32x32.png new file mode 100644 index 00000000..b0b6ad7f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/remove_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/right_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/right_arrow_24x24.png new file mode 100644 index 00000000..7dcba609 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/right_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/right_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/right_arrow_32x32.png new file mode 100644 index 00000000..bb011844 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/right_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_add_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_add_24x24.png new file mode 100644 index 00000000..206c5895 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_add_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_add_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_add_32x32.png new file mode 100644 index 00000000..bf3a7bb8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_add_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_remove_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_remove_24x24.png new file mode 100644 index 00000000..e2573a95 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_remove_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_remove_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_remove_32x32.png new file mode 100644 index 00000000..465ecf64 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/round_remove_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/rss_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/rss_24x24.png new file mode 100644 index 00000000..86606a36 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/rss_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/rss_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/rss_32x32.png new file mode 100644 index 00000000..e1219214 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/rss_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/save_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/save_24x24.png new file mode 100644 index 00000000..cee3aeef Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/save_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/save_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/save_32x32.png new file mode 100644 index 00000000..77d8ca58 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/save_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/scissors_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/scissors_24x24.png new file mode 100644 index 00000000..12e067b1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/scissors_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/scissors_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/scissors_32x32.png new file mode 100644 index 00000000..4cf9393a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/scissors_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/script_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/script_24x24.png new file mode 100644 index 00000000..1cfb80e6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/script_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/script_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/script_32x32.png new file mode 100644 index 00000000..cd530ee6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/script_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/shield_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/shield_24x24.png new file mode 100644 index 00000000..119c4e89 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/shield_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/shield_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/shield_32x32.png new file mode 100644 index 00000000..bdb6fcf5 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/shield_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/sound_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/sound_24x24.png new file mode 100644 index 00000000..e8b5fae8 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/sound_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/sound_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/sound_32x32.png new file mode 100644 index 00000000..97a614d9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/sound_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/star_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/star_24x24.png new file mode 100644 index 00000000..4fcc138a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/star_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/star_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/star_32x32.png new file mode 100644 index 00000000..1ae1c2d7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/star_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/stop_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/stop_24x24.png new file mode 100644 index 00000000..ca630fdc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/stop_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/stop_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/stop_32x32.png new file mode 100644 index 00000000..09847dec Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/stop_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tag_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tag_24x24.png new file mode 100644 index 00000000..79769a4f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tag_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tag_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tag_32x32.png new file mode 100644 index 00000000..53064fc1 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tag_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/toolbox_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/toolbox_24x24.png new file mode 100644 index 00000000..dc2a1e1a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/toolbox_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/toolbox_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/toolbox_32x32.png new file mode 100644 index 00000000..17d3bb9d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/toolbox_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trackback_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trackback_24x24.png new file mode 100644 index 00000000..2e500a5f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trackback_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trackback_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trackback_32x32.png new file mode 100644 index 00000000..bb10f57a Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trackback_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trash_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trash_24x24.png new file mode 100644 index 00000000..73595a59 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trash_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trash_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trash_32x32.png new file mode 100644 index 00000000..ee37bb04 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/trash_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tune_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tune_24x24.png new file mode 100644 index 00000000..f6b19846 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tune_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tune_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tune_32x32.png new file mode 100644 index 00000000..7b2f2f8e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/tune_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/undo_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/undo_24x24.png new file mode 100644 index 00000000..8760c8ab Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/undo_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/undo_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/undo_32x32.png new file mode 100644 index 00000000..befba25b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/undo_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/unlock_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/unlock_24x24.png new file mode 100644 index 00000000..a62422f6 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/unlock_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/unlock_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/unlock_32x32.png new file mode 100644 index 00000000..defbf7fb Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/unlock_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/up_arrow_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/up_arrow_24x24.png new file mode 100644 index 00000000..379b3232 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/up_arrow_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/up_arrow_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/up_arrow_32x32.png new file mode 100644 index 00000000..7ecce281 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/up_arrow_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/user_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/user_24x24.png new file mode 100644 index 00000000..d4e5cf1e Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/user_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/user_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/user_32x32.png new file mode 100644 index 00000000..3be9912c Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/user_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/warning_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/warning_24x24.png new file mode 100644 index 00000000..29a4f85f Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/warning_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/warning_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/warning_32x32.png new file mode 100644 index 00000000..05d5bca9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/warning_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/wrench_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/wrench_24x24.png new file mode 100644 index 00000000..4d51f4b2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/wrench_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/wrench_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/wrench_32x32.png new file mode 100644 index 00000000..c19546c7 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/wrench_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_in_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_in_24x24.png new file mode 100644 index 00000000..718d4ee3 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_in_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_in_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_in_32x32.png new file mode 100644 index 00000000..940adc11 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_in_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_out_24x24.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_out_24x24.png new file mode 100644 index 00000000..40ed87dc Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_out_24x24.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_out_32x32.png b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_out_32x32.png new file mode 100644 index 00000000..f188ebf2 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/images/iconza/yellow/zoom_out_32x32.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/backButton.png b/oss/vtiger/trunk/modules/Mobile/resources/iui/backButton.png new file mode 100644 index 00000000..e27ea8cd Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/iui/backButton.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/blueButton.png b/oss/vtiger/trunk/modules/Mobile/resources/iui/blueButton.png new file mode 100644 index 00000000..0f92dfd9 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/iui/blueButton.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/blue_hd_bg.png b/oss/vtiger/trunk/modules/Mobile/resources/iui/blue_hd_bg.png new file mode 100644 index 00000000..2ce8a24b Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/iui/blue_hd_bg.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/cancel.png b/oss/vtiger/trunk/modules/Mobile/resources/iui/cancel.png new file mode 100644 index 00000000..5f6dcc87 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/iui/cancel.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/grayButton.png b/oss/vtiger/trunk/modules/Mobile/resources/iui/grayButton.png new file mode 100644 index 00000000..0ce6a30d Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/iui/grayButton.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iui-logo-touch-icon.png b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui-logo-touch-icon.png new file mode 100644 index 00000000..8817b302 Binary files /dev/null and b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui-logo-touch-icon.png differ diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.css b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.css new file mode 100644 index 00000000..187c94d0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.css @@ -0,0 +1,406 @@ +/* iui.css (c) 2007-9 by iUI Project Members, see LICENSE.txt for license */ +body { + margin: 0; + font-family: Helvetica; + background: #FFFFFF; + color: #000000; + overflow-x: hidden; + -webkit-user-select: none; + -webkit-text-size-adjust: none; +} + +body > *:not(.toolbar) { + display: none; + position: absolute; + margin: 0; + padding: 0; + left: 0; + top: 45px; + width: 100%; + min-height: 372px; +} + +body[orient="landscape"] > *:not(.toolbar) { + min-height: 268px; +} + +body > *[selected="true"] { + display: block; +} + +a[selected], a:active { + background-color: #194fdb !important; + background-image: url(listArrowSel.png), url(selection.png) !important; + background-repeat: no-repeat, repeat-x; + background-position: right center, left top; + color: #FFFFFF !important; +} + +a[selected="progress"] { + background-image: url(loading.gif), url(selection.png) !important; +} + +/************************************************************************************************/ + +body > .toolbar { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + border-bottom: 1px solid #2d3642; + border-top: 1px solid #6d84a2; + padding: 10px; + height: 45px; + background: url(toolbar.png) #6d84a2 repeat-x; +} + +.toolbar > h1 { + position: absolute; + overflow: hidden; + left: 50%; + margin: 1px 0 0 -75px; + height: 45px; + font-size: 20px; + width: 150px; + font-weight: bold; + text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; + text-align: center; + text-overflow: ellipsis; + white-space: nowrap; + color: #FFFFFF; +} + +body[orient="landscape"] > .toolbar > h1 { + margin-left: -125px; + width: 250px; +} + +.button { + position: absolute; + overflow: hidden; + top: 8px; + right: 6px; + margin: 0; + border-width: 0 5px; + padding: 0 3px; + width: auto; + height: 30px; + line-height: 30px; + font-family: inherit; + font-size: 12px; + font-weight: bold; + color: #FFFFFF; + text-shadow: rgba(0, 0, 0, 0.6) 0px -1px 0; + text-overflow: ellipsis; + text-decoration: none; + white-space: nowrap; + background: none; + -moz-border-image: url(toolButton.png) 0 5 0 5; + -webkit-border-image: url(toolButton.png) 0 5 0 5; +} + +.blueButton { + -moz-border-image: url(blueButton.png) 0 5 0 5; + -webkit-border-image: url(blueButton.png) 0 5 0 5; + border-width: 0 5px; +} + +.leftButton { + left: 6px; + right: auto; +} + +#backButton { + display: none; + left: 6px; + right: auto; + padding: 0; + max-width: 55px; + border-width: 0 8px 0 14px; + -moz-border-image: url(backButton.png) 0 8 0 14; + -webkit-border-image: url(backButton.png) 0 8 0 14; +} + +.whiteButton, +.grayButton { + display: block; + border-width: 0 12px; + padding: 10px; + text-align: center; + font-size: 20px; + font-weight: bold; + text-decoration: inherit; + color: inherit; +} + +.whiteButton { + -moz-border-image: url(whiteButton.png) 0 12 0 12; + -webkit-border-image: url(whiteButton.png) 0 12 0 12; + text-shadow: rgba(255, 255, 255, 0.7) 0 1px 0; +} + +.grayButton { + -moz-border-image: url(grayButton.png) 0 12 0 12; + -webkit-border-image: url(grayButton.png) 0 12 0 12; + color: #FFFFFF; +} + +/************************************************************************************************/ + +body > ul > li { + position: relative; + margin: 0; + border-bottom: 1px solid #E0E0E0; + padding: 8px 0 8px 10px; + font-size: 20px; + font-weight: bold; + list-style: none; +} + +body > ul > li.group { + position: relative; + top: -1px; + margin-bottom: -2px; + border-top: 1px solid #7d7d7d; + border-bottom: 1px solid #999999; + padding: 1px 10px; + background: url(listGroup.png) repeat-x; + font-size: 17px; + font-weight: bold; + text-shadow: rgba(0, 0, 0, 0.4) 0 1px 0; + color: #FFFFFF; +} + +body > ul > li.group:first-child { + top: 0; + border-top: none; +} + +body > ul > li > a { + display: block; + margin: -8px 0 -8px -10px; + padding: 8px 32px 8px 10px; + text-decoration: none; + color: inherit; + background: url(listArrow.png) no-repeat right center; +} + +a[target="_replace"] { + box-sizing: border-box; + -webkit-box-sizing: border-box; + padding-top: 25px; + padding-bottom: 25px; + font-size: 18px; + color: cornflowerblue; + background-color: #FFFFFF; + background-image: none; +} + +/************************************************************************************************/ + +body > .dialog { + top: 0; + width: 100%; + min-height: 417px; + z-index: 2; + background: rgba(0, 0, 0, 0.8); + padding: 0; + text-align: right; +} + +.dialog > fieldset { + box-sizing: border-box; + -webkit-box-sizing: border-box; + width: 100%; + margin: 0; + border: none; + border-top: 1px solid #6d84a2; + padding: 10px 6px; + background: url(toolbar.png) #7388a5 repeat-x; +} + +.dialog > fieldset > h1 { + margin: 0 10px 0 10px; + padding: 0; + font-size: 20px; + font-weight: bold; + color: #FFFFFF; + text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; + text-align: center; +} + +.dialog > fieldset > label { + position: absolute; + margin: 16px 0 0 6px; + font-size: 14px; + color: #999999; +} + +input:not(input[type|=radio]):not(input[type|=checkbox]) { + box-sizing: border-box; + -webkit-box-sizing: border-box; + width: 100%; + margin: 8px 0 0 0; + padding: 6px 6px 6px 44px; + font-size: 16px; + font-weight: normal; +} + +/************************************************************************************************/ + +body > .panel { + box-sizing: border-box; + -webkit-box-sizing: border-box; + padding: 10px; + background: #c8c8c8 url(pinstripes.png); +} + +.panel > fieldset { + position: relative; + margin: 0 0 20px 0; + padding: 0; + background: #FFFFFF; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border: 1px solid #999999; + text-align: right; + font-size: 16px; +} + +.row { + position: relative; + min-height: 42px; + border-bottom: 1px solid #999999; + -moz-border-radius: 0; + -webkit-border-radius: 0; + text-align: right; +} + +fieldset > .row:last-child { + border-bottom: none !important; +} + +.row > input:not(input[type|=radio]):not(input[type|=checkbox]) { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + margin: 0; + border: none; + padding: 12px 10px 0 110px; + height: 42px; + background: none; +} +.row > input[type|=radio], .row > input[type|=checkbox] { + margin: 7px 7px 0 0; + height: 25px; + width: 25px; +} + +.row > label { + position: absolute; + margin: 0 0 0 14px; + line-height: 42px; + font-weight: bold; +} + +.row > span { + position: absolute; + padding: 12px 10px 0 110px; + margin: 0; +} + +.row > .toggle { + position: absolute; + top: 6px; + right: 6px; + width: 100px; + height: 28px; +} + +.toggle { + border: 1px solid #888888; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + background: #FFFFFF url(toggle.png) repeat-x; + font-size: 19px; + font-weight: bold; + line-height: 30px; +} + +.toggle[toggled="true"] { + border: 1px solid #143fae; + background: #194fdb url(toggleOn.png) repeat-x; +} + +.toggleOn { + display: none; + position: absolute; + width: 60px; + text-align: center; + left: 0; + top: 0; + color: #FFFFFF; + text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; +} + +.toggleOff { + position: absolute; + width: 60px; + text-align: center; + right: 0; + top: 0; + color: #666666; +} + +.toggle[toggled="true"] > .toggleOn { + display: block; +} + +.toggle[toggled="true"] > .toggleOff { + display: none; +} + +.thumb { + position: absolute; + top: -1px; + left: -1px; + width: 40px; + height: 28px; + border: 1px solid #888888; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + background: #ffffff url(thumb.png) repeat-x; +} + +.toggle[toggled="true"] > .thumb { + left: auto; + right: -1px; +} + +.panel > h2 { + margin: 0 0 8px 14px; + font-size: inherit; + font-weight: bold; + color: #4d4d70; + text-shadow: rgba(255, 255, 255, 0.75) 2px 2px 0; +} + +/************************************************************************************************/ + +#preloader { + display: none; + background-image: url(loading.gif), url(selection.png), + url(blueButton.png), url(listArrowSel.png), url(listGroup.png); +} + +/************************************************************************************************/ +/* table extension from http://www.k10design.net/articles/iui/ (dependent image blue_hd_bg.png) */ + +.itable { border: 1px solid gray; } +.itable tr.header th { text-align: left; } +.itable tr.alt { background-color: #eff7ff; } +.itable tr.reg { background-color: #fff; } +.itable th { background: url(blue_hd_bg.png) top left repeat-x; border-right: 1px solid grey; } +.itable th:last-child { border-right: none; } +.itable td { border-right: 1px solid gray; } +.itable tr:first-child { white-space: nowrap; } +.itable tr:last-child { border-right: none; } diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.js b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.js new file mode 100644 index 00000000..38d76611 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.js @@ -0,0 +1,701 @@ +/* + Copyright (c) 2007, iUI Project Members + See LICENSE.txt for licensing terms + */ + + +(function() { + +var slideSpeed = 20; +var slideInterval = 0; + +var currentPage = null; +var currentDialog = null; +var currentWidth = 0; +var currentHash = location.hash; +var hashPrefix = "#_"; +var pageHistory = []; +var newPageCount = 0; +var checkTimer; +var hasOrientationEvent = false; +var portraitVal = "portrait"; +var landscapeVal = "landscape"; + +// CWZ +var loadedPages = []; +var actionButtons = []; + +// ************************************************************************************************* + +window.iui = +{ + showPage: function(page, backwards) + { + if (page) + { + if (currentDialog) + { + currentDialog.removeAttribute("selected"); + currentDialog = null; + } + + if (hasClass(page, "dialog")) + showDialog(page); + else + { + var fromPage = currentPage; + currentPage = page; + + if (fromPage) + { + if (fromPage.onblur) + fromPage.onblur(); + + if (fromPage.getAttribute("onunload") && backwards) + eval(fromPage.getAttribute("onunload")); + + setTimeout(slidePages, 0, fromPage, page, backwards); + } + else + updatePage(page, fromPage); + + var lNewPage = (loadedPages.indexOf(page.id) == -1); + + if (lNewPage) + { + loadedPages.push(page.id); + + if (page.getAttribute("stylesheet")) + loadStylesheet(page.getAttribute("stylesheet")); + + if (page.getAttribute("script")) + loadScript(page.getAttribute("script"), function() { continueLoadingPage(page, lNewPage); }); + else + continueLoadingPage(page, lNewPage); + } + else + continueLoadingPage(page, lNewPage); + } + } + }, + + showPageById: function(pageId) + { + var page = $(pageId); + if (page) + { + var index = pageHistory.indexOf(pageId); + var backwards = index != -1; + if (backwards) + pageHistory.splice(index, pageHistory.length); + + iui.showPage(page, backwards); + } + }, + + showPageByHref: function(href, args, method, replace, cb) + { + var req = new XMLHttpRequest(); + req.onerror = function() + { + if (cb) + cb(false); + }; + + req.onreadystatechange = function() + { + if (req.readyState == 4) + { + if (replace) + replaceElementWithSource(replace, req.responseText); + else + { + var frag = document.createElement("div"); + frag.innerHTML = req.responseText; + iui.insertPages(frag.childNodes); + } + if (cb) + setTimeout(cb, 1000, true); + } + }; + + if (args) + { + req.open("POST", href, true); // CWZ 02/11/2009 + //req.open(method || "GET", href, true); + req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + req.setRequestHeader("Content-Length", args.length); + req.send(args.join("&")); + } + else + { + req.open(method || "GET", href, true); + req.send(null); + } + }, + + insertPages: function(nodes) + { + var targetPage; + for (var i = 0; i < nodes.length; ++i) + { + var child = nodes[i]; + if (child.nodeType == 1) + { + if (!child.id) + child.id = "__" + (++newPageCount) + "__"; + + var clone = $(child.id); + if (clone) + clone.parentNode.replaceChild(child, clone); + else + document.body.appendChild(child); + + if (child.getAttribute("selected") == "true" || !targetPage) + targetPage = child; + + --i; + } + } + + if (targetPage) + iui.showPage(targetPage); + }, + + getSelectedPage: function() + { + for (var child = document.body.firstChild; child; child = child.nextSibling) + { + if (child.nodeType == 1 && child.getAttribute("selected") == "true") + return child; + } + }, + isNativeUrl: function(href) + { + for(var i = 0; i < iui.nativeUrlPatterns.length; i++) + { + if(href.match(iui.nativeUrlPatterns[i])) return true; + } + return false; + }, + nativeUrlPatterns: [ + new RegExp("^http:\/\/maps.google.com\/maps\?"), + new RegExp("^mailto:"), + new RegExp("^tel:"), + new RegExp("^http:\/\/www.youtube.com\/watch\\?v="), + new RegExp("^http:\/\/www.youtube.com\/v\/") + ] +}; + +// ************************************************************************************************* + +addEventListener("submit", function(event) +{ + if (hasClass(findParent(event.target, "form"), "dialog") || hasClass(findParent(event.target, "form"), "panel")) + { + submitForm(findParent(event.target, "form")); + event.preventDefault(); + } +}, true); + +addEventListener("load", function(event) +{ + var page = iui.getSelectedPage(); + if (page) + iui.showPage(page); + + setTimeout(preloadImages, 0); + setTimeout(checkOrientAndLocation, 0); + checkTimer = setInterval(checkOrientAndLocation, 300); +}, false); + +addEventListener("unload", function(event) +{ + return; +}, false); + +addEventListener("click", function(event) +{ + var link = findParent(event.target, "a"); + if (link) + { + /* Prasad: Perform load and cache the DOM for re-use unless asked no-to-cache */ + function custom_load() { + if(!hasClass(link, "nocache")) { + link.setAttribute("xhref", link.href); + link.setAttribute("href", "#__" + (newPageCount) + "__"); + } + unselect(); + } + /* END */ + + function unselect() { link.removeAttribute("selected"); } + + if (link.href && link.hash && link.hash != "#") + { + link.setAttribute("selected", "true"); + iui.showPage($(link.hash.substr(1))); + setTimeout(unselect, 500); + } + else if (link == $("backButton")) + history.back(); + else if (link.getAttribute("type") == "submit") + submitForm(findParent(link, "form")); + else if (link.getAttribute("type") == "cancel") + cancelDialog(findParent(link, "form")); + else if (link.target == "_replace") + { + link.setAttribute("selected", "progress"); + iui.showPageByHref(link.href, null, null, link, custom_load); // Prasad: unselect); + } + else if (iui.isNativeUrl(link.href)) + { + return; + } + else if (!link.target) + { + link.setAttribute("selected", "progress"); + iui.showPageByHref(link.href, null, null, null, custom_load); // Prasad: unselect); + } + else + return; + + event.preventDefault(); + } +}, true); + +addEventListener("click", function(event) +{ + var div = findParent(event.target, "div"); + if (div && hasClass(div, "toggle")) + { + div.setAttribute("toggled", div.getAttribute("toggled") != "true"); + event.preventDefault(); + } +}, true); + +function orientChangeHandler() +{ + var orientation=window.orientation; + switch(orientation) + { + case 0: + setOrientation(portraitVal); + break; + + case 90: + case -90: + setOrientation(landscapeVal); + break; + } +} + +if (typeof window.onorientationchange == "object") +{ + window.onorientationchange=orientChangeHandler; + hasOrientationEvent = true; + setTimeout(orientChangeHandler, 0); +} + +function checkOrientAndLocation() +{ + if (!hasOrientationEvent) + { + if (window.innerWidth != currentWidth) + { + currentWidth = window.innerWidth; + var orient = currentWidth == 320 ? portraitVal : landscapeVal; + setOrientation(orient); + } + } + + if (location.hash != currentHash) + { + var pageId = location.hash.substr(hashPrefix.length); + iui.showPageById(pageId); + } +} + +function setOrientation(orient) +{ + document.body.setAttribute("orient", orient); + setTimeout(scrollTo, 100, 0, 1); +} + +function showDialog(page) +{ + currentDialog = page; + page.setAttribute("selected", "true"); + + if (hasClass(page, "dialog") && !page.target) + showForm(page); +} + +function showForm(form) +{ + form.onsubmit = function(event) + { + event.preventDefault(); + submitForm(form); + }; + + form.onclick = function(event) + { + if (event.target == form && hasClass(form, "dialog")) + cancelDialog(form); + }; +} + +function cancelDialog(form) +{ + form.removeAttribute("selected"); +} + +function updatePage(page, fromPage) +{ + if (!page.id) + page.id = "__" + (++newPageCount) + "__"; + + location.href = currentHash = hashPrefix + page.id; + pageHistory.push(page.id); + + var pageTitle = $("pageTitle"); + if (page.title) + pageTitle.innerHTML = page.title; + + if (page.localName.toLowerCase() == "form" && !page.target) + showForm(page); + + var backButton = $("backButton"); + if (backButton) + { + var prevPage = $(pageHistory[pageHistory.length-2]); + if (prevPage && !page.getAttribute("hideBackButton")) + { + backButton.style.display = "inline"; + backButton.innerHTML = prevPage.title ? prevPage.title : "Back"; + } + else + backButton.style.display = "none"; + } +} + +function slidePagesNew(fromPage, toPage, backwards) +{ + try + { + var page = (backwards ? fromPage : toPage); + var axis = page.getAttribute("axis"); + + if (axis == "y") + page.style.top = "100%"; + else + { + if (backwards) + { + fromPage.style.left = "0%"; + toPage.style.left = "-100%"; + } + else + { + fromPage.style.left = "0%"; + toPage.style.left = "100%"; + } + } + + var transitionProperty = (axis == "y") ? 'top' : 'left'; + var transitionDuration = 300; + + toPage.style.webkitTransitionDuration = transitionDuration + "ms"; + fromPage.style.webkitTransitionDuration = transitionDuration + "ms"; + + toPage.setAttribute("selected", "true"); + scrollTo(0, 1); + + clearInterval(checkTimer); + + fromPage.style.webkitTransitionProperty = transitionProperty; + fromPage.style.transitionTimingFunction = "ease-in"; + + toPage.style.webkitTransitionProperty = transitionProperty; + toPage.style.transitionTimingFunction = "ease-in"; + + if (backwards) + { + fromPage.style.left="100%"; + toPage.style.left="0%"; + } + else + { + fromPage.style.left="-100%"; + toPage.style.left="0%"; + } + + // Call completion function sometime after we think we'll be done + setTimeout(slideComplete, transitionDuration); + + function slideComplete() + { + if (!hasClass(toPage, "dialog")) + fromPage.removeAttribute("selected"); + + toPage.style.webkitTransitionDuration = "0s"; + fromPage.style.webkitTransitionDuration = "0s"; + + checkTimer = setInterval(checkOrientAndLocation,300); + setTimeout(updatePage, 0, toPage, fromPage); + } + } + catch (ex) { alert(ex); } +} + +function slidePages(fromPage, toPage, backwards) +{ + var axis = (backwards ? fromPage : toPage).getAttribute("axis"); + if (axis == "y") + (backwards ? fromPage : toPage).style.top = "100%"; + else + toPage.style.left = "100%"; + + toPage.setAttribute("selected", "true"); + scrollTo(0, 1); + clearInterval(checkTimer); + + var percent = 100; + slide(); + var timer = setInterval(slide, slideInterval); + + function slide() + { + percent -= slideSpeed; + if (percent <= 0) + { + percent = 0; + if (!hasClass(toPage, "dialog")) + fromPage.removeAttribute("selected"); + clearInterval(timer); + checkTimer = setInterval(checkOrientAndLocation, 300); + setTimeout(updatePage, 0, toPage, fromPage); + } + + if (axis == "y") + { + backwards + ? fromPage.style.top = (100-percent) + "%" + : toPage.style.top = percent + "%"; + } + else + { + fromPage.style.left = (backwards ? (100-percent) : (percent-100)) + "%"; + toPage.style.left = (backwards ? -percent : percent) + "%"; + } + } +} + +function preloadImages() +{ + var preloader = document.createElement("div"); + preloader.id = "preloader"; + document.body.appendChild(preloader); +} + +function submitForm(form) +{ + // CWZ + if (form.getAttribute("target") == "_self") + form.submit(); + else + iui.showPageByHref(form.action, encodeForm(form), form.method || "POST"); +} + +function encodeForm(form) +{ + function encode(inputs) + { + for (var i = 0; i < inputs.length; ++i) + { + if (inputs[i].name) + { + if ((inputs[i].getAttribute("type") == "checkbox" && !inputs[i].checked) + || (inputs[i].getAttribute("type") == "radio" && !inputs[i].checked) + || (inputs[i].getAttribute("type") == "submit") + || (inputs[i].name && inputs[i].disabled)) + { + continue; + } + else + args.push(inputs[i].name + "=" + escape(inputs[i].value)); + } + } + } + + var args = []; + encode(form.getElementsByTagName("input")); + encode(form.getElementsByTagName("textarea")); // added in 0.20 + encode(form.getElementsByTagName("select")); + return args; +} + +function findParent(node, localName) +{ + while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName)) + node = node.parentNode; + return node; +} + +function hasClass(self, name) +{ + var re = new RegExp("(^|\\s)"+name+"($|\\s)"); + return re.exec(self.getAttribute("class")) != null; +} + +function replaceElementWithSource(replace, source) +{ + var page = replace.parentNode; + var parent = replace; + while (page.parentNode != document.body) + { + page = page.parentNode; + parent = parent.parentNode; + } + + var frag = document.createElement(parent.localName); + frag.innerHTML = source; + + page.removeChild(parent); + + while (frag.firstChild) + page.appendChild(frag.firstChild); +} + +function $(id) { return document.getElementById(id); } +function ddd() { console.log.apply(console, arguments); } + +// CWZ 04/24/2009 +function loadActionButton(page) +{ + try + { + var btn = $("actionButton"); + var lSet = false; + + if (!actionButtons[page.id]) + { + actionButtons[page.id] = { "title" : "", "href" : null, "target" : null, "visible" : true }; + + if (page.getAttribute("actionbutton")) + { + var oButton = eval("("+page.getAttribute("actionbutton")+")"); + + if (oButton) + { + if (oButton.title ) actionButtons[page.id].title = oButton.title; + if (oButton.href ) actionButtons[page.id].href = oButton.href; + if (oButton.target ) actionButtons[page.id].target = oButton.target; + } + + if (!btn) + { + var oToolbar = document.getElementsByClassName("toolbar")[0]; + btn = document.createElement("A"); + btn.id="actionButton"; + btn.className="button"; + + oToolbar.appendChild(btn); + } + } + else if (!btn) // stores the fact that the page has no button + { + lSet = true; + actionButtons[page.id].visible = false; + } + else + { + lSet = true; + actionButtons[page.id].title = btn.innerHTML; + actionButtons[page.id].href = btn.href; + actionButtons[page.id].target = btn.target; + } + } + + if (!lSet) + { + btn.style.visibility = (actionButtons[page.id].visible ? "visible" : "hidden"); + + if (actionButtons[page.id].title != null) btn.innerHTML = actionButtons[page.id].title; + if (actionButtons[page.id].href != null) btn.href = actionButtons[page.id].href; + if (actionButtons[page.id].target != null) btn.target = actionButtons[page.id].target; + } + } + catch (ex) { console.log(ex); } +} + +// CWZ 04/27/2009 +function continueLoadingPage(page, lNewPage) +{ + if (lNewPage && page.getAttribute("onload")) + eval(page.getAttribute("onload")); + + loadActionButton(page); + + if (page.onfocus) + page.onfocus(); +} + +// CWZ adapted from http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml +// and http://stackoverflow.com/questions/756382/bookmarklet-wait-until-javascript-is-loaded/756436 +function loadScript(cFilename, callback) +{ + var script = document.createElement("script"); + + script.setAttribute("type","text/javascript"); + script.setAttribute("src", cFilename); + + var done = false; + script.onload = script.onreadystatechange = function() + { + if( !done && ( !this.readyState + || this.readyState == "loaded" + || this.readyState == "complete") ) + { + done = true; + + callback(); + } + }; + + document.getElementsByTagName("head")[0].appendChild(script); + + return script; +} + +function loadStylesheet(cFilename, callback) +{ + var stylesheet = document.createElement("link"); + + stylesheet.setAttribute("rel", "stylesheet"); + stylesheet.setAttribute("type", "text/css"); + stylesheet.setAttribute("href", cFilename); + + if (callback) + { + var done = false; + stylesheet.onload = stylesheet.onreadystatechange = function() + { + if( !done && ( !this.readyState + || this.readyState == "loaded" + || this.readyState == "complete") ) + { + done = true; + + callback(); + } + }; + } + + document.getElementsByTagName("head")[0].appendChild(stylesheet); +} + + +})(); + diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.original.css b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.original.css new file mode 100644 index 00000000..159398b7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.original.css @@ -0,0 +1,386 @@ +/* iui.css (c) 2007-9 by iUI Project Members, see LICENSE.txt for license */ +body { + margin: 0; + font-family: Helvetica; + background: #FFFFFF; + color: #000000; + overflow-x: hidden; + -webkit-user-select: none; + -webkit-text-size-adjust: none; +} + +body > *:not(.toolbar) { + display: none; + position: absolute; + margin: 0; + padding: 0; + left: 0; + top: 45px; + width: 100%; + min-height: 372px; +} + +body[orient="landscape"] > *:not(.toolbar) { + min-height: 268px; +} + +body > *[selected="true"] { + display: block; +} + +a[selected], a:active { + background-color: #194fdb !important; + background-image: url(listArrowSel.png), url(selection.png) !important; + background-repeat: no-repeat, repeat-x; + background-position: right center, left top; + color: #FFFFFF !important; +} + +a[selected="progress"] { + background-image: url(loading.gif), url(selection.png) !important; +} + +/************************************************************************************************/ + +body > .toolbar { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + border-bottom: 1px solid #2d3642; + border-top: 1px solid #6d84a2; + padding: 10px; + height: 45px; + background: url(toolbar.png) #6d84a2 repeat-x; +} + +.toolbar > h1 { + position: absolute; + overflow: hidden; + left: 50%; + margin: 1px 0 0 -75px; + height: 45px; + font-size: 20px; + width: 150px; + font-weight: bold; + text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; + text-align: center; + text-overflow: ellipsis; + white-space: nowrap; + color: #FFFFFF; +} + +body[orient="landscape"] > .toolbar > h1 { + margin-left: -125px; + width: 250px; +} + +.button { + position: absolute; + overflow: hidden; + top: 8px; + right: 6px; + margin: 0; + border-width: 0 5px; + padding: 0 3px; + width: auto; + height: 30px; + line-height: 30px; + font-family: inherit; + font-size: 12px; + font-weight: bold; + color: #FFFFFF; + text-shadow: rgba(0, 0, 0, 0.6) 0px -1px 0; + text-overflow: ellipsis; + text-decoration: none; + white-space: nowrap; + background: none; + -webkit-border-image: url(toolButton.png) 0 5 0 5; +} + +.blueButton { + -webkit-border-image: url(blueButton.png) 0 5 0 5; + border-width: 0 5px; +} + +.leftButton { + left: 6px; + right: auto; +} + +#backButton { + display: none; + left: 6px; + right: auto; + padding: 0; + max-width: 55px; + border-width: 0 8px 0 14px; + -webkit-border-image: url(backButton.png) 0 8 0 14; +} + +.whiteButton, +.grayButton { + display: block; + border-width: 0 12px; + padding: 10px; + text-align: center; + font-size: 20px; + font-weight: bold; + text-decoration: inherit; + color: inherit; +} + +.whiteButton { + -webkit-border-image: url(whiteButton.png) 0 12 0 12; + text-shadow: rgba(255, 255, 255, 0.7) 0 1px 0; +} + +.grayButton { + -webkit-border-image: url(grayButton.png) 0 12 0 12; + color: #FFFFFF; +} + +/************************************************************************************************/ + +body > ul > li { + position: relative; + margin: 0; + border-bottom: 1px solid #E0E0E0; + padding: 8px 0 8px 10px; + font-size: 20px; + font-weight: bold; + list-style: none; +} + +body > ul > li.group { + position: relative; + top: -1px; + margin-bottom: -2px; + border-top: 1px solid #7d7d7d; + border-bottom: 1px solid #999999; + padding: 1px 10px; + background: url(listGroup.png) repeat-x; + font-size: 17px; + font-weight: bold; + text-shadow: rgba(0, 0, 0, 0.4) 0 1px 0; + color: #FFFFFF; +} + +body > ul > li.group:first-child { + top: 0; + border-top: none; +} + +body > ul > li > a { + display: block; + margin: -8px 0 -8px -10px; + padding: 8px 32px 8px 10px; + text-decoration: none; + color: inherit; + background: url(listArrow.png) no-repeat right center; +} + +a[target="_replace"] { + box-sizing: border-box; + -webkit-box-sizing: border-box; + padding-top: 25px; + padding-bottom: 25px; + font-size: 18px; + color: cornflowerblue; + background-color: #FFFFFF; + background-image: none; +} + +/************************************************************************************************/ + +body > .dialog { + top: 0; + width: 100%; + min-height: 417px; + z-index: 2; + background: rgba(0, 0, 0, 0.8); + padding: 0; + text-align: right; +} + +.dialog > fieldset { + box-sizing: border-box; + -webkit-box-sizing: border-box; + width: 100%; + margin: 0; + border: none; + border-top: 1px solid #6d84a2; + padding: 10px 6px; + background: url(toolbar.png) #7388a5 repeat-x; +} + +.dialog > fieldset > h1 { + margin: 0 10px 0 10px; + padding: 0; + font-size: 20px; + font-weight: bold; + color: #FFFFFF; + text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; + text-align: center; +} + +.dialog > fieldset > label { + position: absolute; + margin: 16px 0 0 6px; + font-size: 14px; + color: #999999; +} + +input:not(input[type|=radio]):not(input[type|=checkbox]) { + box-sizing: border-box; + -webkit-box-sizing: border-box; + width: 100%; + margin: 8px 0 0 0; + padding: 6px 6px 6px 44px; + font-size: 16px; + font-weight: normal; +} + +/************************************************************************************************/ + +body > .panel { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + padding: 10px; + background: #c8c8c8 url(pinstripes.png); +} + +.panel > fieldset { + position: relative; + margin: 0 0 20px 0; + padding: 0; + background: #FFFFFF; + -webkit-border-radius: 10px; + -moz-border-radius: 10px; + border: 1px solid #999999; + text-align: right; + font-size: 16px; +} + +.row { + position: relative; + min-height: 42px; + border-bottom: 1px solid #999999; + -webkit-border-radius: 0; + text-align: right; +} + +fieldset > .row:last-child { + border-bottom: none !important; +} + +.row > input:not(input[type|=radio]):not(input[type|=checkbox]) { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + margin: 0; + border: none; + padding: 12px 10px 0 110px; + height: 42px; + background: none; +} +.row > input[type|=radio], .row > input[type|=checkbox] { + margin: 7px 7px 0 0; + height: 25px; + width: 25px; +} + +.row > label { + position: absolute; + margin: 0 0 0 14px; + line-height: 42px; + font-weight: bold; +} + +.row > span { + position: absolute; + padding: 12px 10px 0 110px; + margin: 0; +} + +.row > .toggle { + position: absolute; + top: 6px; + right: 6px; + width: 100px; + height: 28px; +} + +.toggle { + border: 1px solid #888888; + -webkit-border-radius: 6px; + background: #FFFFFF url(toggle.png) repeat-x; + font-size: 19px; + font-weight: bold; + line-height: 30px; +} + +.toggle[toggled="true"] { + border: 1px solid #143fae; + background: #194fdb url(toggleOn.png) repeat-x; +} + +.toggleOn { + display: none; + position: absolute; + width: 60px; + text-align: center; + left: 0; + top: 0; + color: #FFFFFF; + text-shadow: rgba(0, 0, 0, 0.4) 0px -1px 0; +} + +.toggleOff { + position: absolute; + width: 60px; + text-align: center; + right: 0; + top: 0; + color: #666666; +} + +.toggle[toggled="true"] > .toggleOn { + display: block; +} + +.toggle[toggled="true"] > .toggleOff { + display: none; +} + +.thumb { + position: absolute; + top: -1px; + left: -1px; + width: 40px; + height: 28px; + border: 1px solid #888888; + -webkit-border-radius: 6px; + background: #ffffff url(thumb.png) repeat-x; +} + +.toggle[toggled="true"] > .thumb { + left: auto; + right: -1px; +} + +.panel > h2 { + margin: 0 0 8px 14px; + font-size: inherit; + font-weight: bold; + color: #4d4d70; + text-shadow: rgba(255, 255, 255, 0.75) 2px 2px 0; +} + +/************************************************************************************************/ + +#preloader { + display: none; + background-image: url(loading.gif), url(selection.png), + url(blueButton.png), url(listArrowSel.png), url(listGroup.png); +} \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.original.js b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.original.js new file mode 100644 index 00000000..b7a7c7c6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/resources/iui/iui.original.js @@ -0,0 +1,444 @@ +/* + Copyright (c) 2007-9, iUI Project Members + See LICENSE.txt for licensing terms + */ + + +(function() { + +var slideSpeed = 20; +var slideInterval = 0; + +var currentPage = null; +var currentDialog = null; +var currentWidth = 0; +var currentHash = location.hash; +var hashPrefix = "#_"; +var pageHistory = []; +var newPageCount = 0; +var checkTimer; +var hasOrientationEvent = false; +var portraitVal = "portrait"; +var landscapeVal = "landscape"; + +// ************************************************************************************************* + +window.iui = +{ + showPage: function(page, backwards) + { + if (page) + { + if (currentDialog) + { + currentDialog.removeAttribute("selected"); + currentDialog = null; + } + + if (hasClass(page, "dialog")) + showDialog(page); + else + { + var fromPage = currentPage; + currentPage = page; + + if (fromPage) + setTimeout(slidePages, 0, fromPage, page, backwards); + else + updatePage(page, fromPage); + } + } + }, + + showPageById: function(pageId) + { + var page = $(pageId); + if (page) + { + var index = pageHistory.indexOf(pageId); + var backwards = index != -1; + if (backwards) + pageHistory.splice(index, pageHistory.length); + + iui.showPage(page, backwards); + } + }, + + showPageByHref: function(href, args, method, replace, cb) + { + var req = new XMLHttpRequest(); + req.onerror = function() + { + if (cb) + cb(false); + }; + + req.onreadystatechange = function() + { + if (req.readyState == 4) + { + if (replace) + replaceElementWithSource(replace, req.responseText); + else + { + var frag = document.createElement("div"); + frag.innerHTML = req.responseText; + iui.insertPages(frag.childNodes); + } + if (cb) + setTimeout(cb, 1000, true); + } + }; + + if (args) + { + req.open(method || "GET", href, true); + req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + req.setRequestHeader("Content-Length", args.length); + req.send(args.join("&")); + } + else + { + req.open(method || "GET", href, true); + req.send(null); + } + }, + + insertPages: function(nodes) + { + var targetPage; + for (var i = 0; i < nodes.length; ++i) + { + var child = nodes[i]; + if (child.nodeType == 1) + { + if (!child.id) + child.id = "__" + (++newPageCount) + "__"; + + var clone = $(child.id); + if (clone) + clone.parentNode.replaceChild(child, clone); + else + document.body.appendChild(child); + + if (child.getAttribute("selected") == "true" || !targetPage) + targetPage = child; + + --i; + } + } + + if (targetPage) + iui.showPage(targetPage); + }, + + getSelectedPage: function() + { + for (var child = document.body.firstChild; child; child = child.nextSibling) + { + if (child.nodeType == 1 && child.getAttribute("selected") == "true") + return child; + } + }, + isNativeUrl: function(href) + { + for(var i = 0; i < iui.nativeUrlPatterns.length; i++) + { + if(href.match(iui.nativeUrlPatterns[i])) return true; + } + return false; + }, + nativeUrlPatterns: [ + new RegExp("^http:\/\/maps.google.com\/maps\?"), + new RegExp("^mailto:"), + new RegExp("^tel:"), + new RegExp("^http:\/\/www.youtube.com\/watch\\?v="), + new RegExp("^http:\/\/www.youtube.com\/v\/") + ] +}; + +// ************************************************************************************************* + +addEventListener("load", function(event) +{ + var page = iui.getSelectedPage(); + if (page) + iui.showPage(page); + + setTimeout(preloadImages, 0); + setTimeout(checkOrientAndLocation, 0); + checkTimer = setInterval(checkOrientAndLocation, 300); +}, false); + +addEventListener("unload", function(event) +{ + return; +}, false); + +addEventListener("click", function(event) +{ + var link = findParent(event.target, "a"); + if (link) + { + function unselect() { link.removeAttribute("selected"); } + + if (link.href && link.hash && link.hash != "#") + { + link.setAttribute("selected", "true"); + iui.showPage($(link.hash.substr(1))); + setTimeout(unselect, 500); + } + else if (link == $("backButton")) + history.back(); + else if (link.getAttribute("type") == "submit") + submitForm(findParent(link, "form")); + else if (link.getAttribute("type") == "cancel") + cancelDialog(findParent(link, "form")); + else if (link.target == "_replace") + { + link.setAttribute("selected", "progress"); + iui.showPageByHref(link.href, null, null, link, unselect); + } + else if (iui.isNativeUrl(link.href)) + { + return; + } + else if (!link.target) + { + link.setAttribute("selected", "progress"); + iui.showPageByHref(link.href, null, null, null, unselect); + } + else + return; + + event.preventDefault(); + } +}, true); + +addEventListener("click", function(event) +{ + var div = findParent(event.target, "div"); + if (div && hasClass(div, "toggle")) + { + div.setAttribute("toggled", div.getAttribute("toggled") != "true"); + event.preventDefault(); + } +}, true); + +function orientChangeHandler() +{ + var orientation=window.orientation; + switch(orientation) + { + case 0: + setOrientation(portraitVal); + break; + + case 90: + case -90: + setOrientation(landscapeVal); + break; + } +} + +if (typeof window.onorientationchange == "object") +{ + window.onorientationchange=orientChangeHandler; + hasOrientationEvent = true; + setTimeout(orientChangeHandler, 0); +} + +function checkOrientAndLocation() +{ + if (!hasOrientationEvent) + { + if (window.innerWidth != currentWidth) + { + currentWidth = window.innerWidth; + var orient = currentWidth == 320 ? portraitVal : landscapeVal; + setOrientation(orient); + } + } + + if (location.hash != currentHash) + { + var pageId = location.hash.substr(hashPrefix.length); + iui.showPageById(pageId); + } +} + +function setOrientation(orient) +{ + document.body.setAttribute("orient", orient); + setTimeout(scrollTo, 100, 0, 1); +} + +function showDialog(page) +{ + currentDialog = page; + page.setAttribute("selected", "true"); + + if (hasClass(page, "dialog") && !page.target) + showForm(page); +} + +function showForm(form) +{ + form.onsubmit = function(event) + { + event.preventDefault(); + submitForm(form); + }; + + form.onclick = function(event) + { + if (event.target == form && hasClass(form, "dialog")) + cancelDialog(form); + }; +} + +function cancelDialog(form) +{ + form.removeAttribute("selected"); +} + +function updatePage(page, fromPage) +{ + if (!page.id) + page.id = "__" + (++newPageCount) + "__"; + + location.href = currentHash = hashPrefix + page.id; + pageHistory.push(page.id); + + var pageTitle = $("pageTitle"); + if (page.title) + pageTitle.innerHTML = page.title; + + if (page.localName.toLowerCase() == "form" && !page.target) + showForm(page); + + var backButton = $("backButton"); + if (backButton) + { + var prevPage = $(pageHistory[pageHistory.length-2]); + if (prevPage && !page.getAttribute("hideBackButton")) + { + backButton.style.display = "inline"; + backButton.innerHTML = prevPage.title ? prevPage.title : "Back"; + } + else + backButton.style.display = "none"; + } +} + +function slidePages(fromPage, toPage, backwards) +{ + var axis = (backwards ? fromPage : toPage).getAttribute("axis"); + if (axis == "y") + (backwards ? fromPage : toPage).style.top = "100%"; + else + toPage.style.left = "100%"; + + toPage.setAttribute("selected", "true"); + scrollTo(0, 1); + clearInterval(checkTimer); + + var percent = 100; + slide(); + var timer = setInterval(slide, slideInterval); + + function slide() + { + percent -= slideSpeed; + if (percent <= 0) + { + percent = 0; + if (!hasClass(toPage, "dialog")) + fromPage.removeAttribute("selected"); + clearInterval(timer); + checkTimer = setInterval(checkOrientAndLocation, 300); + setTimeout(updatePage, 0, toPage, fromPage); + } + + if (axis == "y") + { + backwards + ? fromPage.style.top = (100-percent) + "%" + : toPage.style.top = percent + "%"; + } + else + { + fromPage.style.left = (backwards ? (100-percent) : (percent-100)) + "%"; + toPage.style.left = (backwards ? -percent : percent) + "%"; + } + } +} + +function preloadImages() +{ + var preloader = document.createElement("div"); + preloader.id = "preloader"; + document.body.appendChild(preloader); +} + + +function submitForm(form) +{ + iui.showPageByHref(form.action || "POST", encodeForm(form), form.method); +} + + +function encodeForm(form) +{ + function encode(inputs) + { + for (var i = 0; i < inputs.length; ++i) + { + if (inputs[i].name) + args.push(inputs[i].name + "=" + escape(inputs[i].value)); + } + } + + var args = []; + encode(form.getElementsByTagName("input")); + encode(form.getElementsByTagName("textarea")); + encode(form.getElementsByTagName("select")); + return args; +} + +function findParent(node, localName) +{ + while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName)) + node = node.parentNode; + return node; +} + +function hasClass(self, name) +{ + var re = new RegExp("(^|\\s)"+name+"($|\\s)"); + return re.exec(self.getAttribute("class")) != null; +} + +function replaceElementWithSource(replace, source) +{ + var page = replace.parentNode; + var parent = replace; + while (page.parentNode != document.body) + { + page = page.parentNode; + parent = parent.parentNode; + } + + var frag = document.createElement(parent.localName); + frag.innerHTML = source; + + page.removeChild(parent); + + while (frag.firstChild) + page.appendChild(frag.firstChild); +} + +function $(id) { return document.getElementById(id); } +function ddd() { console.log.apply(console, arguments); } + +})(); diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iuix.css b/oss/vtiger/trunk/modules/Mobile/resources/iui/iuix.css new file mode 100644 index 00000000..67eead37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/resources/iui/iuix.css @@ -0,0 +1 @@ +body{margin:0;font-family:Helvetica;background:#FFF;color:#000;overflow-x:hidden;-webkit-user-select:none;-webkit-text-size-adjust:none;}body>*:not(.toolbar){display:none;position:absolute;margin:0;padding:0;left:0;top:45px;width:100%;min-height:372px;}body[orient="landscape"]>*:not(.toolbar){min-height:268px;}body>*[selected="true"]{display:block;}a[selected],a:active{background-color:#194fdb!important;background-image:url(listArrowSel.png),url(selection.png)!important;background-repeat:no-repeat,repeat-x;background-position:right center,left top;color:#FFF!important;}a[selected="progress"]{background-image:url(loading.gif),url(selection.png)!important;}body>.toolbar{box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;border-bottom:1px solid #2d3642;border-top:1px solid #6d84a2;padding:10px;height:45px;background:url(toolbar.png) #6d84a2 repeat-x;}.toolbar>h1{position:absolute;overflow:hidden;left:50%;margin:1px 0 0 -75px;height:45px;font-size:20px;width:150px;font-weight:bold;text-shadow:rgba(0,0,0,0.4) 0 -1px 0;text-align:center;text-overflow:ellipsis;white-space:nowrap;color:#FFF;}body[orient="landscape"]>.toolbar>h1{margin-left:-125px;width:250px;}.button{position:absolute;overflow:hidden;top:8px;right:6px;margin:0;border-width:0 5px;padding:0 3px;width:auto;height:30px;line-height:30px;font-family:inherit;font-size:12px;font-weight:bold;color:#FFF;text-shadow:rgba(0,0,0,0.6) 0 -1px 0;text-overflow:ellipsis;text-decoration:none;white-space:nowrap;background:none;-webkit-border-image:url(toolButton.png) 0 5 0 5;}.blueButton{-webkit-border-image:url(blueButton.png) 0 5 0 5;border-width:0 5px;}.leftButton{left:6px;right:auto;}#backButton{display:none;left:6px;right:auto;padding:0;max-width:55px;border-width:0 8px 0 14px;-webkit-border-image:url(backButton.png) 0 8 0 14;}.whiteButton,.grayButton{display:block;border-width:0 12px;padding:10px;text-align:center;font-size:20px;font-weight:bold;text-decoration:inherit;color:inherit;}.whiteButton{-webkit-border-image:url(whiteButton.png) 0 12 0 12;text-shadow:rgba(255,255,255,0.7) 0 1px 0;}.grayButton{-webkit-border-image:url(grayButton.png) 0 12 0 12;color:#FFF;}body>ul>li{position:relative;margin:0;border-bottom:1px solid #E0E0E0;padding:8px 0 8px 10px;font-size:20px;font-weight:bold;list-style:none;}body>ul>li.group{position:relative;top:-1px;margin-bottom:-2px;border-top:1px solid #7d7d7d;border-bottom:1px solid #999;padding:1px 10px;background:url(listGroup.png) repeat-x;font-size:17px;font-weight:bold;text-shadow:rgba(0,0,0,0.4) 0 1px 0;color:#FFF;}body>ul>li.group:first-child{top:0;border-top:none;}body>ul>li>a{display:block;margin:-8px 0 -8px -10px;padding:8px 32px 8px 10px;text-decoration:none;color:inherit;background:url(listArrow.png) no-repeat right center;}a[target="_replace"]{box-sizing:border-box;-webkit-box-sizing:border-box;padding-top:25px;padding-bottom:25px;font-size:18px;color:cornflowerblue;background-color:#FFF;background-image:none;}body>.dialog{top:0;width:100%;min-height:417px;z-index:2;background:rgba(0,0,0,0.8);padding:0;text-align:right;}.dialog>fieldset{box-sizing:border-box;-webkit-box-sizing:border-box;width:100%;margin:0;border:none;border-top:1px solid #6d84a2;padding:10px 6px;background:url(toolbar.png) #7388a5 repeat-x;}.dialog>fieldset>h1{margin:0 10px 0 10px;padding:0;font-size:20px;font-weight:bold;color:#FFF;text-shadow:rgba(0,0,0,0.4) 0 -1px 0;text-align:center;}.dialog>fieldset>label{position:absolute;margin:16px 0 0 6px;font-size:14px;color:#999;}input:not(input[type|=radio]):not(input[type|=checkbox]){box-sizing:border-box;-webkit-box-sizing:border-box;width:100%;margin:8px 0 0 0;padding:6px 6px 6px 44px;font-size:16px;font-weight:normal;}body>.panel{box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:10px;background:#c8c8c8 url(pinstripes.png);}.panel>fieldset{position:relative;margin:0 0 20px 0;padding:0;background:#FFF;-webkit-border-radius:10px;-moz-border-radius:10px;border:1px solid #999;text-align:right;font-size:16px;}.row{position:relative;min-height:42px;border-bottom:1px solid #999;-webkit-border-radius:0;text-align:right;}fieldset>.row:last-child{border-bottom:none!important;}.row>input:not(input[type|=radio]):not(input[type|=checkbox]){box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;margin:0;border:none;padding:12px 10px 0 110px;height:42px;background:none;}.row>input[type|=radio],.row>input[type|=checkbox]{margin:7px 7px 0 0;height:25px;width:25px;}.row>label{position:absolute;margin:0 0 0 14px;line-height:42px;font-weight:bold;}.row>span{position:absolute;padding:12px 10px 0 110px;margin:0;}.row>.toggle{position:absolute;top:6px;right:6px;width:100px;height:28px;}.toggle{border:1px solid #888;-webkit-border-radius:6px;background:#FFF url(toggle.png) repeat-x;font-size:19px;font-weight:bold;line-height:30px;}.toggle[toggled="true"]{border:1px solid #143fae;background:#194fdb url(toggleOn.png) repeat-x;}.toggleOn{display:none;position:absolute;width:60px;text-align:center;left:0;top:0;color:#FFF;text-shadow:rgba(0,0,0,0.4) 0 -1px 0;}.toggleOff{position:absolute;width:60px;text-align:center;right:0;top:0;color:#666;}.toggle[toggled="true"]>.toggleOn{display:block;}.toggle[toggled="true"]>.toggleOff{display:none;}.thumb{position:absolute;top:-1px;left:-1px;width:40px;height:28px;border:1px solid #888;-webkit-border-radius:6px;background:#fff url(thumb.png) repeat-x;}.toggle[toggled="true"]>.thumb{left:auto;right:-1px;}.panel>h2{margin:0 0 8px 14px;font-size:inherit;font-weight:bold;color:#4d4d70;text-shadow:rgba(255,255,255,0.75) 2px 2px 0;}#preloader{display:none;background-image:url(loading.gif),url(selection.png),url(blueButton.png),url(listArrowSel.png),url(listGroup.png);} \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Mobile/resources/iui/iuix.js b/oss/vtiger/trunk/modules/Mobile/resources/iui/iuix.js new file mode 100644 index 00000000..68e1cba1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Mobile/resources/iui/iuix.js @@ -0,0 +1 @@ +(function(){var _1=20;var _2=0;var _3=null;var _4=null;var _5=0;var _6=location.hash;var _7="#_";var _8=[];var _9=0;var _a;var _b=false;var _c="portrait";var _d="landscape";window.iui={showPage:function(_e,_f){if(_e){if(_4){_4.removeAttribute("selected");_4=null;}if(hasClass(_e,"dialog")){showDialog(_e);}else{var _10=_3;_3=_e;if(_10){setTimeout(slidePages,0,_10,_e,_f);}else{updatePage(_e,_10);}}}},showPageById:function(_11){var _12=$(_11);if(_12){var _13=_8.indexOf(_11);var _14=_13!=-1;if(_14){_8.splice(_13,_8.length);}iui.showPage(_12,_14);}},showPageByHref:function(_15,_16,_17,_18,cb){var req=new XMLHttpRequest();req.onerror=function(){if(cb){cb(false);}};req.onreadystatechange=function(){if(req.readyState==4){if(_18){replaceElementWithSource(_18,req.responseText);}else{var _1b=document.createElement("div");_1b.innerHTML=req.responseText;iui.insertPages(_1b.childNodes);}if(cb){setTimeout(cb,1000,true);}}};if(_16){req.open(_17||"GET",_15,true);req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");req.setRequestHeader("Content-Length",_16.length);req.send(_16.join("&"));}else{req.open(_17||"GET",_15,true);req.send(null);}},insertPages:function(_1c){var _1d;for(var i=0;i<_1c.length;++i){var _1f=_1c[i];if(_1f.nodeType==1){if(!_1f.id){_1f.id="__"+(++_9)+"__";}var _20=$(_1f.id);if(_20){_20.parentNode.replaceChild(_1f,_20);}else{document.body.appendChild(_1f);}if(_1f.getAttribute("selected")=="true"||!_1d){_1d=_1f;}--i;}}if(_1d){iui.showPage(_1d);}},getSelectedPage:function(){for(var _21=document.body.firstChild;_21;_21=_21.nextSibling){if(_21.nodeType==1&&_21.getAttribute("selected")=="true"){return _21;}}},isNativeUrl:function(_22){for(var i=0;i td { + padding: 10px 1px; +} + +a.link_rhook { + display: block; + text-decoration: none; + padding: 0 10px 0 0; + margin-bottom: 2px; +} + +a.autolink { + border-bottom: 0; + padding: 0; + font: inherit; + display: inline; +} + +.table_detail .hdrlabel { + font-weight: bold; + font-size: 15px; + border-bottom: 1px solid #DDDDFF; +} + +.table_detail .label, .table_detail .label2 { + font-size: 13px; + text-align: right; + color: gray; + font-weight: normal; +} + +.table_detail .label2 { + font-size: 15px; + text-align: left; +} + +.table_detail .data { + font-size: 14px; +} + +.searchbox { + font-size: 20px; + margin: 20px; +} + +/* Checkbox UI similar to iPhone */ +.table_checkbox { + width: 100px; + font-size: 12px; + font-weight: bold; + border: 1px solid #888888; + background-color: #FCFCFC; +} +.table_checkbox .on { + float: right; + padding: 5px 15px; + background: #5F92FF; + color: white; +} + +.table_checkbox .off { + float: left; + padding: 5px 15px; + background: #EFEFEF; + color: #888888; +} + +.table_checkbox a { + color: inherit; + padding: 0; +} + +/* END */ diff --git a/oss/vtiger/trunk/modules/Notes/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Notes/language/zh_cn.lang.php new file mode 100644 index 00000000..d91573a3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Notes/language/zh_cn.lang.php @@ -0,0 +1,41 @@ + '备忘录', + 'LBL_MODULE_TITLE' => '备忘录: 首页', + 'LBL_SEARCH_FORM_TITLE' => '查找备忘录', + 'LBL_LIST_FORM_TITLE' => '备忘录列表', + 'LBL_NEW_FORM_TITLE' => '新增列表', + 'LBL_LIST_SUBJECT' => '主题', + 'LBL_LIST_CONTACT_NAME' => '联系人姓名', + 'LBL_LIST_RELATED_TO' => '相关对象', + 'LBL_LIST_DATE_MODIFIED' => '最新修改', + 'LBL_NOTE' => '备忘录:', + 'LBL_NOTE_SUBJECT' => '备忘录主题:', + 'LBL_CONTACT_NAME' => '联系人姓名:', + 'LBL_PHONE' => '电话:', + 'LBL_SUBJECT' => '主题:', + 'LBL_CLOSE' => '完成:', + 'LBL_RELATED_TO' => '相关对象:', + 'LBL_EMAIL_ADDRESS' => 'Email地址:', + 'LBL_COLON' => ':', + 'ERR_DELETE_RECORD' => '必须指定记录编号才能删除客户.', + 'LBL_LIST_FILENAME' => '*附件', + 'LBL_FILENAME' => '*附件:', + 'LBL_NOTE_INFORMATION' => '备忘录信息', + 'LBL_TOOL_FORM_TITLE' => '备忘录工具', + 'Contact Name' => '联系人姓名', + 'Related To' => '相关对象', + 'Subject' => '主题', + 'Created Time' => '创建时间', + 'Modified Time' => '修改时间', + 'Attachment' => '附件', + 'Note' => '备注', + 'Related to' => '相关对象', + 'Last Modified' => '最新更改日期', + 'File' => '文件', + 'LBL_ALL' => '所有', + 'LBL_ASSIGNED_TO' => '负责人', + 'Assigned To' => '负责人', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Orders/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Orders/language/zh_cn.lang.php new file mode 100644 index 00000000..e5c0dab5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Orders/language/zh_cn.lang.php @@ -0,0 +1,138 @@ + '订单', + 'LBL_SO_MODULE_NAME' => '销售订单', + 'LBL_RELATED_PRODUCTS' => '系列产品', + 'LBL_MODULE_TITLE' => '订单: Home', + 'LBL_SEARCH_FORM_TITLE' => '查找订单', + 'LBL_LIST_FORM_TITLE' => '采购订单列表', + 'LBL_LIST_SO_FORM_TITLE' => '销售订单列表', + 'LBL_NEW_FORM_TITLE' => '新增采购订单', + 'LBL_NEW_FORM_SO_TITLE' => '新增销售订单', + 'LBL_MEMBER_ORG_FORM_TITLE' => '下属单位', + 'LBL_LIST_ACCOUNT_NAME' => '客户姓名', + 'LBL_LIST_CITY' => '城市', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '省份', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => 'Email地址', + 'LBL_LIST_CONTACT_NAME' => '联系人姓名', + 'db_name' => 'LBL_LIST_ACCOUNT_NAME', + 'db_website' => 'LBL_LIST_WEBSITE', + 'db_billing_address_city' => 'LBL_LIST_CITY', + 'LBL_ACCOUNT' => '客户:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_PHONE' => '电话:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_TICKER_SYMBOL' => '股票代码:', + 'LBL_OTHER_PHONE' => '其他电话:', + 'LBL_ANY_PHONE' => '任意电话:', + 'LBL_MEMBER_OF' => '上级单位:', + 'LBL_EMAIL' => 'Email:', + 'LBL_EMPLOYEES' => '员工:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它Email:', + 'LBL_ANY_EMAIL' => '任意Email:', + 'LBL_OWNERSHIP' => '所有制:', + 'LBL_RATING' => '评价:', + 'LBL_INDUSTRY' => '行业:', + 'LBL_SIC_CODE' => '行业编码:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年收入:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_Quote_INFORMATION' => '客户信息', + 'LBL_CUSTOM_INFORMATION' => '自定义信息', + 'LBL_BILLING_ADDRESS' => '付款地址:', + 'LBL_SHIPPING_ADDRESS' => '付款地址:', + 'LBL_ANY_ADDRESS' => '任何地址:', + 'LBL_CITY' => '城市:', + 'LBL_STATE' => '省份:', + 'LBL_POSTAL_CODE' => '邮编:', + 'LBL_COUNTRY' => '国家:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息:', + 'LBL_TERMS_INFORMATION' => '付款条件', + 'LBL_DESCRIPTION' => '描述:', + 'NTC_COPY_BILLING_ADDRESS' => '将付款地址复制到收货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '将收货地址复制到付款地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '您确定要删除关于这个会员组织的记录?', + 'LBL_DUPLICATE' => '复制具有潜力的客户', + 'MSG_DUPLICATE' => '创建这个客户可能创建重复的客户。你可以选择客户列表中的客户复制创建新的公司,以继承它相关的数据。', + 'LBL_INVITEE' => '联系人', + 'ERR_DELETE_RECORD' => '删除这个客户必须指定这个客户的记录编号.', + 'LBL_SELECT_ACCOUNT' => '选择客户', + 'LBL_GENERAL_INFORMATION' => '一般信息', + 'LBL_NEW_POTENTIAL' => '新增商机', + 'LBL_POTENTIAL_TITLE' => '商机', + 'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话', + 'LBL_CALL_TITLE' => '电话', + 'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '撰写新邮件', + 'LBL_EMAIL_TITLE' => 'Emails', + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_CONTACT_TITLE' => '联系人', + 'LBL_ALL' => '所有', + 'LBL_PROSPECT' => '期望', + 'LBL_INVESTOR' => '投资商', + 'LBL_RESELLER' => '代理商', + 'LBL_PARTNER' => '合作伙伴', + 'LBL_TOOL_FORM_TITLE' => '客户工具', + 'Subject' => '主题', + 'Quote Name' => '报价单名称', + 'Vendor Name' => '供应商名称', + 'Requisition No' => '申请编号', + 'Tracking Number' => '查询号', + 'Contact Name' => '联系人姓名', + 'Due Date' => '到期日期', + 'Carrier' => '运输公司', + 'Type' => '类型', + 'Sales Tax' => '销售税', + 'Sales Commission' => '销售佣金', + 'Excise Duty' => '货物税', + 'Total' => '总计', + 'Product Name' => '产品名称', + 'Assigned To' => '负责人', + 'Billing Address' => '付款地址', + 'Shipping Address' => '收货地址', + 'Billing City' => '城市', + 'Billing State' => '省份', + 'Billing Code' => '邮编', + 'Billing Country' => '国家', + 'Shipping City' => '城市', + 'Shipping State' => '省份', + 'Shipping Code' => '邮编', + 'Shipping Country' => '国家', + 'City' => '城市', + 'State' => '省份', + 'Code' => '邮编', + 'Country' => '国家', + 'Created Time' => '创建时间', + 'Modified Time' => '修改时间', + 'Description' => '描述', + 'Potential Name' => '商机名称', + 'Customer No' => '客户编号', + 'Purchase Order' => '采购订单', + 'Vendor Terms' => '商家期约', + 'Pending' => '等待', + 'Account Name' => '客户姓名', + 'Terms & Conditions' => '付款条件', + 'LBL_PO_INFORMATION' => '采购订单信息', + 'LBL_PO' => '采购订单', + 'LBL_SO_INFORMATION' => '销售订单信息', + 'LBL_SO' => '销售订单:', + 'LBL_SO_FORM_TITLE' => '销售', + 'LBL_PO_FORM_TITLE' => '采购', + 'LBL_SUBJECT_TITLE' => '主题', + 'LBL_VENDOR_NAME_TITLE' => '供应商名称', + 'LBL_TRACKING_NO_TITLE' => '查询号:', + 'LBL_PO_SEARCH_TITLE' => '查找采购订单', + 'LBL_SO_SEARCH_TITLE' => '查找销售订单', + 'LBL_QUOTE_NAME_TITLE' => '报价单名称', + 'Order Id' => '订单编号', + 'LBL_MY_TOP_SO' => '最近销售订单', + 'Status' => '状态', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PickList/AssignValues.php b/oss/vtiger/trunk/modules/PickList/AssignValues.php new file mode 100644 index 00000000..ed945ac9 --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/AssignValues.php @@ -0,0 +1,53 @@ +assign("IMAGE_PATH",$image_path); + +$fieldName = vtlib_purify($_REQUEST["fieldname"]); +$fieldLabel = vtlib_purify($_REQUEST['fieldlabel']); +$moduleName = vtlib_purify($_REQUEST["moduleName"]); +$roleid = vtlib_purify($_REQUEST['roleid']); +if(!empty($roleid)){ + $roleName = getRoleName($roleid); +} + +if($moduleName == 'Events'){ + $temp_module_strings = return_module_language($current_language, 'Calendar'); +}else{ + $temp_module_strings = return_module_language($current_language, $moduleName); +} + +if(!empty($fieldName)){ + $values = getAllPickListValues($fieldName); +} + +$assignedValues = getAssignedPicklistValues($fieldName, $roleid, $adb); + +$smarty->assign("THEME",$theme); +$smarty->assign("FIELDNAME",$fieldName); +$smarty->assign("FIELDLABEL", getTranslatedString($fieldLabel)); +$smarty->assign("MODULE",$moduleName); +$smarty->assign("PICKVAL",$values); +$smarty->assign("ASSIGNED_VALUES",$assignedValues); +$smarty->assign("ROLEID",$roleid); +$smarty->assign("ROLENAME", $roleName); +$smarty->assign("MOD", return_module_language($current_language,'PickList')); +$smarty->assign("APP",$app_strings); + +$data = $smarty->fetch("modules/PickList/AssignPicklistValues.tpl"); +echo $data; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PickList/PickList.php b/oss/vtiger/trunk/modules/PickList/PickList.php new file mode 100644 index 00000000..6345043a --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/PickList.php @@ -0,0 +1,78 @@ +assign("MODULE_LISTS",$modules); +$smarty->assign("ROLE_LISTS",getrole2picklist()); +$smarty->assign("ALL_LISTS",$available_module_picklist); + +$smarty->assign("APP", $app_strings); //the include language files +$smarty->assign("MOD", return_module_language($current_language,'Settings')); //the settings module language file +$smarty->assign("MOD_PICKLIST", return_module_language($current_language,'PickList')); //the picklist module language files +$smarty->assign("TEMP_MOD", $temp_module_strings); //the selected modules' language file + +$smarty->assign("MODULE",$fld_module); +$smarty->assign("PICKLIST_VALUES",$picklist_fields); +$smarty->assign("THEME",$theme); +$smarty->assign("UITYPE", $uitype); +$smarty->assign("SEL_ROLEID",$roleid); + +if($_REQUEST['directmode'] != 'ajax'){ + $smarty->display("modules/PickList/PickList.tpl"); +}else{ + $smarty->display("modules/PickList/PickListContents.tpl"); +} + +?> diff --git a/oss/vtiger/trunk/modules/PickList/PickListAction.php b/oss/vtiger/trunk/modules/PickList/PickListAction.php new file mode 100644 index 00000000..06dce632 --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/PickListAction.php @@ -0,0 +1,139 @@ +sql_escape_string($tableName); +$mode = trim($_REQUEST['mode']); +if(empty($mode)){ + echo "action mode is empty"; + exit; +} + +if($mode == 'add'){ + $newValues = $_REQUEST['newValues']; + $selectedRoles = $_REQUEST['selectedRoles']; + + $arr = Zend_Json::decode($newValues); + $roles = Zend_Json::decode($selectedRoles); + $count = count($arr); + + $sql = "select picklistid from vtiger_picklist where name=?"; + $result = $adb->pquery($sql, array($tableName)); + $picklistid = $adb->query_result($result,0,"picklistid"); + + for($i=0; $i<$count;$i++){ + $val = trim($arr[$i]); + if(!empty($val)){ + $id = $adb->getUniqueID("vtiger_$tableName"); + $picklist_valueid = getUniquePicklistID(); + $sql = "insert into vtiger_$tableName values (?,?,?,?)"; + $adb->pquery($sql, array($id, $val, 1, $picklist_valueid)); + + //add the picklist values to the selected roles + for($j=0;$jquery_result($adb->pquery($sql, array($roleid, $picklistid)),0,'sortid'); + + $sql = "insert into vtiger_role2picklist values(?,?,?,?)"; + $adb->pquery($sql, array($roleid, $picklist_valueid, $picklistid, $sortid)); + } + } + } + echo "SUCCESS"; +}elseif($mode == 'edit'){ + $newValues = Zend_Json::decode($_REQUEST['newValues']); + $oldValues = Zend_Json::decode($_REQUEST['oldValues']); + if(count($newValues) != count($oldValues)){ + echo "Some error occured"; + exit; + } + + $qry="select tablename,columnname from vtiger_field where fieldname=? and presence in (0,2)"; + $result = $adb->pquery($qry, array($tableName)); + $num = $adb->num_rows($result); + + for($i=0; $ipquery($sql, array($newVal, $oldVal)); + + //replace the value of this piclist with new one in all records + if($num > 0){ + for($n=0;$n<$num;$n++){ + $table_name = $adb->query_result($result,$n,'tablename'); + $columnName = $adb->query_result($result,$n,'columnname'); + + $sql = "update $table_name set $columnName=? where $columnName=?"; + $adb->pquery($sql, array($newVal, $oldVal)); + } + } + } + } + echo "SUCCESS"; +}elseif($mode == 'delete'){ + $values = Zend_Json::decode($_REQUEST['values']); + $replaceVal = $_REQUEST['replaceVal']; + if(!empty($replaceVal)){ + $sql = "select * from vtiger_$tableName where $tableName=?"; + $result = $adb->pquery($sql, array($replaceVal)); + $replacePicklistID = $adb->query_result($result, 0, "picklist_valueid"); + } + + for($i=0;$ipquery($sql, array($values[$i])); + $origPicklistID = $adb->query_result($result, 0, "picklist_valueid"); + + //give permissions for the new picklist + if(!empty($replaceVal)){ + $sql = "select * from vtiger_role2picklist where picklistvalueid=?"; + $result = $adb->pquery($sql, array($replacePicklistID)); + $count = $adb->num_rows($result); + + if($count == 0){ + $sql = "update vtiger_role2picklist set picklistvalueid=? where picklistvalueid=?"; + $adb->pquery($sql, array($replacePicklistID, $origPicklistID)); + } + } + + $sql = "delete from vtiger_$tableName where $tableName=?"; + $adb->pquery($sql, array($values[$i])); + $sql = "delete from vtiger_role2picklist where picklistvalueid=?"; + $adb->pquery($sql, array($origPicklistID)); + + //replace the value of this piclist with new one in all records + $qry="select tablename,columnname from vtiger_field where fieldname=? and presence in (0,2)"; + $result = $adb->pquery($qry, array($tableName)); + $num = $adb->num_rows($result); + if($num > 0){ + for($n=0;$n<$num;$n++){ + $table_name = $adb->query_result($result,$n,'tablename'); + $columnName = $adb->query_result($result,$n,'columnname'); + + $sql = "update $table_name set $columnName=? where $columnName=?"; + $adb->pquery($sql, array($replaceVal, $values[$i])); + } + } + } + echo "SUCCESS"; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PickList/PickListAjax.php b/oss/vtiger/trunk/modules/PickList/PickListAjax.php new file mode 100644 index 00000000..0903b4dd --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/PickListAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/PickList/PickListUtils.php b/oss/vtiger/trunk/modules/PickList/PickListUtils.php new file mode 100644 index 00000000..c2669748 --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/PickListUtils.php @@ -0,0 +1,211 @@ +$fieldlabel,'generatedtype'=>$generatedtype,'columnname'=>$columnname,'fieldname'=>$fieldname,'value'=>picklistvalues)) + */ +function getUserFldArray($fld_module,$roleid){ + global $adb, $log; + $user_fld = Array(); + $tabid = getTabid($fld_module); + + $query="select vtiger_field.fieldlabel,vtiger_field.columnname,vtiger_field.fieldname, vtiger_field.uitype" . + " FROM vtiger_field inner join vtiger_picklist on vtiger_field.fieldname = vtiger_picklist.name" . + " where (displaytype=1 and vtiger_field.tabid=? and vtiger_field.uitype in ('15','55','33','16') " . + " or (vtiger_field.tabid=? and fieldname='salutationtype' and fieldname !='vendortype')) " . + " and vtiger_field.presence in (0,2) ORDER BY vtiger_picklist.picklistid ASC"; + + $result = $adb->pquery($query, array($tabid, $tabid)); + $noofrows = $adb->num_rows($result); + + if($noofrows > 0){ + $fieldlist = array(); + for($i=0; $i<$noofrows; $i++){ + $user_fld = array(); + $fld_name = $adb->query_result($result,$i,"fieldname"); + + $user_fld['fieldlabel'] = $adb->query_result($result,$i,"fieldlabel"); + $user_fld['generatedtype'] = $adb->query_result($result,$i,"generatedtype"); + $user_fld['columnname'] = $adb->query_result($result,$i,"columnname"); + $user_fld['fieldname'] = $adb->query_result($result,$i,"fieldname"); + $user_fld['uitype'] = $adb->query_result($result,$i,"uitype"); + $user_fld['value'] = getAssignedPicklistValues($user_fld['fieldname'], $roleid, $adb); + $fieldlist[] = $user_fld; + } + } + return $fieldlist; +} + +/** + * Function to get modules which has picklist values + * It gets the picklist modules and return in an array in the following format + * $modules = Array($tabid=>$tablabel,$tabid1=>$tablabel1,$tabid2=>$tablabel2,-------------,$tabidn=>$tablabeln) + */ +function getPickListModules(){ + global $adb; + // vtlib customization: Ignore disabled modules. + $query = 'select distinct vtiger_field.fieldname,vtiger_field.tabid,vtiger_tab.tablabel, vtiger_tab.name as tabname,uitype from vtiger_field inner join vtiger_tab on vtiger_tab.tabid=vtiger_field.tabid where uitype IN (15,33) and vtiger_field.tabid != 29 and vtiger_tab.presence != 1 and vtiger_field.presence in (0,2) order by vtiger_field.tabid ASC'; + // END + $result = $adb->pquery($query, array()); + while($row = $adb->fetch_array($result)){ + $modules[$row['tablabel']] = $row['tabname']; + } + return $modules; +} + +/** + * this function returns all the roles present in the CRM so that they can be displayed in the picklist module + * @return array $role - the roles present in the CRM in the array format + */ +function getrole2picklist(){ + global $adb; + $query = "select rolename,roleid from vtiger_role where roleid not in('H1') order by roleid"; + $result = $adb->pquery($query, array()); + while($row = $adb->fetch_array($result)){ + $role[$row['roleid']] = $row['rolename']; + } + return $role; + +} + +/** + * this function returns the picklists available for a module + * @param array $picklist_details - the details about the picklists in the module + * @return array $module_pick - the picklists present in the module in an array format + */ +function get_available_module_picklist($picklist_details){ + $avail_pick_values = $picklist_details; + foreach($avail_pick_values as $key => $val){ + $module_pick[$avail_pick_values[$key]['fieldname']] = getTranslatedString($avail_pick_values[$key]['fieldlabel']); + } + return $module_pick; +} + +/** + * this function returns all the picklist values that are available for a given + * @param string $fieldName - the name of the field + * @return array $arr - the array containing the picklist values + */ +function getAllPickListValues($fieldName){ + global $adb; + $sql = 'SELECT * FROM vtiger_'.$adb->sql_escape_string($fieldName); + $result = $adb->query($sql); + $count = $adb->num_rows($result); + + $arr = array(); + for($i=0;$i<$count;$i++){ + $arr[] = $adb->query_result($result, $i, $fieldName); + } + return $arr; +} + + +/** + * this function accepts the fieldname and the language string array and returns all the editable picklist values for that fieldname + * @param string $fieldName - the name of the picklist + * @param array $lang - the language string array + * @param object $adb - the peardatabase object + * @return array $pick - the editable picklist values + */ +function getEditablePicklistValues($fieldName, $lang, $adb){ + $values = array(); + $fieldName = $adb->sql_escape_string($fieldName); + $sql="select $fieldName from vtiger_$fieldName where presence=1 and $fieldName <> '--None--'"; + $res = $adb->query($sql); + $RowCount = $adb->num_rows($res); + if($RowCount > 0){ + for($i=0;$i<$RowCount;$i++){ + $pick_val = $adb->query_result($res,$i,$fieldName); + if($lang[$pick_val] != ''){ + $values[]=$lang[$pick_val]; + }else{ + $values[]=$pick_val; + } + } + } + return $values; +} + +/** + * this function accepts the fieldname and the language string array and returns all the non-editable picklist values for that fieldname + * @param string $fieldName - the name of the picklist + * @param array $lang - the language string array + * @param object $adb - the peardatabase object + * @return array $pick - the no-editable picklist values + */ +function getNonEditablePicklistValues($fieldName, $lang, $adb){ + $values = array(); + $fieldName = $adb->sql_escape_string($fieldName); + $sql = "select $fieldName from vtiger_$fieldName where presence=0"; + $result = $adb->query($sql); + $count = $adb->num_rows($result); + for($i=0;$i<$count;$i++){ + $non_val = $adb->query_result($result,$i,$fieldName); + if($lang[$non_val] != ''){ + $values[]=$lang[$non_val]; + }else{ + $values[]=$non_val; + } + } + if(count($values)==0){ + $values = ""; + } + return $values; +} + +/** + * this function returns all the assigned picklist values for the given tablename for the given roleid + * @param string $tableName - the picklist tablename + * @param integer $roleid - the roleid of the role for which you want data + * @param object $adb - the peardatabase object + * @return array $val - the assigned picklist values in array format + */ +function getAssignedPicklistValues($tableName, $roleid, $adb){ + $arr = array(); + + $sub = getSubordinateRoleAndUsers($roleid); + $subRoles = array($roleid); + $subRoles = array_merge($subRoles, array_keys($sub)); + + $sql = "select picklistid from vtiger_picklist where name = ?"; + $result = $adb->pquery($sql, array($tableName)); + if($adb->num_rows($result)){ + $picklistid = $adb->query_result($result, 0, "picklistid"); + + + $roleids = array(); + foreach($subRoles as $role){ + $roleids[] = $role; + } + + $sql = "SELECT distinct ".$adb->sql_escape_string($tableName)." FROM ". $adb->sql_escape_string("vtiger_$tableName") + . " inner join vtiger_role2picklist on ".$adb->sql_escape_string("vtiger_$tableName").".picklist_valueid=vtiger_role2picklist.picklistvalueid" + . " and roleid in (".generateQuestionMarks($roleids).") order by sortid"; + $result = $adb->pquery($sql, $roleids); + $count = $adb->num_rows($result); + + if($count) { + while($resultrow = $adb->fetch_array($result)) { + $arr[] = $resultrow[$tableName]; + } + } + } + // END + + return $arr; +} +?> diff --git a/oss/vtiger/trunk/modules/PickList/SaveAssignedValues.php b/oss/vtiger/trunk/modules/PickList/SaveAssignedValues.php new file mode 100644 index 00000000..d8bfc7a8 --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/SaveAssignedValues.php @@ -0,0 +1,71 @@ +pquery($sql, array($tableName)); +if($adb->num_rows($result) > 0){ + $picklistid = $adb->query_result($result, 0, "picklistid"); +} + +if(!empty($roleid)){ + assignValues($picklistid, $roleid, $values, $tableName); +} + +$otherRoles = Zend_Json::decode($otherRoles); +if(!empty($otherRoles)){ + foreach($otherRoles as $role){ + assignValues($picklistid, $role, $values, $tableName); + } +} + +echo "SUCCESS"; + + +function assignValues($picklistid, $roleid, $values, $tableName){ + global $adb; + $count = count($values); + //delete older values + $sql = 'DELETE FROM vtiger_role2picklist WHERE roleid=? AND picklistid=?'; + $adb->pquery($sql, array($roleid,$picklistid)); + + //insert the new values + for($i=0;$i<$count;$i++){ + $pickVal = $values[$i]; + $tableName = $adb->sql_escape_string($tableName); + $sql = "SELECT * FROM vtiger_$tableName WHERE $tableName=?"; + $result = $adb->pquery($sql, array($pickVal)); + if($adb->num_rows($result) > 0){ + $picklistvalueid = $adb->query_result($result, 0, "picklist_valueid"); + $sortid = $i+1; + $sql = 'INSERT INTO vtiger_role2picklist VALUES (?,?,?,?)'; + $adb->pquery($sql, array($roleid, $picklistvalueid, $picklistid, $sortid)); + } + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PickList/ShowActionDivs.php b/oss/vtiger/trunk/modules/PickList/ShowActionDivs.php new file mode 100644 index 00000000..292f149f --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/ShowActionDivs.php @@ -0,0 +1,61 @@ +assign("IMAGE_PATH",$image_path); + +$fieldName=vtlib_purify($_REQUEST["fieldname"]); +$fieldLabel =vtlib_purify($_REQUEST["fieldlabel"]); +$moduleName=vtlib_purify($_REQUEST["moduleName"]); +$mode=$_REQUEST["mode"]; + +if($moduleName == 'Events'){ + $temp_module_strings = return_module_language($current_language, 'Calendar'); +}else{ + $temp_module_strings = return_module_language($current_language, $moduleName); +} + +if(isset($fieldName)){ + $editableValues = getEditablePicklistValues($fieldName, $temp_module_strings, $adb); + $nonEditableValues = getNonEditablePicklistValues($fieldName, $temp_module_strings, $adb); +} +$temp_label = getTranslatedString($fieldLabel); +$roleDetails=getAllRoleDetails(); + +// Remove Organization from the list of roles (which is the first one in the list of roles) +array_shift($roleDetails); + +$smarty->assign("FIELDNAME",$fieldName); +$smarty->assign("FIELDLABEL",$temp_label); +$smarty->assign('NONEDITPICKLIST',$nonEditableValues); +$smarty->assign("MODULE",$moduleName); +$smarty->assign("PICKVAL",$editableValues); +$smarty->assign("ROLEDETAILS",$roleDetails); +$smarty->assign("MOD", return_module_language($current_language,'PickList')); +$smarty->assign("APP",$app_strings); + +if($mode == 'add'){ + $data = $smarty->fetch("modules/PickList/AddPickList.tpl"); +}elseif($mode == 'edit'){ + $data = $smarty->fetch("modules/PickList/EditPickList.tpl"); +}elseif($mode == 'delete'){ + $data = $smarty->fetch("modules/PickList/DeletePickList.tpl"); +} + +echo $data; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PickList/ShowRoleSelect.php b/oss/vtiger/trunk/modules/PickList/ShowRoleSelect.php new file mode 100644 index 00000000..4b9b4cef --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/ShowRoleSelect.php @@ -0,0 +1,34 @@ +getRoleName($roleid))); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("ROLES",$otherRoles); +$smarty->assign("MOD", return_module_language($current_language,'PickList')); +$smarty->assign("APP",$app_strings); + +$str = $smarty->fetch("modules/PickList/ShowRoleSelect.tpl"); +echo $str; +?> diff --git a/oss/vtiger/trunk/modules/PickList/language/en_us.lang.php b/oss/vtiger/trunk/modules/PickList/language/en_us.lang.php new file mode 100644 index 00000000..f5ffec17 --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/language/en_us.lang.php @@ -0,0 +1,34 @@ +'Assign', + 'ADD_PICKLIST_VALUES'=>'Add picklist values', + 'LBL_EXISTING_PICKLIST_VALUES'=>'Existing picklist values', + 'LBL_PICKLIST_ADDINFO'=>'Add new entries here', + 'LBL_SELECT_ROLES'=>'Select roles', + 'LBL_NON_EDITABLE_PICKLIST_ENTRIES'=>'Non-editable values', + 'EDIT_PICKLIST_VALUE'=>'Edit picklist values', + 'LBL_EDIT_HERE'=>'Replace with: ', + 'LBL_SELECT_TO_EDIT'=>'Select a value to edit: ', + 'DELETE_PICKLIST_VALUES'=>'Delete picklist values', + 'LBL_REPLACE_WITH'=>'Replace with: ', + 'ASSIGN_PICKLIST_VALUES'=>'Assign Picklist Values', + 'LBL_PICKLIST_VALUES'=>'Available picklist values', + 'LBL_PICKLIST_VALUES_ASSIGNED_TO'=>'Assigned picklist values for ', + 'LBL_ADD_TO_OTHER_ROLES'=>'Add to other roles', + 'LBL_OK_BUTTON_LABEL'=>'Ok', + 'LBL_SELECT_ROLES'=>'Select roles', + 'LBL_DISPLAYED_VALUES'=>'All accessible values for the role are shown below', +); +?> diff --git a/oss/vtiger/trunk/modules/PickList/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/PickList/language/zh_cn.lang.php new file mode 100644 index 00000000..f5ffec17 --- /dev/null +++ b/oss/vtiger/trunk/modules/PickList/language/zh_cn.lang.php @@ -0,0 +1,34 @@ +'Assign', + 'ADD_PICKLIST_VALUES'=>'Add picklist values', + 'LBL_EXISTING_PICKLIST_VALUES'=>'Existing picklist values', + 'LBL_PICKLIST_ADDINFO'=>'Add new entries here', + 'LBL_SELECT_ROLES'=>'Select roles', + 'LBL_NON_EDITABLE_PICKLIST_ENTRIES'=>'Non-editable values', + 'EDIT_PICKLIST_VALUE'=>'Edit picklist values', + 'LBL_EDIT_HERE'=>'Replace with: ', + 'LBL_SELECT_TO_EDIT'=>'Select a value to edit: ', + 'DELETE_PICKLIST_VALUES'=>'Delete picklist values', + 'LBL_REPLACE_WITH'=>'Replace with: ', + 'ASSIGN_PICKLIST_VALUES'=>'Assign Picklist Values', + 'LBL_PICKLIST_VALUES'=>'Available picklist values', + 'LBL_PICKLIST_VALUES_ASSIGNED_TO'=>'Assigned picklist values for ', + 'LBL_ADD_TO_OTHER_ROLES'=>'Add to other roles', + 'LBL_OK_BUTTON_LABEL'=>'Ok', + 'LBL_SELECT_ROLES'=>'Select roles', + 'LBL_DISPLAYED_VALUES'=>'All accessible values for the role are shown below', +); +?> diff --git a/oss/vtiger/trunk/modules/Portal/Delete.php b/oss/vtiger/trunk/modules/Portal/Delete.php new file mode 100644 index 00000000..f426e90e --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/Delete.php @@ -0,0 +1,22 @@ +pquery($del_query, array($_REQUEST['record'])); + + //code added for returning back to the current view after delete from list view +header("Location: index.php?action=PortalAjax&module=Portal&file=ListView&mode=ajax&datamode=manage"); +?> diff --git a/oss/vtiger/trunk/modules/Portal/ListView.php b/oss/vtiger/trunk/modules/Portal/ListView.php new file mode 100644 index 00000000..15f17bf9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/ListView.php @@ -0,0 +1,78 @@ +pquery($query, array()); +//Getting the Default URL Value if any +$default_url = $adb->query_result($result,0,'portalurl'); +$no_of_portals=$adb->num_rows($result); +$portal_info=array(); +//added as an enhancement to set default +?> + +query_result($result,0,'portalurl'); +$smarty = new vtigerCRM_Smarty; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("DEFAULT_URL", $def_ault); +$smarty->assign("APP", $app_strings); +$smarty->assign("PORTAL_COUNT", count($portal_info)); +$smarty->assign("PORTALS", $portal_info); +$smarty->assign("MODULE", $currentModule); +$smarty->assign("DEFAULT",'yes'); +$smarty->assign("CATEGORY", getParentTab()); +if($_REQUEST['datamode'] == 'data') + $smarty->display("MySitesContents.tpl"); +elseif($_REQUEST['datamode'] == 'manage') + $smarty->display("MySitesManage.tpl"); +else + $smarty->display("MySites.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Portal/Popup.php b/oss/vtiger/trunk/modules/Portal/Popup.php new file mode 100644 index 00000000..969cdabb --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/Popup.php @@ -0,0 +1,67 @@ +pquery($query, array($portalid)); + $portalname = $adb->query_result($result,0,'portalname'); + $portalurl = $adb->query_result($result,0,'portalurl'); + /* to remove http:// from portal url*/ + $portalurl = preg_replace("/http:\/\//i","",$portalurl); +} +$portal_inputs=''; +$portal_inputs.='
    + + + + + + +
    ' .$mod_strings['LBL_ADD'] .' '.$mod_strings['LBL_BOOKMARK'].'
    + + + + +
    + + + + + + + + + + + +
    '.$mod_strings['LBL_BOOKMARK'].' ' .$mod_strings['LBL_URL'] .' http://
    '.$mod_strings['LBL_BOOKMARK'].' ' .$mod_strings['LBL_NAME'] .'
    +
    + + + + +
    +    + +
    + +
    '; + +echo $portal_inputs; + + +?> diff --git a/oss/vtiger/trunk/modules/Portal/Portal.js b/oss/vtiger/trunk/modules/Portal/Portal.js new file mode 100644 index 00000000..129b2c00 --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/Portal.js @@ -0,0 +1,146 @@ +/********************************************************************************* +** 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. +* + ********************************************************************************/ + + +function fetchAddSite(id) +{ + $("status").style.display="inline"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'module=Portal&action=PortalAjax&file=Popup&record='+id, + onComplete: function(response) { + $("status").style.display="none"; + $('editportal_cont').innerHTML = response.responseText; + } + } + ); +} + +function fetchContents(mode) +{ + // Reloading the window is better, If not reloaded ... mysitesArray variable needs to be updated + // using eval method on javascript. + if(mode == 'data') { + window.location.href = 'index.php?module=Portal&action=ListView&parenttab=Tools'; + return; + } + $("status").style.display="inline"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'action=PortalAjax&mode=ajax&module=Portal&file=ListView&datamode='+mode, + onComplete: function(response) { + $("status").style.display="none"; + $('portalcont').innerHTML = response.responseText; + } + } + ); +} +function DeleteSite(id) +{ + if(confirm(alert_arr.SURE_TO_DELETE)) + { + $("status").style.display="inline"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'action=PortalAjax&mode=ajax&file=Delete&module=Portal&record='+id, + onComplete: function(response) { + $("status").style.display="none"; + $('portalcont').innerHTML = response.responseText; + } + } + ); + } +} +function SaveSite(id) +{ + if ($('portalurl').value.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) { + alert(alert_arr.SITEURL_CANNOT_BE_EMPTY) + return false; + } + if ($('portalname').value.replace(/^\s+/g, '').replace(/\s+$/g, '').length==0) { + alert(alert_arr.SITENAME_CANNOT_BE_EMPTY) + return false; + } + Effect.Puff('orgLay'); + $("status").style.display="inline"; + var portalurl = document.getElementById('portalurl').value; + var portalurl = portalurl.replace(/&/g, "#$#$#"); + var portalname = document.getElementById('portalname').value; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'action=PortalAjax&mode=ajax&file=Save&module=Portal&portalname='+portalname+'&portalurl='+portalurl+'&record='+id, + onComplete: function(response) { + if(response.responseText.indexOf(":#:FAILURE") > -1) + { + alert(alert_arr.VALID_DATA) + }else + { + $('portalcont').innerHTML = response.responseText; + } + $("status").style.display="none"; + } + } + ); +} +function setSite(oUrllist) +{ + //var url = oUrllist.options[oUrllist.options.selectedIndex].value; + var id = oUrllist.options[oUrllist.options.selectedIndex].value; + document.getElementById('locatesite').src = mysitesArray[id]; +} +//added as an enhancement to set default value +function defaultMysites(oSelectlist) +{ + var id = $("urllist").value; + $("status").style.display="block"; + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody:'action=PortalAjax&mode=ajax&file=Save&module=Portal&check=true&passing_var='+id, + onComplete: function(response) { + //alert(response.responseText); + $("status").style.display="none"; + } + } + ); + +} + +var oRegex = new Object() ; +oRegex.UriProtocol = new RegExp('') ; +oRegex.UriProtocol.compile( '^(((http|https|ftp|news):\/\/)|mailto:)', 'gi' ) ; + +oRegex.UrlOnChangeProtocol = new RegExp('') ; +oRegex.UrlOnChangeProtocol.compile( '^(http|https|ftp|news)://(?=.)', 'gi' ) ; + +function OnUrlChange() +{ + var sUrl; + var sProtocol; + + sUrl=document.getElementById("portalurl").value ; + sProtocol=oRegex.UrlOnChangeProtocol.exec( sUrl ) ; + if ( sProtocol ) + { + sUrl = sUrl.substr( sProtocol[0].length ) ; + document.getElementById("portalurl").value = sUrl ; + } + + +} diff --git a/oss/vtiger/trunk/modules/Portal/Portal.php b/oss/vtiger/trunk/modules/Portal/Portal.php new file mode 100644 index 00000000..de7e3a38 --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/Portal.php @@ -0,0 +1,47 @@ +println("just entered the SavePortal method"); + $portalid=$adb->getUniqueID('vtiger_portal'); + $query="insert into vtiger_portal values(?,?,?,?,?)"; + $params=array($portalid,$portalname,$portalurl,0,0); + $adb->println($query); + $result=$adb->pquery($query,$params); + return $portalid; +} +/** Function to update the portal in database + * @param $portalname : Type String + * @param $portalurl : Type String + * @param $portalid : Type Integer + * This function updates the portal with the given $portalname,$portalurl + * This Returns $portalid + */ +function UpdatePortal($portalname,$portalurl,$portalid) +{ + global $adb; + $adb->println("just entered the SavePortal method"); + $query="update vtiger_portal set portalname=? ,portalurl=? where portalid=?"; + $params=array($portalname, $portalurl, $portalid); + $adb->println($query); + $result=$adb->pquery($query, $params); + return $portalid; +} +?> diff --git a/oss/vtiger/trunk/modules/Portal/PortalAjax.php b/oss/vtiger/trunk/modules/Portal/PortalAjax.php new file mode 100644 index 00000000..b1b7fcdc --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/PortalAjax.php @@ -0,0 +1,13 @@ + + diff --git a/oss/vtiger/trunk/modules/Portal/Save.php b/oss/vtiger/trunk/modules/Portal/Save.php new file mode 100644 index 00000000..032f027e --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/Save.php @@ -0,0 +1,44 @@ +pquery($updateDefalt, array($_REQUEST['passing_var'])); + $updateZero = "UPDATE vtiger_portal SET setdefault=0 WHERE portalid not in(?)"; + $set_default= $adb->pquery($updateZero, array($_REQUEST['passing_var'])); + exit(); +} +if($portlname != '' && $portlurl != '') +{ + if(isset($_REQUEST['record']) && $_REQUEST['record'] !='') + { + $result=UpdatePortal($portlname,"http://".str_replace("#$#$#","&",$portlurl),$_REQUEST['record']); + } + else + { + $result=SavePortal($portlname,"http://".str_replace("#$#$#","&",$portlurl)); + } + header("Location: index.php?action=PortalAjax&module=Portal&file=ListView&mode=ajax&datamode=manage"); +}else +{ + echo ":#:FAILURE"; +} +?> diff --git a/oss/vtiger/trunk/modules/Portal/index.php b/oss/vtiger/trunk/modules/Portal/index.php new file mode 100644 index 00000000..d46fe334 --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/index.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Portal/language/en_us.lang.php b/oss/vtiger/trunk/modules/Portal/language/en_us.lang.php new file mode 100644 index 00000000..6fb714bf --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/language/en_us.lang.php @@ -0,0 +1,34 @@ +"BookMarked URL's", +'LBL_MANAGE_BOOKMARKS'=>'Manage Bookmarks', +'LBL_BOOKMARK_LIST'=>'Bookmark List', +'LBL_MY_BOOKMARKS'=>'My Bookmarks', +'LBL_NEW_BOOKMARK'=>'New Bookmark', +'LBL_BOOKMARK'=>'Bookmark', +'LBL_NAME'=>'Name :', +'LBL_URL'=>'URL :', +'LBL_ADD'=>'Add', +'LBL_SNO'=>'#', +'LBL_BOOKMARK_NAME_URL'=>'Bookmark Name & URL', +'LBL_TOOLS'=>'Tools', +'LBL_MANAGE_SITES'=>'Manage Sites', +'LBL_MY_SITES'=>'Sites', + +// Added/Updated for vtiger CRM 5.0.4 +//added as an enhancement +'LBL_SET_DEFAULT_BUTTON'=>'Set As Default', +); +?> diff --git a/oss/vtiger/trunk/modules/Portal/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Portal/language/zh_cn.lang.php new file mode 100644 index 00000000..b69ee855 --- /dev/null +++ b/oss/vtiger/trunk/modules/Portal/language/zh_cn.lang.php @@ -0,0 +1,32 @@ + '书签网址的', + 'LBL_MANAGE_BOOKMARKS' => '管理书签', + 'LBL_BOOKMARK_LIST' => '书签列表', + 'LBL_MY_BOOKMARKS' => '我的书签', + 'LBL_NEW_BOOKMARK' => '新增书签', + 'LBL_BOOKMARK' => '书签', + 'LBL_NAME' => '名称:', + 'LBL_URL' => '网址:', + 'LBL_ADD' => '新增', + 'LBL_SNO' => '#', + 'LBL_BOOKMARK_NAME_URL' => '书签名称 & 网址', + 'LBL_TOOLS' => '工具', + 'LBL_MANAGE_SITES' => '管理网站', + 'LBL_MY_SITES' => '我的网站', +//added as an enhancement +'LBL_SET_DEFAULT_BUTTON'=>'预设', +); +?> diff --git a/oss/vtiger/trunk/modules/Potentials/CallRelatedList.php b/oss/vtiger/trunk/modules/Potentials/CallRelatedList.php new file mode 100644 index 00000000..741aad54 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/CallRelatedList.php @@ -0,0 +1,75 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['potentialname']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings; + global $currentModule; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("CATEGORY",$category); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("ID",$focus->id); + $smarty->assign("MODULE",$currentModule); + $smarty->assign("SINGLE_MOD",$app_strings['Potential']); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + //$smarty->assign("ACCOUNTID",$focus->column_fields['account_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 + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/Charts.php b/oss/vtiger/trunk/modules/Potentials/Charts.php new file mode 100644 index 00000000..67194ede --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Charts.php @@ -0,0 +1,1241 @@ +debug("Entering outcome_by_month(".$date_start.",". $date_end.",". $user_id.") method ..."); + global $app_strings,$lang_crm, $app_list_strings, $current_module_strings,$current_user, $log, $charset, $tmp_dir; + global $theme; + include_once ('Image/Graph.php'); + include_once ('Image/Canvas.php'); + + $log =& LoggerManager::getLogger('outcome_by_month chart'); + // Set the basic parameters of the graph + $canvas =& Image_Canvas::factory('png', array('width' => $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + $log->debug("graph object created"); + + // add a TrueType font + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 11 pixels + $font->setSize(8); + + $graph->setFont($font); + // create the plotarea layout + $title =& Image_Graph::factory('title', array('Title',10)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'axis', + 'axis' + )); + $footer =& Image_Graph::factory('title', array('Footer',8)); + $graph->add( + Image_Graph::vertical($title, + Image_Graph::vertical( + $plotarea, + $footer, + 90 + ), + 5 + ) + ); + + //$graph->SetScale("textlin"); + + if (!file_exists($cache_file_name) || !file_exists($cache_file_name.'.map') || $refresh == true) { + //$font = calculate_font_family($lang_crm); + + $log->debug("date_start is: $date_start"); + $log->debug("date_end is: $date_end"); + $log->debug("user_id is: "); + $log->debug($user_id); + $log->debug("cache_file_name is: $cache_file_name"); + + //build the where clause for the query that matches $user + $where = ""; + $first = true; + $current = 0; + + //build the where clause for the query that matches $date_start and $date_end + $where .= " closingdate >= '$date_start' AND closingdate <= '$date_end'"; + $subtitle = $current_module_strings['LBL_DATE_RANGE']." ".getDisplayDate($date_start)." ".$current_module_strings['LBL_DATE_RANGE_TO']." ".getDisplayDate($date_end)."\n"; + + //Now do the db queries + //query for opportunity data that matches $datay and $user + $opp = new Potentials(); + $opp_list = $opp->get_full_list("vtiger_potential.amount DESC, vtiger_potential.closingdate DESC", $where); + + //build pipeline by sales stage data + $total = 0; + $count = array(); + $sum = array(); + $months = array(); + $other = $current_module_strings['LBL_LEAD_SOURCE_OTHER']; + if (isset($opp_list)) { + foreach ($opp_list as $record) { + $month = substr_replace($record->column_fields['closingdate'],'',-3); + if (!in_array($month, $months)) { array_push($months, $month); } + if ($record->column_fields['sales_stage'] == 'Closed Won' || $record->column_fields['sales_stage'] == 'Closed Lost') { + $sales_stage=$record->column_fields['sales_stage']; + } + else { + $sales_stage=$other; + } + + if (!isset($sum[$month][$sales_stage][$record->column_fields['assigned_user_id']])) + { + $sum[$month][$sales_stage][$record->column_fields['assigned_user_id']] = 0; + } + if (isset($record->column_fields['amount']) && in_array($record->column_fields['assigned_user_id'],$user_id)) { + // Strip all non numbers from this string. + $amount = convertFromMasterCurrency(ereg_replace('[^0-9]', '', floor($record->column_fields['amount'])),$current_user->conv_rate); + $sum[$month][$sales_stage][$record->column_fields['assigned_user_id']] = $sum[$month][$sales_stage][$record->column_fields['assigned_user_id']] + $amount; + if (isset($count[$month][$sales_stage][$record->column_fields['assigned_user_id']])) { + + $count[$month][$sales_stage][$record->column_fields['assigned_user_id']]++; + } else { + + $count[$month][$sales_stage][$record->column_fields['assigned_user_id']] = 1; + } + $total = $total + ($amount/1000); + } + } + } + + $legend = array(); + $datax = array(); + $aTargets = array(); + $aAlts = array(); + $stages = array($other, 'Closed Lost', 'Closed Won'); + //sort the months or push a bogus month on the array so that an empty chart is drawn + if (empty($months)) { + array_push($months, date('Y-m',time())); + } + else{ + sort($months); + } + foreach($months as $month) { + foreach($stages as $stage) { + $log->debug("stage is $stage"); + foreach ($user_id as $the_id) { + $the_user = get_assigned_user_name($the_id); + if (!isset($datax[$stage][$the_id])) { + $datax[$stage][$the_id] = array(); + } + if (!isset($aAlts[$stage][$the_id])) { + $aAlts[$stage][$the_id] = array(); + } + if (!isset($aTargets[$stage][$the_id])) { + $aTargets[$stage][$the_id] = array(); + } + + if (isset($sum[$month][$stage][$the_id])) { + array_push($datax[$stage][$the_id], $sum[$month][$stage][$the_id]/1000); + array_push($aAlts[$stage][$the_id], $the_user.' - '.$count[$month][$stage][$the_id]." ".$current_module_strings['LBL_OPPS_OUTCOME']." $stage"); + } + else { + array_push($datax[$stage][$the_id], 0); + array_push($aAlts[$stage][$the_id], ""); + } + $cvid = getCvIdOfAll("Potentials"); + array_push($aTargets[$stage][$the_id], "index.php?module=Potentials&action=ListView&date_closed=$month&sales_stage=".urlencode($stage)."&query=true&type=dbrd&owner=".$the_user."&viewname=".$cvid); + } + } + array_push($legend,$month); + } + $log->debug("datax is:"); + $log->debug($datax); + $log->debug("aAlts is:"); + $log->debug($aAlts); + $log->debug("aTargets is:"); + $log->debug($aTargets); + $log->debug("sum is:"); + $log->debug($sum); + $log->debug("count is:"); + $log->debug($count); + + //now build the bar plots for each user across the sales stages + $index = 0; + $datasets = array(); + $xlabels = array(); + $fills =& Image_Graph::factory('Image_Graph_Fill_Array'); + $color = array('Closed Lost'=>'#FF9900','Closed Won'=>'#009933', $other=>'#0066CC'); + foreach($stages as $stage) { + $datasets[$index] = & Image_Graph::factory('dataset'); + foreach($datax[$stage] as $ownerid=>$owner_amt) { + foreach($owner_amt as $i=>$y) { + $x = 1+2*$i; + $datasets[$index]->addPoint( + $x, + $y, + array( + 'url' => $aTargets[$stage][$ownerid][$i], + 'alt' => $aAlts[$stage][$ownerid][$i] + ) + ); + } + } + // Set fill colors for bars + $fills->addColor($color[$stage]); + $index++; + } + + for($i=0;$i$m) { + $monthSum = 0; + foreach($user_id as $the_id) { + foreach($stages as $stage) $monthSum += $datax[$stage][$the_id][$num]; + } + if($monthSum > $maximum) $maximum = $monthSum; + $log->debug('maximum = '.$maximum.' month = '.$m.' sum = '.$monthSum); + } + + if($theme == "blue") + { + $font_color = "#212473"; + } + else + { + $font_color = "#000000"; + } + $font->setColor($font_color); + + // Create the grouped bar plot + $gbplot = & $plotarea->addNew('bar', array($datasets, 'stacked')); + $gbplot->setFillStyle($fills); + + //You can change the width of the bars if you like + $gbplot->setBarWidth(50/count($months),"%"); + + // set margin + $plotarea->setPadding(array('top'=>0,'bottom'=>0,'left'=>10,'right'=>30)); + + // Set white margin color + $graph->setBackgroundColor('#F5F5F5'); + + // Use a box around the plot area + $gbplot->setBorderColor('black'); + + // Use a gradient to fill the plot area + $gbplot->setBackground(Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_VERTICAL, 'white', '#E5E5E5'))); + + // Setup title + $titlestr = $current_module_strings['LBL_TOTAL_PIPELINE'].$current_user->currency_symbol.$total.$app_strings['LBL_THOUSANDS_SYMBOL']; + //$titlestr = $current_module_strings['LBL_TOTAL_PIPELINE'].$current_user->currency_symbol.$total; + + $title->setText($titlestr); + + // Create the xaxis labels + $array_data =& Image_Graph::factory('Image_Graph_DataPreprocessor_Array', + array($xlabels) + ); + + // Setup X-axis + $xaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_X); + $xaxis->setDataPreprocessor($array_data); + $xaxis->forceMinimum(0); + $xaxis->forceMaximum(2*count($months)); + $xaxis->setLabelInterval(1); + $xaxis->setTickOptions(0,0); + $xaxis->setLabelInterval(2,2); + $xaxis->setTickOptions(5,0,2); + + // set grid + $gridY =& $plotarea->addNew('line_grid', IMAGE_GRAPH_AXIS_Y); + $gridY->setLineColor('#E5E5E5@0.5'); + + + // Add some grace to y-axis so the bars doesn't go + // all the way to the end of the plot area + $yaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_Y); + $yaxis->forceMaximum($maximum * 1.1); + $ticks = get_tickspacing($maximum); + + // Setup the Y-axis to be displayed in the bottom of the + // graph. We also finetune the exact layout of the title, + // ticks and labels to make them look nice. + $yaxis->setAxisIntersection('max'); + + // Then fix the tick marks + $valueproc =& Image_Graph::factory('Image_Graph_DataPreprocessor_Formatted', $current_user->currency_symbol."%d"); + $yaxis->setFontSize(8); + $yaxis->setDataPreprocessor($valueproc); + // Arrange Y-Axis tick marks inside + $yaxis->setLabelInterval($ticks[0]); + $yaxis->setTickOptions(-5,0); + $yaxis->setLabelInterval($ticks[1],2); + $yaxis->setTickOptions(-2,0,2); + $yaxis->setLabelOption('position','inside'); + + // Finally setup the title + $yaxis->setLabelOption('position','inside'); + + // eliminate zero values + $gbplot->setDataSelector(Image_Graph::factory('Image_Graph_DataSelector_NoZeros')); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setDataPreprocessor($valueproc); + $marker->setFillColor('000000@0.0'); + $marker->setBorderColor('000000@0.0'); + $marker->setFontColor('white'); + $marker->setFontSize(8); + $gbplot->setMarker($marker); + + $subtitle .= $current_module_strings['LBL_OPP_SIZE'].$current_user->currency_symbol.$current_module_strings['LBL_OPP_SIZE_VALUE']; + $footer->setText($subtitle); + $footer->setAlignment(IMAGE_GRAPH_ALIGN_TOP_RIGHT); + + // .. and stroke the graph + $imgMap = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => './', + 'urlpath' => '' + )); + //$imgMap = htmlspecialchars($output); + save_image_map($cache_file_name.'.map', $imgMap); + } + else { + $imgMap_fp = fopen($cache_file_name.'.map', "rb"); + $imgMap = fread($imgMap_fp, filesize($cache_file_name.'.map')); + fclose($imgMap_fp); + } + $fileModTime = filemtime($cache_file_name.'.map'); + $return = "\n$imgMap"; + $log->debug("Exiting outcome_by_month method ..."); + return $return; + } + + /** + * Creates lead_source_by_outcome pipeline image as a horizontal accumlated bar graph for multiple vtiger_users. + * param $datay- the lead source data to display in the x-axis + * param $date_start- the begin date of opps to find + * param $date_end- the end date of opps to find + * param $ids - list of assigned vtiger_users of opps to find + * param $cache_file_name - file name to write image to + * param $refresh - boolean whether to rebuild image if exists + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.. + * All Rights Reserved.. + * Contributor(s): ______________________________________.. + */ + function lead_source_by_outcome($datay=array('foo','bar'), $user_id=array('1'), $cache_file_name='a_file', $refresh=false,$width=900,$height=500){ + global $log,$current_user; + $log->debug("Entering lead_source_by_outcome(".$datay.",".$user_id.",".$cache_file_name.",".$refresh.") method ..."); + global $app_strings,$lang_crm, $current_module_strings,$charset, $tmp_dir; + global $theme; + + include_once ('Image/Graph.php'); + include_once ('Image/Canvas.php'); + + $log =& LoggerManager::getLogger('lead_source_by_outcome chart'); + // Set the basic parameters of the graph + $canvas =& Image_Canvas::factory('png', array('width' => $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + $log->debug("graph object created"); + // add a TrueType font + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 11 pixels + $font->setSize(8); + + $graph->setFont($font); + // create the plotarea layout + $title =& Image_Graph::factory('title', array('Test',10)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'axis', + 'axis', + 'horizontal' + )); + $footer =& Image_Graph::factory('title', array('Footer',8)); + $graph->add( + Image_Graph::vertical($title, + Image_Graph::vertical( + $plotarea, + $footer, + 90 + ), + 5 + ) + ); + + if (!file_exists($cache_file_name) || !file_exists($cache_file_name.'.map') || $refresh == true) { + + $log->debug("datay is:"); + $log->debug($datay); + $log->debug("user_id is: "); + $log->debug($user_id); + $log->debug("cache_file_name is: $cache_file_name"); + + $where=""; + //build the where clause for the query that matches $datay + $count = count($datay); + if ($count>0) { + $where .= " leadsource in ( "; + $ls_i = 0; + foreach ($datay as $key=>$value) { + if($ls_i != 0) $where .= ", "; + $where .= "'".addslashes($key)."'"; + $ls_i++; + } + $where .= ")"; + } + + //Now do the db queries + //query for opportunity data that matches $datay and $user + $opp = new Potentials(); + $opp_list = $opp->get_full_list("vtiger_potential.amount DESC, vtiger_potential.closingdate DESC", $where); + + //build pipeline by sales stage data + $total = 0; + $count = array(); + $sum = array(); + $other = $current_module_strings['LBL_LEAD_SOURCE_OTHER']; + if (isset($opp_list)) { + foreach ($opp_list as $record) { + //if lead source is blank, set it to the language's "none" value + if (isset($record->column_fields['leadsource']) && $record->column_fields['leadsource'] != '') { + $lead_source = $record->column_fields['leadsource']; + } + else { + $lead_source = $current_module_strings['NTC_NO_LEGENDS']; + } + + if ($record->column_fields['sales_stage'] == 'Closed Won' || $record->column_fields['sales_stage'] == 'Closed Lost') { + $sales_stage=$record->column_fields['sales_stage']; + } + else { + $sales_stage=$other; + } + + if (!isset($sum[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']])) { + $sum[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']] = 0; + } + if (isset($record->column_fields['amount']) && in_array($record->column_fields['assigned_user_id'],$user_id)) { + // Strip all non numbers from this string. + $amount = convertFromMasterCurrency(ereg_replace('[^0-9]', '', floor($record->column_fields['amount'])),$current_user->conv_rate); + $sum[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']] = $sum[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']] + $amount; + if (isset($count[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']])) { + $count[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']]++; + } + else { + $count[$lead_source][$sales_stage][$record->column_fields['assigned_user_id']] = 1; + } + $total = $total + ($amount/1000); + } + } + } + $legend = array(); + $datax = array(); + $aTargets = array(); + $aAlts = array(); + $stages = array($other,'Closed Lost', 'Closed Won'); + foreach($datay as $lead=>$translation) { + if ($lead == '') { + $lead = $current_module_strings['NTC_NO_LEGENDS']; + $translation = $current_module_strings['NTC_NO_LEGENDS']; + } + foreach($stages as $stage) { + foreach ($user_id as $the_id) { + $the_user = get_assigned_user_name($the_id); + $log->debug("stage_key is $stage"); + if (!isset($datax[$stage][$the_id])) { + $datax[$stage][$the_id] = array(); + } + if (!isset($aAlts[$stage][$the_id])) { + $aAlts[$stage][$the_id] = array(); + } + if (!isset($aTargets[$stage][$the_id])) { + $aTargets[$stage][$the_id] = array(); + } + + if (isset($sum[$lead][$stage][$the_id])) { + array_push($datax[$stage][$the_id], $sum[$lead][$stage][$the_id]/1000); + array_push($aAlts[$stage][$the_id], $the_user.' - '.$count[$lead][$stage][$the_id]." ".$current_module_strings['LBL_OPPS_OUTCOME']." $stage"); + } + else { + array_push($datax[$stage][$the_id], 0); + array_push($aAlts[$stage][$the_id], ""); + } + $cvid = getCvIdOfAll("Potentials"); + array_push($aTargets[$stage][$the_id], "index.php?module=Potentials&action=ListView&leadsource=".urlencode($lead)."&sales_stage=".urlencode($stage)."&query=true&type=dbrd&owner=".$the_user."&viewname=".$cvid); + } + } + array_push($legend,$translation); + } + + $log->debug("datax is:"); + $log->debug($datax); + $log->debug("aAlts is:"); + $log->debug($aAlts); + $log->debug("aTargets is:"); + $log->debug($aTargets); + $log->debug("sum is:"); + $log->debug($sum); + $log->debug("count is:"); + $log->debug($count); + + //now build the bar plots for each user across the sales stages + $color = array('Closed Lost'=>'FF9900','Closed Won'=>'009933', $other=>'0066CC'); + $index = 0; + $xlabels = array(); + $datasets = array(); + $fills =& Image_Graph::factory('Image_Graph_Fill_Array'); + foreach($stages as $stage) { + // Now create a bar pot + $datasets[$index] = & Image_Graph::factory('dataset'); + foreach($datax[$stage] as $ownerid=>$owner_amt) { + foreach($owner_amt as $i=>$y) { + $x = 1+2*$i; + $datasets[$index]->addPoint( + //$datay[$legend[$x]], + $x, + $y, + array( + 'url' => $aTargets[$stage][$ownerid][$i], + 'alt' => $aAlts[$stage][$ownerid][$i], + 'target' => '' + ) + ); + } + } + // Set fill colors for bars + $fills->addColor("#".$color[$stage]); + $log->debug("datax[$stage] is: "); + $log->debug($datax[$stage]); + $index++; + } + + for($i=0;$i$legend_text) { + $dataxSum = 0; + foreach($user_id as $the_id) { + foreach($stages as $stage) $dataxSum += $datax[$stage][$the_id][$legendidx]; + } + if($dataxSum > $maximum) $maximum = $dataxSum; + } + + if($theme == "blue") + { + $font_color = "#212473"; + } + else + { + $font_color = "#000000"; + } + $font->setColor($font_color); + + // Create the grouped bar plot + $gbplot = & $plotarea->addNew('bar', array($datasets, 'stacked')); + $gbplot->setFillStyle($fills); + + //You can change the width of the bars if you like + $gbplot->setBarWidth(50/count($legend),"%"); + + // Set white margin color + $graph->setBackgroundColor('#F5F5F5'); + + // Use a box around the plot area + $gbplot->setBorderColor('black'); + + // Use a gradient to fill the plot area + $gbplot->setBackground(Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL, 'white', '#E5E5E5'))); + + // Setup title + $titlestr = $current_module_strings['LBL_ALL_OPPORTUNITIES'].$current_user->currency_symbol.$total.$app_strings['LBL_THOUSANDS_SYMBOL']; + //$titlestr = $current_module_strings['LBL_ALL_OPPORTUNITIES'].$current_user->currency_symbol.$total; + $title->setText($titlestr); + + // Create the xaxis labels + $array_data =& Image_Graph::factory('Image_Graph_DataPreprocessor_Array', + array($xlabels) + ); + + // Setup X-axis + $xaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_X); + $xaxis->setDataPreprocessor($array_data); + $xaxis->forceMinimum(0); + $xaxis->forceMaximum(2*count($legend)); + $xaxis->setLabelInterval(1); + $xaxis->setTickOptions(0,0); + $xaxis->setLabelInterval(2,2); + $xaxis->setTickOptions(5,0,2); + $xaxis->setInverted(true); + + // set grid + $gridY =& $plotarea->addNew('line_grid', IMAGE_GRAPH_AXIS_Y); + $gridY->setLineColor('#E5E5E5@0.5'); + + // Add some grace to y-axis so the bars doesn't go + // all the way to the end of the plot area + $yaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_Y); + $yaxis->forceMaximum($maximum * 1.1); + $ticks = get_tickspacing($maximum); + + // Then fix the tick marks + $yaxis->setFontSize(8); + $yaxis->setAxisIntersection('max'); + $valueproc =& Image_Graph::factory('Image_Graph_DataPreprocessor_Formatted', $current_user->currency_symbol."%d"); + $yaxis->setDataPreprocessor($valueproc); + $yaxis->setLabelInterval($ticks[0]); + $yaxis->setTickOptions(-5,0); + $yaxis->setLabelInterval($ticks[1],2); + $yaxis->setTickOptions(-2,0,2); + + // eliminate zero values + $gbplot->setDataSelector(Image_Graph::factory('Image_Graph_DataSelector_NoZeros')); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setDataPreprocessor($valueproc); + $marker->setFillColor('#000000@0.0'); + $marker->setBorderColor('#000000@0.0'); + $marker->setFontColor('white'); + $marker->setFontSize(8); + $gbplot->setMarker($marker); + + // Finally setup the title + $subtitle = $current_module_strings['LBL_OPP_SIZE'].$current_user->currency_symbol.$current_module_strings['LBL_OPP_SIZE_VALUE']; + $footer->setText($subtitle); + $footer->setAlignment(IMAGE_GRAPH_ALIGN_TOP_RIGHT); + + // .. and stroke the graph + $imgMap = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => './', + 'urlpath' => '' + )); + //$imgMap = htmlspecialchars($output); + save_image_map($cache_file_name.'.map', $imgMap); + } + else { + $imgMap_fp = fopen($cache_file_name.'.map', "rb"); + $imgMap = fread($imgMap_fp, filesize($cache_file_name.'.map')); + fclose($imgMap_fp); + } + $fileModTime = filemtime($cache_file_name.'.map'); + $return = "\n$imgMap"; + $log->debug("Exiting lead_source_by_outcome method ..."); + return $return; + } + + /** + * Creates opportunity pipeline image as a horizontal accumlated bar graph for multiple vtiger_users. + * param $datax- the sales stage data to display in the x-axis + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.. + * All Rights Reserved.. + * Contributor(s): ______________________________________.. + */ + function pipeline_by_sales_stage($datax=array('foo','bar'), $date_start='2071-10-15', $date_end='2071-10-15', $user_id=array('1'), $cache_file_name='a_file', $refresh=false,$width=900,$height=500){ + global $log,$current_user; + $log->debug("Entering pipeline_by_sales_stage(".$datax.",".$date_start.",".$date_end.",".$user_id.",".$cache_file_name.",".$refresh.") method ..."); + global $app_strings,$lang_crm, $current_module_strings, $charset, $tmp_dir; + global $theme; + include_once ('Image/Graph.php'); + include_once ('Image/Canvas.php'); + + $log =& LoggerManager::getLogger('opportunity charts'); + // Set the basic parameters of the graph + + + $canvas =& Image_Canvas::factory('png', array('width' => $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + //$log->debug("graph object created"); + // add a TrueType font + //$font =& $graph->addNew('font', calculate_font_name($lang_crm)); + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 11 pixels + $font->setSize(8); + + $graph->setFont($font); + $title =& Image_Graph::factory('title', array('Test',10)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'axis', + 'axis', + 'horizontal' + )); + $footer =& Image_Graph::factory('title', array('Footer',8)); + $graph->add( + Image_Graph::vertical($title, + Image_Graph::vertical( + $plotarea, + $footer, + 90 + ), + 5 + ) + ); + $log->debug("graph object created"); + + + if (!file_exists($cache_file_name) || !file_exists($cache_file_name.'.map') || $refresh == true) { + + $log->debug("starting pipeline chart"); + $log->debug("datax is:"); + $log->debug($datax); + $log->debug("user_id is: "); + $log->debug($user_id); + $log->debug("cache_file_name is: $cache_file_name"); + + $where=""; + //build the where clause for the query that matches $datax + $count = count($datax); + if ($count>0) { + $where .= " sales_stage in ( "; + $ss_i = 0; + foreach ($datax as $key=>$value) { + if($ss_i != 0) $where .= ", "; + $where .= "'".addslashes($key)."'"; + $ss_i++; + } + $where .= ")"; + } + + //build the where clause for the query that matches $date_start and $date_end + $where .= " AND closingdate >= '$date_start' AND closingdate <= '$date_end'"; + $subtitle = $current_module_strings['LBL_DATE_RANGE']." ".getDisplayDate($date_start)." ".$current_module_strings['LBL_DATE_RANGE_TO']." ".getDisplayDate($date_end)."\n"; + + //Now do the db queries + //query for opportunity data that matches $datax and $user + $opp = new Potentials(); + $opp_list = $opp->get_full_list("vtiger_potential.amount DESC, vtiger_potential.closingdate DESC", $where); + + //build pipeline by sales stage data + $total = 0; + $count = array(); + $sum = array(); + if (isset($opp_list)) { + foreach ($opp_list as $record) { + if (!isset($sum[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']])) { + $sum[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']] = 0; + } + if (isset($record->column_fields['amount']) && in_array($record->column_fields['assigned_user_id'],$user_id)) { + // Strip all non numbers from this string. + $amount = convertFromMasterCurrency(ereg_replace('[^0-9]', '', floor($record->column_fields['amount'])),$current_user->conv_rate); + $sum[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']] = $sum[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']] + $amount; + if (isset($count[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']])) { + $count[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']]++; + } + else { + $count[$record->column_fields['sales_stage']][$record->column_fields['assigned_user_id']] = 1; + } + $total = $total + ($amount/1000); + } + } + } + $legend = array(); + $datay = array(); + $aTargets = array(); + $aAlts = array(); + foreach ($datax as $stage_key=>$stage_translation) { + foreach ($user_id as $the_id) { + $the_user = get_assigned_user_name($the_id); + if (!isset($datay[$the_id])) { + $datay[$the_id] = array(); + } + if (!isset($aAlts[$the_id])) { + $aAlts[$the_id] = array(); + } + if (!isset($aTargets[$the_id])) { + $aTargets[$the_id] = array(); + } + + if (isset($sum[$stage_key][$the_id])) { + array_push($datay[$the_id], $sum[$stage_key][$the_id]/1000); + array_push($aAlts[$the_id], $the_user.' - '.$count[$stage_key][$the_id]." ".$current_module_strings['LBL_OPPS_IN_STAGE']." $stage_translation"); + } + else { + array_push($datay[$the_id], 0); + array_push($aAlts[$the_id], ""); + } + $cvid = getCvIdOfAll("Potentials"); + array_push($aTargets[$the_id], "index.php?module=Potentials&action=ListView&sales_stage=".urlencode($stage_key)."&closingdate_start=".urlencode($date_start)."&closingdate_end=".urlencode($date_end)."&query=true&type=dbrd&owner=".$the_user."&viewname=".$cvid); + } + array_push($legend,$stage_translation); + } + + $log->debug("datay is:"); + $log->debug($datay); + $log->debug("aAlts is:"); + $log->debug($aAlts); + $log->debug("aTargets is:"); + $log->debug($aTargets); + $log->debug("sum is:"); + $log->debug($sum); + $log->debug("count is:"); + $log->debug($count); + + //now build the bar plots for each user across the sales stages + $colors = color_generator(count($user_id),'#D50100','#002222'); + $index = 0; + $datasets = array(); + $xlabels = array(); + $fills =& Image_Graph::factory('Image_Graph_Fill_Array'); + foreach($user_id as $the_id) { + // Now create a bar pot + $datasets[$index] = & Image_Graph::factory('dataset'); + foreach($datay[$the_id] as $i => $y) { + $x = 1+2*$i; + $datasets[$index]->addPoint( + $x, + $y, + array( + 'url' => $aTargets[$the_id][$i], + 'alt' => $aAlts[$the_id][$i] + ) + ); + } + + // Set fill colors for bars + $fills->addColor($colors[$index]); + + $index++; + } + for($i=0;$i$legend_text) { + $legendsum = 0; + foreach($user_id as $the_id) $legendsum += $datay[$the_id][$legendidx]; + if($legendsum > $maximum) $maximum = $legendsum; + } + // Create the grouped bar plot + $gbplot = & $plotarea->addNew('bar', array($datasets, 'stacked')); + $gbplot->setFillStyle($fills); + + //You can change the width of the bars if you like + $gbplot->setBarWidth(50/count($legend),"%"); + + + // Set white margin color + $graph->setBackgroundColor('#F5F5F5'); + + // Use a box around the plot area + $gbplot->setBorderColor('black'); + + // Use a gradient to fill the plot area + $gbplot->setBackground(Image_Graph::factory('gradient', array(IMAGE_GRAPH_GRAD_HORIZONTAL, 'white', '#E5E5E5'))); + + if($theme == "blue") + { + $font_color = "#212473"; + } + else + { + $font_color = "#000000"; + } + $font->setColor($font_color); + + // Setup title + $titlestr = $current_module_strings['LBL_TOTAL_PIPELINE'].$current_user->currency_symbol.$total.$app_strings['LBL_THOUSANDS_SYMBOL']; + //$titlestr = $current_module_strings['LBL_TOTAL_PIPELINE'].$current_user->currency_symbol.$total; + $title->setText($titlestr); + + // Create the xaxis labels + $array_data =& Image_Graph::factory('Image_Graph_DataPreprocessor_Array', + array($xlabels) + ); + + + // Setup X-axis + $xaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_X); + $xaxis->setDataPreprocessor($array_data); + $xaxis->forceMinimum(0); + $xaxis->forceMaximum(2*count($legend)); + $xaxis->setLabelInterval(1); + $xaxis->setTickOptions(0,0); + $xaxis->setLabelInterval(2,2); + $xaxis->setTickOptions(5,0,2); + $xaxis->setInverted(true); + + // Setup Y-axis + $yaxis =& $plotarea->getAxis(IMAGE_GRAPH_AXIS_Y); + $yaxis->setFontSize(8); + $yaxis->setAxisIntersection('max'); + + // Add some grace to y-axis so the bars doesn't go + // all the way to the end of the plot area + $yaxis->forceMaximum($maximum * 1.1); + $ticks = get_tickspacing($maximum); + + // set grid + $gridY =& $plotarea->addNew('line_grid', IMAGE_GRAPH_AXIS_Y); + $gridY->setLineColor('#E5E5E5@0.5'); + + // First make the labels look right + $valueproc =& Image_Graph::factory('Image_Graph_DataPreprocessor_Formatted', $current_user->currency_symbol."%d"); + $yaxis->setDataPreprocessor($valueproc); + $yaxis->setLabelInterval($ticks[0]); + $yaxis->setTickOptions(-5,0); + $yaxis->setLabelInterval($ticks[1],2); + $yaxis->setTickOptions(-2,0,2); + + // eliminate zero values + $gbplot->setDataSelector(Image_Graph::factory('Image_Graph_DataSelector_NoZeros')); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setDataPreprocessor($valueproc); + $marker->setFillColor('000000@0.0'); + $marker->setBorderColor('000000@0.0'); + $marker->setFontColor('white'); + $marker->setFontSize(8); + $gbplot->setMarker($marker); + + // Finally setup the title + + $subtitle .= $current_module_strings['LBL_OPP_SIZE'].$current_user->currency_symbol.$current_module_strings['LBL_OPP_SIZE_VALUE']; + $footer->setText($subtitle); + $footer->setAlignment(IMAGE_GRAPH_ALIGN_TOP_RIGHT); + + // .. and stroke the graph + $imgMap = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => './', + 'urlpath' => '' + )); + //$imgMap = $graph->GetHTMLImageMap('pipeline'); + save_image_map($cache_file_name.'.map', $imgMap); + } + else { + $imgMap_fp = fopen($cache_file_name.'.map', "rb"); + $imgMap = fread($imgMap_fp, filesize($cache_file_name.'.map')); + fclose($imgMap_fp); + } + $fileModTime = filemtime($cache_file_name.'.map'); + $return = "\n$imgMap"; + $log->debug("Exiting pipeline_by_sales_stage method ..."); + return $return; + } + + /** + * Creates pie chart image of opportunities by lead_source. + * param $datax- the sales stage data to display in the x-axis + * param $datay- the sum of opportunity amounts for each opportunity in each sales stage + * to display in the y-axis + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.. + * All Rights Reserved.. + * Contributor(s): ______________________________________.. + */ + function pipeline_by_lead_source($legends=array('foo','bar'), $user_id=array('1'), $cache_file_name='a_file', $refresh=true,$width=900,$height=500){ + global $log,$current_user; + $log->debug("Entering pipeline_by_lead_source(".$legends.") method ..."); + global $app_strings,$lang_crm, $current_module_strings, $log, $charset, $tmp_dir; + global $theme; + + include_once ('Image/Graph.php'); + include_once ('Image/Canvas.php'); + + $font = calculate_font_name($lang_crm); + if (!file_exists($cache_file_name) || !file_exists($cache_file_name.'.map') || $refresh == true) { + $log =& LoggerManager::getLogger('opportunity charts'); + $log->debug("starting pipeline chart"); + $log->debug("legends is:"); + $log->debug($legends); + $log->debug("user_id is: "); + $log->debug($user_id); + $log->debug("cache_file_name is: $cache_file_name"); + + //Now do the db queries + //query for opportunity data that matches $legends and $user + $where=""; + //build the where clause for the query that matches $datax + $count = count($legends); + if ($count>0) { + $where .= " leadsource in ( "; + $ls_i = 0; + foreach ($legends as $key=>$value) { + if($ls_i != 0) $where .= ", "; + $where .= "'".addslashes($key)."'"; + $ls_i++; + } + $where .= ")"; + } + + $opp = new Potentials(); + $opp_list = $opp->get_full_list("vtiger_potential.amount DESC, vtiger_potential.closingdate DESC", $where); + + //build pipeline by lead source data + $total = 0; + $count = array(); + $sum = array(); + if (isset($opp_list)) { + foreach ($opp_list as $record) { + if (!isset($sum[$record->column_fields['leadsource']])) $sum[$record->column_fields['leadsource']] = 0; + if (isset($record->column_fields['amount']) && isset($record->column_fields['leadsource'])) { + // Strip all non numbers from this string. + $amount = convertFromMasterCurrency(ereg_replace('[^0-9]', '', floor($record->column_fields['amount'])),$current_user->conv_rate); + $sum[$record->column_fields['leadsource']] = $sum[$record->column_fields['leadsource']] + ($amount/1000); + if (isset($count[$record->column_fields['leadsource']])) $count[$record->column_fields['leadsource']]++; + else $count[$record->column_fields['leadsource']] = 1; + $total = $total + ($amount/1000); + } + } + } + + $visible_legends = array(); + $data= array(); + $aTargets = array(); + $aAlts = array(); + foreach ($legends as $lead_source_key=>$lead_source_translation) { + if (isset($sum[$lead_source_key])) + { + array_push($data, $sum[$lead_source_key]); + if($lead_source_key != '') + { + array_push($visible_legends, $lead_source_translation); + } + else + { + // put none in if the vtiger_field is blank. + array_push($visible_legends, $current_module_strings['NTC_NO_LEGENDS']); + } + $cvid = getCvIdOfAll("Potentials"); + array_push($aTargets, "index.php?module=Potentials&action=ListView&leadsource=".urlencode($lead_source_key)."&query=true&type=dbrd&viewname=".$cvid); + array_push($aAlts, $count[$lead_source_key]." ".$current_module_strings['LBL_OPPS_IN_LEAD_SOURCE']." $lead_source_translation "); + } + } + + $log->debug("sum is:"); + $log->debug($sum); + $log->debug("count is:"); + $log->debug($count); + $log->debug("total is: $total"); + if ($total == 0) { +$log->debug("Exiting pipeline_by_lead_source method ..."); + return ($current_module_strings['ERR_NO_OPPS']); + } + + if($theme == "blue") + { + $font_color = "#212473"; + } + else + { + $font_color = "#000000"; + } + + + $canvas =& Image_Canvas::factory('png', array('width' => $width, 'height' => $height, 'usemap' => true)); + $imagemap = $canvas->getImageMap(); + $graph =& Image_Graph::factory('graph', $canvas); + + $font =& $graph->addNew('font', calculate_font_name($lang_crm)); + // set the font size to 11 pixels + $font->setSize(8); + $font->setColor($font_color); + + $graph->setFont($font); + // create the plotarea layout + $title =& Image_Graph::factory('title', array('Test',10)); + $plotarea =& Image_Graph::factory('plotarea',array( + 'category', + 'axis' + )); + $footer =& Image_Graph::factory('title', array('Footer',8)); + $graph->add( + Image_Graph::vertical($title, + Image_Graph::vertical( + $plotarea, + $footer, + 90 + ), + 5 + ) + ); + + // Generate colours + $colors = color_generator(count($visible_legends),'#33CCFF','#3322FF'); + $index = 0; + $dataset = & Image_Graph::factory('dataset'); + $fills =& Image_Graph::factory('Image_Graph_Fill_Array'); + foreach($visible_legends as $legend) { + $dataset->addPoint( + $legend, + $data[$index], + array( + 'url' => $aTargets[$index], + 'alt' => $aAlts[$index] + ) + ); + $fills->addColor($colors[$index]); + $log->debug('point ='.$legend.','.$data[$index]); + + $index++; + } + + // create the pie chart and associate the filling colours + $gbplot = & $plotarea->addNew('pie', $dataset); + $plotarea->hideAxis(); + $gbplot->setFillStyle($fills); + + // Setup title + $titlestr = $current_module_strings['LBL_TOTAL_PIPELINE'].$current_user->currency_symbol.$total.$app_strings['LBL_THOUSANDS_SYMBOL']; + //$titlestr = $current_module_strings['LBL_TOTAL_PIPELINE'].$current_user->currency_symbol.$total; + + $title->setText($titlestr); + + // format the data values + $valueproc =& Image_Graph::factory('Image_Graph_DataPreprocessor_Formatted', $current_user->currency_symbol."%d"); + + // set markers + $marker =& $graph->addNew('value_marker', IMAGE_GRAPH_VALUE_Y); + $marker->setDataPreprocessor($valueproc); + $marker->setFillColor('#FFFFFF'); + $marker->setBorderColor($font_color); + $marker->setFontColor($font_color); + $marker->setFontSize(8); + $pointingMarker =& $graph->addNew('Image_Graph_Marker_Pointing_Angular', array(20, &$marker)); + $gbplot->setMarker($pointingMarker); + + // set legend + $legend_box =& $plotarea->addNew('legend'); + $legend_box->setPadding(array('top'=>20,'bottom'=>0,'left'=>0,'right'=>0)); + $legend_box->setFillColor('#F5F5F5'); + $legend_box->showShadow(); + + $subtitle = $current_module_strings['LBL_OPP_SIZE'].$current_user->currency_symbol.$current_module_strings['LBL_OPP_SIZE_VALUE']; + $footer->setText($subtitle); + $footer->setAlignment(IMAGE_GRAPH_ALIGN_TOP_LEFT); + + $imgMap = $graph->done( + array( + 'tohtml' => true, + 'border' => 0, + 'filename' => $cache_file_name, + 'filepath' => './', + 'urlpath' => '' + )); + //$imgMap = htmlspecialchars($output); + save_image_map($cache_file_name.'.map', $imgMap); + } + else { + $imgMap_fp = fopen($cache_file_name.'.map', "rb"); + $imgMap = fread($imgMap_fp, filesize($cache_file_name.'.map')); + fclose($imgMap_fp); + } + $fileModTime = filemtime($cache_file_name.'.map'); + $return = "\n$imgMap"; + $log->debug("Exiting pipeline_by_lead_source method ..."); + return $return; + + } + +} + + +/** + * Creates a file with the image map + * param $filename - file name to save to + * param $image_map - image map string to save + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function save_image_map($filename,$image_map) +{ + global $log; + $log->debug("Entering save_image_map(".$filename.",".$image_map.") method ..."); + // save the image map to file + $log =& LoggerManager::getLogger('save_image_file'); + + if (!$handle = fopen($filename, 'w')) { + $log->debug("Cannot open file ($filename)"); + $log->debug("Exiting save_image_map method ..."); + return; + } + + // Write $somecontent to our opened file. + if (fwrite($handle, $image_map) === FALSE) { + $log->debug("Cannot write to file ($filename)"); + $log->debug("Exiting save_image_map method ..."); + return false; + } + + $log->debug("Success, wrote ($image_map) to file ($filename)"); + + fclose($handle); + $log->debug("Exiting save_image_map method ..."); + return true; + +} + +// retrieve the translated strings. +$app_strings = return_application_language($current_language); + +if(isset($app_strings['LBL_CHARSET'])) +{ + $charset = $app_strings['LBL_CHARSET']; +} +else +{ + $charset = $default_charset; +} + + +?> diff --git a/oss/vtiger/trunk/modules/Potentials/CustomView.php b/oss/vtiger/trunk/modules/Potentials/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/Delete.php b/oss/vtiger/trunk/modules/Potentials/Delete.php new file mode 100644 index 00000000..e9046f54 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Delete.php @@ -0,0 +1,35 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/DetailView.php b/oss/vtiger/trunk/modules/Potentials/DetailView.php new file mode 100644 index 00000000..29e3d383 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/DetailView.php @@ -0,0 +1,128 @@ +retrieve_entity_info($_REQUEST['record'],"Potentials"); + $focus->id = $_REQUEST['record']; + $focus->name=$focus->column_fields['potentialname']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Potential detail view"); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $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 + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); + +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("SINGLE_MOD", 'Opportunity'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + + +if(isPermitted("Potentials","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); +if(isPermitted("Invoice","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("CONVERTINVOICE","permitted"); +if(isPermitted("Potentials","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$tabid = getTabid("Potentials"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$smarty->assign("CONVERTMODE",'potentoinvoice'); +$smarty->assign("MODULE","Potentials"); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +$smarty->assign("SinglePane_View", $singlepane_view); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("DetailView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/DetailViewAjax.php b/oss/vtiger/trunk/modules/Potentials/DetailViewAjax.php new file mode 100644 index 00000000..0ab8965d --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/DetailViewAjax.php @@ -0,0 +1,51 @@ +retrieve_entity_info($crmid,"Potentials"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $_REQUEST[$fieldname] = $fieldvalue; + if($fieldname == 'amount')//amount converted to dollar value while saving + { + $modObj->column_fields[$fieldname] = getConvertedPrice($fieldvalue); + } + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Potentials"); + sendNotificationToOwner('Potentials',&$modObj); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/EditView.php b/oss/vtiger/trunk/modules/Potentials/EditView.php new file mode 100644 index 00000000..aaf62107 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/EditView.php @@ -0,0 +1,164 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if(isset($_REQUEST['record']) && $_REQUEST['record'] != ''){ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Potentials"); + $focus->name=$focus->column_fields['potentialname']; +} + +//adding support for uitype 10 +if(!empty($_REQUEST['contact_id'])){ + $focus->column_fields['related_to'] = $_REQUEST['contact_id']; +}elseif(!empty($_REQUEST['account_id'])){ + $focus->column_fields['related_to'] = $_REQUEST['account_id']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['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,$mode,$focus->column_fields)); +else +{ + $smarty->assign("BASBLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS')); +} +$smarty->assign("OP_MODE",$disp_view); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +//needed when creating a new opportunity with a default vtiger_account value passed in +if (isset($_REQUEST['accountname']) && is_null($focus->accountname)) { + $focus->accountname = $_REQUEST['accountname']; +} +if (isset($_REQUEST['accountid']) && is_null($focus->related_to)) { + $focus->related_to = $_REQUEST['accountid']; +} +if (isset($_REQUEST['contactid']) && is_null($focus->related_to)) { + $focus->related_to = $_REQUEST['contactid']; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Potential detail view"); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); + +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} + + + +// Unimplemented until jscalendar language vtiger_files are fixed +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Potential'); + + + $tabid = getTabid("Potentials"); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data = split_validationdataArray($validationData); + + $smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); + $smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); + $smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +//fix for potential duplicate header +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +if($focus->mode == 'edit') +$smarty->display("salesEditView.tpl"); +else +$smarty->display("CreateView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/ExportRecords.php b/oss/vtiger/trunk/modules/Potentials/ExportRecords.php new file mode 100644 index 00000000..dcbf10eb --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/ExportRecords.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/Potentials/FindDuplicateRecords.php new file mode 100644 index 00000000..a1ff9757 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/FindDuplicateRecords.php @@ -0,0 +1,106 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    + $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/Import.php b/oss/vtiger/trunk/modules/Potentials/Import.php new file mode 100644 index 00000000..71867d63 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Import.php @@ -0,0 +1,45 @@ + + diff --git a/oss/vtiger/trunk/modules/Potentials/ListView.php b/oss/vtiger/trunk/modules/Potentials/ListView.php new file mode 100644 index 00000000..536b6700 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/ListView.php @@ -0,0 +1,261 @@ +initSortbyField('Potentials'); +// END +$smarty = new vtigerCRM_Smarty(); +$other_text = Array(); + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to Change/Delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['POTENTIALS_ORDER_BY'] = $order_by; +$_SESSION['POTENTIALS_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); +} + +//<<<>>>>>> +$oCustomView = new CustomView("Potentials"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//<<<<>>>> +$smarty->assign("CHANGE_OWNER",getUserslist()); +$smarty->assign("CHANGE_GROUP_OWNER",getGroupslist()); +if(isPermitted('Potentials','Delete','') == 'yes') +{ + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +} +if(isPermitted('Potentials','EditView','') == 'yes') +{ + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; + $other_text['c_owner'] = $app_strings[LBL_CHANGE_OWNER]; +} + +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Potentials"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Potentials"); +}else +{ + $list_query = getListQuery("Potentials"); +} +//<<<<<<<>>>>>>>> +if(isset($where) && $where != '') +{ + if(isset($_REQUEST['from_dashboard']) && $_REQUEST['from_dashboard'] == 'true') + $list_query .= " AND vtiger_potential.sales_stage = '".$mod_strings['Closed Won']."' AND ".$where; + elseif(isset($_REQUEST['from_homepagedb']) && $_REQUEST['from_homepagedb'] == 'true') + $list_query .= " AND vtiger_potential.sales_stage not in( '".$mod_strings['Closed Won']."' , '".$mod_strings['Closed Lost']."' )AND ".$where; + else + $list_query .= " AND ".$where; + + $_SESSION['export_where'] = $where; +} +else + unset($_SESSION['export_where']); + + +if(isset($order_by) && $order_by != '') +{ + if($order_by == 'smownerid') + { + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY user_name'; + $list_query .= ' ORDER BY user_name '.$sorder; + } + else + { + $tablename = getTableNameForField('Potentials',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY '.$tablename.$order_by; + + $list_query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } +} +if($viewid ==0) +{ + echo "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_PERMISSION]
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + exit; +} +//Constructing the list view + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Opportunity'); +$smarty->assign("BUTTONS",$other_text); +$smarty->assign("CATEGORY",$category); + +//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); + +//Retreive the List View Table Header +if($viewid !='') +$url_string .="&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"Potentials",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search=getSearchListHeaderValues($focus,"Potentials",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER", $listview_header_search); + + +$listview_entries = getListViewEntries($focus,"Potentials",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); +$smarty->assign("LISTENTITY", $listview_entries); + +$smarty->assign("AVALABLE_FIELDS", getMergeFields($currentModule,"available_fields")); +$smarty->assign("FIELDS_TO_MERGE", getMergeFields($currentModule,"fileds_to_merge")); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Potentials","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','potentialname','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($currentModule); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("SELECT_SCRIPT", $view_script); + +$check_button = Button_Check($currentModule); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/ListViewPagging.php b/oss/vtiger/trunk/modules/Potentials/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/ListViewTop.php b/oss/vtiger/trunk/modules/Potentials/ListViewTop.php new file mode 100644 index 00000000..ab30ab24 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/ListViewTop.php @@ -0,0 +1,98 @@ +$title,'Header'=>$listview_header,'Entries'=>$listview_entries) where as listview_header and listview_entries are arrays of header and entity values which are returned from function getListViewHeader and getListViewEntries +*/ +function getTopPotentials($maxval,$calCnt) +{ + $log = LoggerManager::getLogger('top opportunity_list'); + $log->debug("Entering getTopPotentials() method ..."); + require_once("data/Tracker.php"); + require_once('modules/Potentials/Potentials.php'); + require_once('include/logging.php'); + require_once('include/ListView/ListView.php'); + + global $app_strings; + global $adb; + global $current_language; + global $current_user; + $current_module_strings = return_module_language($current_language, "Potentials"); + + $title=array(); + $title[]='myTopOpenPotentials.gif'; + $title[]=$current_module_strings['LBL_TOP_OPPORTUNITIES']; + $title[]='home_mypot'; + $where = "AND vtiger_potential.sales_stage not in ('Closed Won','Closed Lost','".$current_module_strings['Closed Won']."','".$current_module_strings['Closed Lost']."') AND vtiger_crmentity.smownerid='".$current_user->id."'"; + $header=array(); + $header[]=$current_module_strings['LBL_LIST_OPPORTUNITY_NAME']; + //$header[]=$current_module_strings['LBL_LIST_ACCOUNT_NAME']; + $currencyid=fetchCurrency($current_user->id); + $rate_symbol = getCurrencySymbolandCRate($currencyid); + $rate = $rate_symbol['rate']; + $curr_symbol = $rate_symbol['symbol']; + $header[]=$current_module_strings['LBL_LIST_AMOUNT'].'('.$curr_symbol.')'; + $list_query = getListQuery("Potentials",$where); + $list_query .=" ORDER BY amount DESC"; + + $list_query .=" LIMIT " . $adb->sql_escape_string($maxval); + + if($calCnt == 'calculateCnt') { + $list_result_rows = $adb->query(mkCountQuery($list_query)); + return $adb->query_result($list_result_rows, 0, 'count'); + } + + $list_result = $adb->query($list_query); + + $open_potentials_list = array(); + $noofrows = $adb->num_rows($list_result); + + $entries=array(); + if ($noofrows) { + for($i=0;$i<$noofrows;$i++) + { + $open_potentials_list[] = Array('name' => $adb->query_result($list_result,$i,'potentialname'), + 'id' => $adb->query_result($list_result,$i,'potentialid'), + 'amount' => $adb->query_result($list_result,$i,'amount'), + ); + $potentialid=$adb->query_result($list_result,$i,'potentialid'); + $potentialname = $adb->query_result($list_result,$i,'potentialname'); + $Top_Potential = (strlen($potentialname) > 20) ? (substr($potentialname,0,20).'...') : $potentialname; + $value=array(); + $value[]=''.$Top_Potential.''; + + $value[]=convertFromDollar($adb->query_result($list_result,$i,'amount'),$rate); + $entries[$potentialid]=$value; + } + } + + $search_qry = "&query=true&Fields0=vtiger_crmentity.smownerid&Condition0=is&Srch_value0=".$current_user->column_fields['user_name']."&Fields1=vtiger_potential.sales_stage&Condition1=dcts&Srch_value1=closed&searchtype=advance&search_cnt=2&matchtype=all"; + + $values=Array('ModuleName'=>'Potentials','Title'=>$title,'Header'=>$header,'Entries'=>$entries,'search_qry'=>$search_qry); + + if ( ($display_empty_home_blocks && count($open_potentials_list) == 0 ) || (count($open_potentials_list)>0) ) + { + $log->debug("Exiting getTopPotentials method ..."); + return $values; + } +} +?> diff --git a/oss/vtiger/trunk/modules/Potentials/MassEdit.php b/oss/vtiger/trunk/modules/Potentials/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/MassEditSave.php b/oss/vtiger/trunk/modules/Potentials/MassEditSave.php new file mode 100644 index 00000000..0e1f2a6f --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/Popup.php b/oss/vtiger/trunk/modules/Potentials/Popup.php new file mode 100644 index 00000000..491b56b5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Popup.php @@ -0,0 +1,17 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/Potentials.js b/oss/vtiger/trunk/modules/Potentials/Potentials.js new file mode 100644 index 00000000..9f2bd778 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Potentials.js @@ -0,0 +1,89 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + + +document.write(" +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Potentials/QuickCreate.php b/oss/vtiger/trunk/modules/Potentials/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/Save.php b/oss/vtiger/trunk/modules/Potentials/Save.php new file mode 100644 index 00000000..72d2369b --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Save.php @@ -0,0 +1,74 @@ +id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; +$curr_symbol= $rate_symbol['symbol']; + +setObjectValuesFromRequest($focus); + +if(isset($_REQUEST['amount'])) +{ + $value = convertToDollar($_REQUEST['amount'],$rate); + $focus->column_fields['amount'] = $value; +} + +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("Potentials"); +$pot_id = $return_id = $focus->id; + +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Potentials"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +$local_log->debug("Saved record with id of ".$return_id); + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + +//Added to send mail to the vtiger_potential-owner about the Potential +if($focus->mode == 'edit') { // For non-edit mode sending mail is handled during Save + $status = sendNotificationToOwner('Potentials',$focus); +} + +header("Location: index.php?action=$return_action&module=$return_module&parenttab=$parenttab&record=$return_id&pot_id=$pot_id&viewname=$return_viewname&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/Settings.php b/oss/vtiger/trunk/modules/Potentials/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/TagCloud.php b/oss/vtiger/trunk/modules/Potentials/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/UnifiedSearch.php b/oss/vtiger/trunk/modules/Potentials/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Potentials/index.php b/oss/vtiger/trunk/modules/Potentials/index.php new file mode 100644 index 00000000..c31a5646 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/index.php @@ -0,0 +1,30 @@ + diff --git a/oss/vtiger/trunk/modules/Potentials/language/en_us.lang.php b/oss/vtiger/trunk/modules/Potentials/language/en_us.lang.php new file mode 100644 index 00000000..656cf4e6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/language/en_us.lang.php @@ -0,0 +1,156 @@ +'Potentials', +'LBL_MODULE_TITLE'=>'Potentials: Home', +'LBL_SEARCH_FORM_TITLE'=>'Potential Search', +'LBL_LIST_FORM_TITLE'=>'Potential List', +'LBL_OPPORTUNITY_NAME'=>'Potential Name:', +'LBL_OPPORTUNITY'=>'Potential:', +'LBL_NAME'=>'Potential Name', +'LBL_INVITEE'=>'Contacts', +'LBL_LIST_OPPORTUNITY_NAME'=>'Potential', +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_PRODUCT_NAME'=>'Product Name', +'LBL_LIST_AMOUNT'=>'Amount', +'LBL_LIST_DATE_CLOSED'=>'Expected Close', +'LBL_LIST_SALES_STAGE'=>'Sales Stage', + +'LBL_OPPORTUNITY_NAME'=>'Potential Name:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_AMOUNT'=>'Amount:', +'LBL_DATE_CLOSED'=>'Expected Close Date:', +'LBL_TYPE'=>'Type:', +'LBL_NEXT_STEP'=>'Next Step:', +'LBL_LEAD_SOURCE'=>'Lead Source:', +'LBL_SALES_STAGE'=>'Sales Stage:', +'LBL_PROBABILITY'=>'Probability (%):', +'LBL_DESCRIPTION'=>'Description:', +'LBL_OPPORTUNITY_INFORMATION'=>'Potential Information:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information:', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', + +'LBL_NEW_FORM_TITLE'=>'New Potential', + +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the opportunity.", +'LBL_TOP_OPPORTUNITIES'=>"My Top Open Potentials", + +'NTC_REMOVE_OPP_CONFIRMATION'=>'Are you sure you want to remove this contact from this opportunity?', + +'NTC_NONE_SCHEDULED'=>'None scheduled.', + +'LBL_SELECT_OPPOPTUNITY'=>'Select Potential', +'LBL_GENERAL_INFORMATION'=>'General Information', + + + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_NOTE'=>'New Document', +'LBL_NOTE_TITLE'=>'Documents', + +'LBL_NEW_ATTACHMENT'=>'New Attachment', +'LBL_ATTACHMENT_TITLE'=>'Attachments', + +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_WON'=>'Won', +'LBL_LOST'=>'Lost', +'LBL_VALUE_PROPOSITION'=>'Value Proposition', +'LBL_PROSPECTING'=>'Prospecting', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Potential Tools', +//Added for 4GA +'Potential Name'=>'Potential Name', +'Amount'=>'Amount', +'Account Name'=>'Account Name', +'Currency'=>'Currency', +'Expected Close Date'=>'Expected Close Date', +'Opportunity Type'=>'Opportunity Type', +'Type'=>'Type', +'Next Step'=>'Next Step', +'Lead Source'=>'Lead Source', +'Sales Stage'=>'Sales Stage', +'Assigned To'=>'Assigned To', +'Probability'=>'Probability (%)', +'Campaign Source'=>'Campaign Source', +'Description'=>'Description', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +//Added for 4.2 Release -- CustomView +'Potential'=>'Potential', +'Expected Close'=>'Expected Close', + +//Added for Existing Picklist Strings + +'Prospecting'=>'Prospecting', +'Qualification'=>'Qualification', +'Needs Analysis'=>'Needs Analysis', +'Value Proposition'=>'Value Proposition', +'Id. Decision Makers'=>'Id. Decision Makers', +'Perception Analysis'=>'Perception Analysis', +'Proposal/Price Quote'=>'Proposal/Price Quote', +'Negotiation/Review'=>'Negotiation/Review', +'Closed Won'=>'Closed Won', +'Closed Lost'=>'Closed Lost', + +'Cold Call'=>'Cold Call', +'Existing Customer'=>'Existing Customer', +'Self Generated'=>'Self Generated', +'Employee'=>'Employee', +'Partner'=>'Partner', +'Public Relations'=>'Public Relations', +'Direct Mail'=>'Direct Mail', +'Conference'=>'Conference', +'Trade Show'=>'Trade Show', +'Web Site'=>'Web Site', +'Word of mouth'=>'Word of mouth', +'Other'=>'Other', + +'--None--'=>'--None--', +'Existing Business'=>'Existing Business', +'New Business'=>'New Business', + +// Added after 5.0.4 GA + +// Module Sequence Numbering +'Potential No' => 'Potential No', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Potentials/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Potentials/language/zh_cn.lang.php new file mode 100644 index 00000000..84579115 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/language/zh_cn.lang.php @@ -0,0 +1,158 @@ + '业务', + 'LBL_MODULE_TITLE' => '业务: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻业务', + 'LBL_LIST_FORM_TITLE' => '业务列表', + //'LBL_OPPORTUNITY_NAME' => '业务名称:', + 'LBL_OPPORTUNITY_NAME' => '机会名称:', + //'LBL_OPPORTUNITY' => '业务:', + 'LBL_OPPORTUNITY' => '机会:', + 'LBL_NAME' => '业务名称', + 'LBL_INVITEE' => '联系人', + 'LBL_LIST_OPPORTUNITY_NAME' => '可能性', + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_PRODUCT_NAME' => '业务类型', + 'LBL_LIST_AMOUNT' => '合计', + 'LBL_LIST_DATE_CLOSED' => '预期结束', + 'LBL_LIST_SALES_STAGE' => '销售策略', + +'LBL_OPPORTUNITY_NAME'=>'潜在客户名称:', + 'LBL_ACCOUNT_NAME' => '客户名称:', +'LBL_AMOUNT' => '合计:', + 'LBL_DATE_CLOSED' => '预期结束日期:', + 'LBL_TYPE' => '类型:', + 'LBL_NEXT_STEP' => '下一步:', + 'LBL_LEAD_SOURCE' => '接触来源:', + 'LBL_SALES_STAGE' => '客服场景:', + 'LBL_PROBABILITY' => '可能性 (%):', + 'LBL_DESCRIPTION' => '描述:', + 'LBL_OPPORTUNITY_INFORMATION' => '业务信息:', + 'LBL_DESCRIPTION_INFORMATION' => '描述信息:', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + + 'LBL_NEW_FORM_TITLE' => '新增业务', + + 'ERR_DELETE_RECORD' => '删除业务必须指定记录编号.', + 'LBL_TOP_OPPORTUNITIES' => '最佳业务', + +'NTC_REMOVE_OPP_CONFIRMATION' => '您确定要从业务中删除这位联系人?', + + 'NTC_NONE_SCHEDULED' => '未安排行程', + +'LBL_SELECT_OPPOPTUNITY' => '选择业务', + 'LBL_GENERAL_INFORMATION' => '一般信息', + + + +//for v4 release added + 'LBL_NEW_POTENTIAL' => '新增业务', + 'LBL_POTENTIAL_TITLE' => '业务', + +'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '电子邮件', + 'LBL_NEW_NOTE' => '新增备忘录', + 'LBL_NOTE_TITLE' => '备忘录', + + 'LBL_NEW_ATTACHMENT' => '新增附件', + 'LBL_ATTACHMENT_TITLE' => '附件', + + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_CONTACT_TITLE' => '联系人', + +//Added vtiger_fields after RC1 - Release + 'LBL_ALL' => '全部', + 'LBL_WON' => '获得', + 'LBL_LOST' => '失去', + 'LBL_VALUE_PROPOSITION' => '价值建议', + 'LBL_PROSPECTING' => '预期值', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '业务编辑器', +//Added for 4GA +'Potential Name' => '业务名称', + 'Amount' => '合计', + 'Account Name' => '客户名称', + 'Currency' => '货币', +'Expected Close Date' => '预定结束日期', + 'Opportunity Type' => '机会类型', + 'Type' => '类型', + 'Next Step' => '下一步', + 'Lead Source' => '接触来源', + 'Sales Stage' => '销售策略', +'Assigned To' => '负责人', + 'Probability' => '可能性 (%)', + 'Campaign Source' => '活动来源', +'Description' => '描述', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', +//Added for 4.2 Release -- CustomView + 'Potential' => '业务', + 'Expected Close' => '预期结案日期', + +//Added for Existing Picklist Strings + + 'Prospecting' => '潜在客户', + 'Qualification' => '具有资格', + 'Needs Analysis' => '需要分析', + 'Value Proposition' => '价值主张', + 'Id. Decision Makers' => '决策者', + 'Perception Analysis' => '感觉分析', + 'Proposal/Price Quote' => '建议书/报价单', + 'Negotiation/Review' => '交涉/审阅', + 'Closed Won' => '成功结案', + 'Closed Lost' => '失败结案', + + 'Cold Call' => '陌生拜访', + 'Existing Customer' => '既有客户', + 'Self Generated' => '自动产生', + 'Employee' => '员工', + 'Partner' => '伙伴', + 'Public Relations' => '公众关系', + 'Direct Mail' => '邮件营销', + 'Conference' => '研讨会', + 'Trade Show' => '贸易展览', + 'Web Site' => '网站', + 'Word of mouth' => '朋友介绍', + 'Other' => '其它', + + '--None--' => '-- 无 --', + 'Existing Business' => '已有商务往来', + 'New Business' => '新客户', + +// Added after 5.0.4 GA + +// Module Sequence Numbering +'Potential No' => 'Potential No', +// END + +); + +?> diff --git a/oss/vtiger/trunk/modules/Potentials/updateRelations.php b/oss/vtiger/trunk/modules/Potentials/updateRelations.php new file mode 100644 index 00000000..040b46d0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Potentials/updateRelations.php @@ -0,0 +1,55 @@ +pquery($sql, array($id, $forCRMRecord)); + } elseif($dest_mod == 'Products') {//when we select product from potential related list + $sql = "insert into vtiger_seproductsrel values (?,?,?)"; + $adb->pquery($sql, array($forCRMRecord, $id,'Potentials')); + } elseif($dest_mod == 'Documents') { + $sql = "insert into vtiger_senotesrel values (?,?)"; + $adb->pquery($sql, array($forCRMRecord, $id)); + } else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/CallRelatedList.php b/oss/vtiger/trunk/modules/PriceBooks/CallRelatedList.php new file mode 100644 index 00000000..ee6ff619 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/CallRelatedList.php @@ -0,0 +1,80 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['bookname']; + $log->debug("PriceBook id =".$focus->id); + $log->debug("PriceBook Name =".$focus->name); + } + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + + $related_array=getRelatedLists($currentModule,$focus); + + global $mod_strings; + global $app_strings; + global $theme, $currentModule; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if(isset($focus->name)) + $smarty->assign("NAME", $focus->name); + $smarty->assign("CATEGORY",$category); + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("ID",$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 + + $smarty->assign("CURRENCY_ID",$focus->column_fields['currency_id']); + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("SINGLE_MOD",$app_strings['PriceBook']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("RelatedListContents.tpl"); + else + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/CustomView.php b/oss/vtiger/trunk/modules/PriceBooks/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/Delete.php b/oss/vtiger/trunk/modules/PriceBooks/Delete.php new file mode 100644 index 00000000..0148d6e2 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/Delete.php @@ -0,0 +1,51 @@ +pquery("delete from vtiger_pricebookproductrel where pricebookid=? and productid=?", array($pricebookid, $productid)); +} + +if($_REQUEST['module'] == $_REQUEST['return_module']) + $focus->mark_deleted($_REQUEST['record']); + +$parenttab = getParentTab(); + +header("Location: index.php?module=".vtlib_purify($_REQUEST['return_module'])."&action=".vtlib_purify($_REQUEST['return_action'])."&record=".vtlib_purify($_REQUEST['return_id'])."&parenttab=$parenttab$url"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/DetailView.php b/oss/vtiger/trunk/modules/PriceBooks/DetailView.php new file mode 100644 index 00000000..76a72447 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/DetailView.php @@ -0,0 +1,107 @@ +retrieve_entity_info($_REQUEST['record'],"PriceBooks"); + $focus->id = $_REQUEST['record']; + $focus->name = $focus->column_fields['bookname']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; +} + +global $app_strings,$mod_strings,$theme,$currentModule,$singlepane_view; + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); + +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("CUSTOMFIELD", $cust_fld); + +if(isPermitted("PriceBooks","PriceBookEditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +if(isPermitted("PriceBooks","DeletePriceBook",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +// 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 + +$smarty->assign("NAME", $focus->name); + + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$tabid = getTabid("PriceBooks"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$smarty->assign("MODULE", $currentModule); +$smarty->assign("SINGLE_MOD", 'PriceBook'); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +$smarty->assign("SinglePane_View", $singlepane_view); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} + +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("Inventory/InventoryDetailView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/DetailViewAjax.php b/oss/vtiger/trunk/modules/PriceBooks/DetailViewAjax.php new file mode 100644 index 00000000..a2233ae7 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/DetailViewAjax.php @@ -0,0 +1,46 @@ +retrieve_entity_info($crmid,"PriceBooks"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("PriceBooks"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/EditView.php b/oss/vtiger/trunk/modules/PriceBooks/EditView.php new file mode 100644 index 00000000..85ad9fa1 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/EditView.php @@ -0,0 +1,125 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if(isset($_REQUEST['record']) && $_REQUEST['record'] != '') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"PriceBooks"); + $focus->name = $focus->column_fields['bookname']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $bas_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS'); + $blocks['basicTab'] = $bas_block; + + $smarty->assign("BLOCKS",$blocks); + $smarty->assign("BLOCKS_COUNT",count($blocks)); +} +$smarty->assign("OP_MODE",$disp_view); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'PriceBook'); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} + +$smarty->assign("ID", $focus->id); +if(isset($focus->name)) + $smarty->assign("NAME", $focus->name); + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} + +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + + +$tabid = getTabid("PriceBooks"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +// Added to set price book active when creating a new pricebook +if($focus->mode != 'edit' && $_REQUEST['isDuplicate'] != 'true') + $smarty->assign('PRICE_BOOK_MODE', 'create'); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +if($focus->mode == 'edit') + $smarty->display('Inventory/InventoryEditView.tpl'); +else + $smarty->display('Inventory/InventoryCreateView.tpl'); +?> diff --git a/oss/vtiger/trunk/modules/PriceBooks/ListView.php b/oss/vtiger/trunk/modules/PriceBooks/ListView.php new file mode 100644 index 00000000..c6646430 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/ListView.php @@ -0,0 +1,193 @@ +assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'PriceBook'); + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$focus = new PriceBooks(); +// Initialize sort by fields +$focus->initSortbyField('PriceBooks'); +// END +$other_text=Array(); + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +if (!isset($where)) $where = ""; + +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['PRICEBOOK_ORDER_BY'] = $order_by; +$_SESSION['PRICEBOOK_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + +if(isset($_REQUEST['query']) && $_REQUEST['query'] != '' && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); + +} + +//<<<>>>>>> +$oCustomView = new CustomView("PriceBooks"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//<<<<>>>> +if(isPermitted('PriceBooks','DeletePriceBook','') == 'yes') + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +if(isPermitted('PriceBooks','EditView','') == 'yes') + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("PriceBooks"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"PriceBooks"); +}else +{ + $list_query = getListQuery("PriceBooks"); +} +//<<<<<<<>>>>>>>> + + +if(isset($where) && $where != '') +{ + $list_query .= ' and '.$where; +} + +if(isset($order_by) && $order_by != '') +{ + $tablename = getTableNameForField('PriceBooks',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY '.$tablename.$order_by; + $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); + +//Retreive the List View Table Header + +$listview_header = getListViewHeader($focus,"PriceBooks",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search = getSearchListHeaderValues($focus,"PriceBooks",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER",$listview_header_search); + +$listview_entries = getListViewEntries($focus,"PriceBooks",$list_result,$navigation_array,'','&return_module=PriceBooks&return_action=index','EditView','Delete',$oCustomView); +$smarty->assign("LISTENTITY", $listview_entries); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"PriceBooks","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','bookname','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("SELECT_SCRIPT", $view_script); +$smarty->assign("BUTTONS", $other_text); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/ListViewPagging.php b/oss/vtiger/trunk/modules/PriceBooks/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/MassEdit.php b/oss/vtiger/trunk/modules/PriceBooks/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/MassEditSave.php b/oss/vtiger/trunk/modules/PriceBooks/MassEditSave.php new file mode 100644 index 00000000..0e1f2a6f --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/Popup.php b/oss/vtiger/trunk/modules/PriceBooks/Popup.php new file mode 100644 index 00000000..18d2d154 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/Popup.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/PriceBooks.js b/oss/vtiger/trunk/modules/PriceBooks/PriceBooks.js new file mode 100644 index 00000000..5fb03320 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/PriceBooks.js @@ -0,0 +1,192 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + +prod_array = new Array(); +function addtopricebook() +{ + x = document.addToPB.selected_id.length; + prod_array = new Array(x); + idstring = ""; + + if ( x == undefined) + { + if (document.addToPB.selected_id.checked) + { + yy = document.addToPB.selected_id.value+"_listprice"; + document.addToPB.idlist.value=document.addToPB.selected_id.value; + + var elem = document.addToPB.elements; + var ele_len =elem.length; + var i=0,j=0; + + for(i=0; i'crmid','vtiger_pricebook'=>'pricebookid','vtiger_pricebookcf'=>'pricebookid'); + /** + * Mandatory table for supporting custom fields. + */ + var $customFieldTable = Array('vtiger_pricebookcf', 'pricebookid'); + var $column_fields = Array(); + + var $sortby_fields = Array('bookname'); + + // This is the list of fields that are in the lists. + var $list_fields = Array( + 'Price Book Name'=>Array('pricebook'=>'bookname'), + 'Active'=>Array('pricebook'=>'active') + ); + + var $list_fields_name = Array( + 'Price Book Name'=>'bookname', + 'Active'=>'active' + ); + var $list_link_field= 'bookname'; + + var $search_fields = Array( + 'Price Book Name'=>Array('pricebook'=>'bookname') + ); + var $search_fields_name = Array( + 'Price Book Name'=>'bookname', + ); + + //Added these variables which are used as default order by and sortorder in ListView + var $default_order_by = 'bookname'; + var $default_sort_order = 'ASC'; + + var $mandatory_fields = Array('bookname','currency_id','pricebook_no','createdtime' ,'modifiedtime'); + + /** Constructor which will set the column_fields in this object + */ + function PriceBooks() { + $this->log =LoggerManager::getLogger('pricebook'); + $this->log->debug("Entering PriceBooks() method ..."); + $this->db = PearDatabase::getInstance(); + $this->column_fields = getColumnFields('PriceBooks'); + $this->log->debug("Exiting PriceBook method ..."); + } + + function save_module($module) + { + // Update the list prices in the price book with the unit price, if the Currency has been changed + $this->updateListPrices(); + } + + /* Function to Update the List prices for all the products of a current price book + with its Unit price, if the Currency for Price book has changed. */ + function updateListPrices() { + global $log, $adb; + $log->debug("Entering function updateListPrices..."); + $pricebook_currency = $this->column_fields['currency_id']; + $prod_res = $adb->pquery("select productid from vtiger_pricebookproductrel where pricebookid=? and usedcurrency != ?", + array($this->id,$pricebook_currency)); + $numRows = $adb->num_rows($prod_res); + $prod_ids = array(); + for($i=0;$i<$numRows;$i++) { + $prod_ids[] = $adb->query_result($prod_res,$i,'productid'); + } + if(count($prod_ids) > 0) { + $prod_price_list = getPricesForProducts($pricebook_currency,$prod_ids); + + for($i=0;$iid, $product_id); + $adb->pquery($query, $params); + } + } + $log->debug("Exiting function updateListPrices..."); + } + + /** Function used to get the sort order for PriceBook listview + * @return string $sorder - first check the $_REQUEST['sorder'] if request value is empty then check in the $_SESSION['PRICEBOOK_SORT_ORDER'] if this session value is empty then default sort order will be returned. + */ + function getSortOrder() + { + global $log; + $log->debug("Entering getSortOrder() method ..."); + if(isset($_REQUEST['sorder'])) + $sorder = $this->db->sql_escape_string($_REQUEST['sorder']); + else + $sorder = (($_SESSION['PRICEBOOK_SORT_ORDER'] != '')?($_SESSION['PRICEBOOK_SORT_ORDER']):($this->default_sort_order)); + $log->debug("Exiting getSortOrder() method ..."); + return $sorder; + } + + /** Function used to get the order by value for PriceBook listview + * @return string $order_by - first check the $_REQUEST['order_by'] if request value is empty then check in the $_SESSION['PRICEBOOK_ORDER_BY'] if this session value is empty then default order by will be returned. + */ + function getOrderBy() + { + global $log; + $log->debug("Entering getOrderBy() method ..."); + + $use_default_order_by = ''; + if(PerformancePrefs::getBoolean('LISTVIEW_DEFAULT_SORTING', true)) { + $use_default_order_by = $this->default_order_by; + } + + if (isset($_REQUEST['order_by'])) + $order_by = $this->db->sql_escape_string($_REQUEST['order_by']); + else + $order_by = (($_SESSION['PRICEBOOK_ORDER_BY'] != '')?($_SESSION['PRICEBOOK_ORDER_BY']):($use_default_order_by)); + $log->debug("Exiting getOrderBy method ..."); + return $order_by; + } + + /** function used to get the products which are related to the pricebook + * @param int $id - pricebook id + * @return array - return an array which will be returned from the function getPriceBookRelatedProducts + **/ + function get_pricebook_products($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule,$current_user; + $log->debug("Entering get_pricebook_products(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + if($singlepane_view == 'true') + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + else + $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id; + + $button = ''; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + } + + $query = 'select vtiger_products.productid, vtiger_products.productname, vtiger_products.productcode, vtiger_products.commissionrate, vtiger_products.qty_per_unit, vtiger_products.unit_price, vtiger_crmentity.crmid, vtiger_crmentity.smownerid,vtiger_pricebookproductrel.listprice from vtiger_products inner join vtiger_pricebookproductrel on vtiger_products.productid = vtiger_pricebookproductrel.productid inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_products.productid inner join vtiger_pricebook on vtiger_pricebook.pricebookid = vtiger_pricebookproductrel.pricebookid where vtiger_pricebook.pricebookid = '.$id.' and vtiger_crmentity.deleted = 0'; + + $return_value = getPriceBookRelatedProducts($query,$this,$returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_pricebook_products method ..."); + return $return_value; + } + + /** function used to get the services which are related to the pricebook + * @param int $id - pricebook id + * @return array - return an array which will be returned from the function getPriceBookRelatedServices + **/ + function get_pricebook_services($id, $cur_tab_id, $rel_tab_id, $actions=false) { + global $log, $singlepane_view,$currentModule,$current_user; + $log->debug("Entering get_pricebook_services(".$id.") method ..."); + $this_module = $currentModule; + + $related_module = vtlib_getModuleNameById($rel_tab_id); + require_once("modules/$related_module/$related_module.php"); + $other = new $related_module(); + vtlib_setup_modulevars($related_module, $other); + $singular_modname = vtlib_toSingular($related_module); + + $parenttab = getParentTab(); + + if($singlepane_view == 'true') + $returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id; + else + $returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id; + + $button = ''; + + if($actions) { + if(is_string($actions)) $actions = explode(',', strtoupper($actions)); + if(in_array('SELECT', $actions) && isPermitted($related_module,4, '') == 'yes') { + $button .= " "; + } + } + + $query = 'select vtiger_service.serviceid, vtiger_service.servicename, vtiger_service.commissionrate, + vtiger_service.qty_per_unit, vtiger_service.unit_price, vtiger_crmentity.crmid, vtiger_crmentity.smownerid, + vtiger_pricebookproductrel.listprice from vtiger_service + inner join vtiger_pricebookproductrel on vtiger_service.serviceid = vtiger_pricebookproductrel.productid + inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_service.serviceid + inner join vtiger_pricebook on vtiger_pricebook.pricebookid = vtiger_pricebookproductrel.pricebookid + where vtiger_pricebook.pricebookid = '.$id.' and vtiger_crmentity.deleted = 0'; + + $return_value = $other->getPriceBookRelatedServices($query,$this,$returnset); + + if($return_value == null) $return_value = Array(); + $return_value['CUSTOM_BUTTON'] = $button; + + $log->debug("Exiting get_pricebook_services method ..."); + return $return_value; + } + + /** function used to get whether the pricebook has related with a product or not + * @param int $id - product id + * @return true or false - if there are no pricebooks available or associated pricebooks for the product is equal to total number of pricebooks then return false, else return true + */ + function get_pricebook_noproduct($id) + { + global $log; + $log->debug("Entering get_pricebook_noproduct(".$id.") method ..."); + + $query = "select vtiger_crmentity.crmid, vtiger_pricebook.* from vtiger_pricebook inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_pricebook.pricebookid where vtiger_crmentity.deleted=0"; + $result = $this->db->pquery($query, array()); + $no_count = $this->db->num_rows($result); + if($no_count !=0) + { + $pb_query = 'select vtiger_crmentity.crmid, vtiger_pricebook.pricebookid,vtiger_pricebookproductrel.productid from vtiger_pricebook inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_pricebook.pricebookid inner join vtiger_pricebookproductrel on vtiger_pricebookproductrel.pricebookid=vtiger_pricebook.pricebookid where vtiger_crmentity.deleted=0 and vtiger_pricebookproductrel.productid=?'; + $result_pb = $this->db->pquery($pb_query, array($id)); + if($no_count == $this->db->num_rows($result_pb)) + { + $log->debug("Exiting get_pricebook_noproduct method ..."); + return false; + } + elseif($this->db->num_rows($result_pb) == 0) + { + $log->debug("Exiting get_pricebook_noproduct method ..."); + return true; + } + elseif($this->db->num_rows($result_pb) < $no_count) + { + $log->debug("Exiting get_pricebook_noproduct method ..."); + return true; + } + } + else + { + $log->debug("Exiting get_pricebook_noproduct method ..."); + return false; + } + } + + /* + * Function to get the primary query part of a report + * @param - $module Primary module name + * returns the query string formed on fetching the related data for report for primary module + */ + function generateReportsQuery($module){ + $moduletable = $this->table_name; + $moduleindex = $this->table_index; + + $query = "from $moduletable + inner join vtiger_crmentity on vtiger_crmentity.crmid=$moduletable.$moduleindex + left join vtiger_currency_info as vtiger_currency_info$module on vtiger_currency_info$module.id = $moduletable.currency_id + left join vtiger_groups as vtiger_groups$module on vtiger_groups$module.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_users$module on vtiger_users$module.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid"; + return $query; + } + + /* + * Function to get the secondary query part of a report + * @param - $module primary module name + * @param - $secmodule secondary module name + * returns the query string formed on fetching the related data for report for secondary module + */ + function generateReportsSecQuery($module,$secmodule){ + $query = $this->getRelationQuery($module,$secmodule,"vtiger_pricebook","pricebookid"); + $query .=" left join vtiger_crmentity as vtiger_crmentityPriceBooks on vtiger_crmentityPriceBooks.crmid=vtiger_pricebook.pricebookid and vtiger_crmentityPriceBooks.deleted=0 + left join vtiger_currency_info as vtiger_currency_infoPriceBooks on vtiger_currency_infoPriceBooks.id = vtiger_pricebook.currency_id + left join vtiger_users as vtiger_usersPriceBooks on vtiger_usersPriceBooks.id = vtiger_crmentityPriceBooks.smownerid + left join vtiger_groups as vtiger_groupsPriceBooks on vtiger_groupsPriceBooks.groupid = vtiger_crmentityPriceBooks.smownerid"; + + return $query; + } + + /* + * Function to get the relation tables for related modules + * @param - $secmodule secondary module name + * returns the array with table names and fieldnames storing relations between module and this module + */ + function setRelationTables($secmodule){ + $rel_tables = array ( + "Products" => array("vtiger_pricebookproductrel"=>array("pricebookid","productid"),"vtiger_pricebook"=>"pricebookid"), + "Services" => array("vtiger_pricebookproductrel"=>array("pricebookid","productid"),"vtiger_pricebook"=>"pricebookid"), + ); + return $rel_tables[$secmodule]; + } + +} +?> diff --git a/oss/vtiger/trunk/modules/PriceBooks/PriceBooksAjax.php b/oss/vtiger/trunk/modules/PriceBooks/PriceBooksAjax.php new file mode 100644 index 00000000..ce66087f --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/PriceBooksAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/QuickCreate.php b/oss/vtiger/trunk/modules/PriceBooks/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/Save.php b/oss/vtiger/trunk/modules/PriceBooks/Save.php new file mode 100644 index 00000000..0a83a735 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/Save.php @@ -0,0 +1,51 @@ +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("PriceBooks"); +$return_id = $focus->id; + +$parenttab = getParentTab(); +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "PriceBooks"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +header("Location: index.php?action=$return_action&module=$return_module&parenttab=$parenttab&record=$return_id&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/Settings.php b/oss/vtiger/trunk/modules/PriceBooks/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/TagCloud.php b/oss/vtiger/trunk/modules/PriceBooks/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/UnifiedSearch.php b/oss/vtiger/trunk/modules/PriceBooks/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PriceBooks/index.php b/oss/vtiger/trunk/modules/PriceBooks/index.php new file mode 100644 index 00000000..cdab8de1 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/index.php @@ -0,0 +1,20 @@ + diff --git a/oss/vtiger/trunk/modules/PriceBooks/language/en_us.lang.php b/oss/vtiger/trunk/modules/PriceBooks/language/en_us.lang.php new file mode 100644 index 00000000..251726ec --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/language/en_us.lang.php @@ -0,0 +1,42 @@ +'Price Book Information:', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_DESCRIPTION_INFORMATION'=>'Description Name:', +//Mapping for price book +'Price Book Name'=>'Price Book Name', +'Product Name'=>'Product Name', +'Active'=>'Active', +'Description'=>'Description', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'LBL_LIST_PRODUCT_NAME'=>'Product Name', +'LBL_PRODUCT_CODE'=>'Part Number', +'LBL_PRODUCT_UNIT_PRICE'=>'Unit Price', +'LBL_PB_LIST_PRICE'=>'List Price', +'LBL_ACTION'=>'Action', +'PriceBook'=>'Price Book', + +// Added after 5.0.4 GA +'Currency'=>'Currency', + +// Module Sequence Numbering +'PriceBook No' => 'PriceBook No', +// END +); + + + +?> diff --git a/oss/vtiger/trunk/modules/PriceBooks/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/PriceBooks/language/zh_cn.lang.php new file mode 100644 index 00000000..60effc78 --- /dev/null +++ b/oss/vtiger/trunk/modules/PriceBooks/language/zh_cn.lang.php @@ -0,0 +1,41 @@ + '价目表信息:', + 'LBL_CUSTOM_INFORMATION' => '自订信息:', + 'LBL_DESCRIPTION_INFORMATION' => '描述名称:', + //Mapping for price book + 'Price Book Name' => '价目表名称', + 'Product Name' => '产品名称', + 'Active' => '启用', + 'Description' => '说明', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'LBL_LIST_PRODUCT_NAME' => '产品名称', + 'LBL_PRODUCT_CODE' => '产品代号', + 'LBL_PRODUCT_UNIT_PRICE' => '单位价格', + 'LBL_PB_LIST_PRICE' => '定价', + 'LBL_ACTION' => '操作', + 'PriceBook' => '价目表', +// Added after 5.0.4 GA +'Currency'=>'Currency', + +// Module Sequence Numbering +'PriceBook No' => 'PriceBook No', +// END +); + + + +?> diff --git a/oss/vtiger/trunk/modules/Products/AddProductToPriceBooks.html b/oss/vtiger/trunk/modules/Products/AddProductToPriceBooks.html new file mode 100644 index 00000000..26e461a8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/AddProductToPriceBooks.html @@ -0,0 +1,156 @@ + + + + + + + + +
     
      +{PRICEBOOKLISTHEADER} + + + + + + + + + +
    + + {LISTHEADER} + {LISTENTITY} +
    +
     
    + + + +
    + +  + + + diff --git a/oss/vtiger/trunk/modules/Products/AddProductToPriceBooks.php b/oss/vtiger/trunk/modules/Products/AddProductToPriceBooks.php new file mode 100644 index 00000000..7aab869b --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/AddProductToPriceBooks.php @@ -0,0 +1,170 @@ +id,'unit_price') != '0'){ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_UNIT_PRICE_NOT_PERMITTED]
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; + exit(); +} + +$smarty=new vtigerCRM_Smarty; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); + +$focus = new PriceBooks(); + +//Retreive the list of PriceBooks +$list_query = getListQuery("PriceBooks"); + +$list_query .= ' and vtiger_pricebook.active<>0 ORDER BY pricebookid DESC '; + +$list_result = $adb->query($list_query); +$num_rows = $adb->num_rows($list_result); + +$record_string= "Total No of PriceBooks : ".$num_rows; + +//Retreiving the array of already releated products +$sql1="select vtiger_crmentity.crmid, vtiger_pricebookproductrel.pricebookid,vtiger_products.unit_price + from vtiger_pricebookproductrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_pricebookproductrel.productid + inner join vtiger_products on vtiger_products.productid=vtiger_pricebookproductrel.productid + where vtiger_crmentity.deleted=0 and vtiger_pricebookproductrel.productid=?"; +$res1 = $adb->pquery($sql1, array($productid)); +$num_prod_rows = $adb->num_rows($res1); +$pbk_array = Array(); +for($i=0; $i<$num_prod_rows; $i++) +{ + $pbkid=$adb->query_result($res1,$i,"pricebookid"); + $pbk_array[$pbkid] = $pbkid; +} + +$pro_unit_price = getUnitPrice($productid, $currentModule); +$prod_price_details = getPriceDetailsForProduct($productid, $pro_unit_price); + +$prod_cur_price = array(); +for($i=0; $i + + '; + + //we should not display the Add to PriceBook button if there is no pricebooks to associate + if($num_rows != $num_prod_rows) + $other_text .=' '; + +$other_text .=''; +$other_text .=' + + '; + +$smarty->assign("PRICEBOOKLISTHEADER", get_form_header($current_module_strings['LBL_LIST_PRICEBOOK_FORM_TITLE'], $other_text, false )); + + +//List View Table Header +$list_header = ''; +$list_header .= ''; +$list_header .=''; +$list_header .= ''.$mod_strings['LBL_PRICEBOOK'].''; +$list_header .= ''.$app_strings['LBL_CURRENCY'].''; +$list_header .= ''.$mod_strings['LBL_PRODUCT_UNIT_PRICE'].''; +$list_header .= ''.$mod_strings['LBL_PB_LIST_PRICE'].''; +$list_header .= ''; + +$smarty->assign("LISTHEADER", $list_header); + +$list_body =''; +for($i=0; $i<$num_rows; $i++) +{ + $entity_id = $adb->query_result($list_result,$i,"crmid"); + if(! array_key_exists($entity_id, $pbk_array)) + { + $pk_currency_id = $adb->query_result($list_result,$i,"currency_id"); + $pk_currency_name = $adb->query_result($list_result,$i,"currency_name"); + $unit_price = $prod_cur_price[$pk_currency_id]; + $field_name = $entity_id."_listprice"; + $unit_price_array[]="'".$unit_price."'"; + $field_name_array[]="'".$field_name."'"; + + $list_body .= ''; + $list_body .= ''; + $list_body .= ''.$adb->query_result($list_result,$i,"bookname").''; + $list_body .= ''.$pk_currency_name.''; + $list_body .= ''.$unit_price.''; + + $list_body .=''; + if(isPermitted("PriceBooks","EditView","") == 'yes') + $list_body .= ''; + else + $list_body .= ''; + $list_body .= ''; + } + +} + +$smarty->assign("UNIT_PRICE_ARRAY",implode(",",$unit_price_array)); +$smarty->assign("FIELD_NAME_ARRAY",implode(",",$field_name_array)); + +if($order_by !='') + $url_string .="&order_by=".$order_by; +if($sorder !='') + $url_string .="&sorder=".$sorder; + +$smarty->assign("LISTENTITY", $list_body); +$smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +$smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +$smarty->assign("RETURN_ID", $productid); +$smarty->assign("CATEGORY", $parenttab); + +$smarty->display("AddProductToPriceBooks.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/AddProductsToPriceBook.html b/oss/vtiger/trunk/modules/Products/AddProductsToPriceBook.html new file mode 100644 index 00000000..68b5818b --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/AddProductsToPriceBook.html @@ -0,0 +1,58 @@ + + + + +
    +
    +{PRODUCTLISTHEADER} + + + + + + + +
    + + + + {NAVIGATION} + +
     {RECORD_COUNTS}
    +
    + + {LISTHEADER} + {LISTENTITY} +
    +
     
    + + + + + diff --git a/oss/vtiger/trunk/modules/Products/AddProductsToPriceBook.php b/oss/vtiger/trunk/modules/Products/AddProductsToPriceBook.php new file mode 100644 index 00000000..72e1d86d --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/AddProductsToPriceBook.php @@ -0,0 +1,189 @@ +id); +$parenttab = getParentTab(); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +require_once($theme_path.'layout_utils.php'); + +if(getFieldVisibilityPermission('Products',$current_user->id,'unit_price') != '0'){ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_UNIT_PRICE_NOT_PERMITTED]
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; + exit(); +} + +$pricebookname = getPriceBookName($pricebook_id); + +$smarty= new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); + +$focus = new Products(); + +if (isset($_REQUEST['order_by'])) + $order_by = $adb->sql_escape_string($_REQUEST['order_by']); + +$url_string = ''; // assigning http url string +$sorder = 'ASC'; // Default sort order +if(isset($_REQUEST['sorder']) && $_REQUEST['sorder'] != '') + $sorder = $adb->sql_escape_string($_REQUEST['sorder']); + + +//Retreive the list of Products +$list_query = getListQuery("Products"); + +if(isset($order_by) && $order_by != '') +{ + $list_query .= ' and vtiger_products.discontinued<>0 ORDER BY '.$order_by.' '.$sorder; +} + +$list_query .= " and vtiger_products.discontinued<>0 group by vtiger_crmentity.crmid"; +$list_result = $adb->query($list_query); +$num_rows = $adb->num_rows($list_result); + +$record_string= "Total No of Product Available : ".$num_rows; + +//Retreiving the array of already releated products +$sql1 = "select productid from vtiger_pricebookproductrel + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_pricebookproductrel.productid + WHERE vtiger_crmentity.setype='Products' AND vtiger_crmentity.deleted=0 AND pricebookid=?"; +$res1 = $adb->pquery($sql1, array($pricebook_id)); +$num_prod_rows = $adb->num_rows($res1); +$prod_array = Array(); +for($i=0; $i<$num_prod_rows; $i++) +{ + $prodid=$adb->query_result($res1,$i,"productid"); + $prod_array[$prodid] = $prodid; +} + + +//Buttons Add To PriceBook and Cancel +$other_text = ' + + + + '; + +$other_text .=' + +
      + + + + '; + + //we should not display the Add to PriceBook button if there is no products to associate + if($num_rows != $num_prod_rows && $num_rows > 0) + $other_text .=''; + +$other_text .=' 
    '; + +$smarty->assign("PRODUCTLISTHEADER", get_form_header($current_module_strings['LBL_LIST_FORM_TITLE'], $other_text, false )); + +//Retreive the List View Table Header + +$list_header = ''; +$list_header .= ''; +$list_header .=''; +$list_header .= ''.$mod_strings['LBL_LIST_PRODUCT_NAME'].''; +if(getFieldVisibilityPermission('Products', $current_user->id, 'productcode') == '0') + $list_header .= ''.$mod_strings['LBL_PRODUCT_CODE'].''; +if(getFieldVisibilityPermission('Products', $current_user->id, 'unit_price') == '0') + $list_header .= ''.$mod_strings['LBL_PRODUCT_UNIT_PRICE'].''; +$list_header .= ''.$mod_strings['LBL_PB_LIST_PRICE'].''; +$list_header .= ''; + +$smarty->assign("LISTHEADER", $list_header); + + +//if the product is not associated already then we should display that products +$new_prod_array = array(); +$unit_price_array=array(); +$field_name_array=array(); +$entity_id_array =array(); +for($i=0; $i<$num_rows; $i++) +{ + $entity_id = $adb->query_result($list_result,$i,"crmid"); + if(! array_key_exists($entity_id, $prod_array)) + { + $new_prod_array[] = $entity_id; + } + $entity_id_array[$entity_id] = $i; +} +$prod_price_list = getPricesForProducts($currency_id, $new_prod_array); + +$list_body =''; +for($i=0; $iinfo("Products :: Showing the List of products to be added in price book"); + $entity_id = $new_prod_array[$i]; + + $list_body .= ''; + $unit_price = $prod_price_list[$entity_id]; + $field_name = $entity_id."_listprice"; + $unit_price_array[]="'".$unit_price."'"; + $field_name_array[]="'".$field_name."'"; + + $list_body .= ''; + $list_body .= ''.$adb->query_result($list_result,$entity_id_array[$entity_id],"productname").''; + + if(getFieldVisibilityPermission('Products', $current_user->id, 'productcode') == '0') + $list_body .= ''.$adb->query_result($list_result,$entity_id_array[$entity_id],"productcode").''; + if(getFieldVisibilityPermission('Products', $current_user->id, 'unit_price') == '0') + $list_body .= ''.$unit_price.''; + + $list_body .=''; + if(isPermitted("PriceBooks","EditView","") == 'yes') + $list_body .= ''; + else + $list_body .= ''; + $list_body .= ''; +} + +$smarty->assign("UNIT_PRICE_ARRAY",implode(",",$unit_price_array)); +$smarty->assign("FIELD_NAME_ARRAY",implode(",",$field_name_array)); + +if($order_by !='') + $url_string .="&order_by=".$order_by; +if($sorder !='') + $url_string .="&sorder=".$sorder; + +$smarty->assign("LISTENTITY", $list_body); +$smarty->assign("CATEGORY", $parenttab); + +$smarty->display("AddProductsToPriceBook.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/CallRelatedList.php b/oss/vtiger/trunk/modules/Products/CallRelatedList.php new file mode 100644 index 00000000..4b93cd87 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/CallRelatedList.php @@ -0,0 +1,74 @@ +retrieve_entity_info($record,$currentModule); + $focus->id = $record; + $focus->name=$focus->column_fields['productname']; + $product_base_currency = getProductBaseCurrency($focus->id,$currentModule); + } else { + $product_base_currency = fetchCurrency($current_user->id); + } + + $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']); + + $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->name); + $smarty->assign('UPDATEINFO',updateInfo($focus->id)); + + $smarty->assign("CURRENCY_ID",$product_base_currency); + + $is_member = $focus->ismember_check(); + $smarty->assign("IS_MEMBER",$is_member); + + // 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'); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/CustomView.php b/oss/vtiger/trunk/modules/Products/CustomView.php new file mode 100644 index 00000000..aebb8b53 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/CustomView.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Products/Delete.php b/oss/vtiger/trunk/modules/Products/Delete.php new file mode 100644 index 00000000..77a0dceb --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/Delete.php @@ -0,0 +1,37 @@ +deleteProduct2ProductRelation($record, $return_id, $_REQUEST['is_parent']); + +$parenttab = getParentTab(); + +if(isset($_REQUEST['activity_mode'])) + $url .= '&activity_mode='.vtlib_purify($_REQUEST['activity_mode']); + +header("Location: index.php?module=$return_module&action=$return_action&record=$return_id&parenttab=$parenttab&relmodule=$module".$url); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/DeletePriceBookProductRel.php b/oss/vtiger/trunk/modules/Products/DeletePriceBookProductRel.php new file mode 100644 index 00000000..105fcbbe --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/DeletePriceBookProductRel.php @@ -0,0 +1,33 @@ +info("Products :: Deleting Price Book - Delete from PriceBook RelatedList"); + $query = "delete from vtiger_pricebookproductrel where pricebookid=? and productid=?"; + $adb->pquery($query, array($return_id, $record)); +} +else +{ + $log->info("Products :: Deleting Price Book"); + $query = "delete from vtiger_pricebookproductrel where pricebookid=? and productid=?"; + $adb->pquery($query, array($record, $return_id)); +} + +header("Location: index.php?module=".$return_module."&action=".$return_module."Ajax&file=$return_action&ajax=delpbprorel&record=".$return_id); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/DetailView.php b/oss/vtiger/trunk/modules/Products/DetailView.php new file mode 100644 index 00000000..f5b7dfcf --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/DetailView.php @@ -0,0 +1,127 @@ +'.$_SESSION['image_type_error'].'
    '; + session_unregister('image_type_error'); + } + $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', 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); + +$recordName = array_values(getEntityName($currentModule, $focus->id)); +$recordName = $recordName[0]; +$smarty->assign('NAME', $recordName); +$smarty->assign('UPDATEINFO',updateInfo($focus->id)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); + +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +// 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 + +//Added to display the Tax informations +$tax_details = getTaxDetailsForProduct($focus->id); + +for($i=0;$iid); +} +$smarty->assign("TAX_DETAILS", $tax_details); + +$price_details = getPriceDetailsForProduct($focus->id, $focus->unit_price, 'available_associated',$currentModule); +$smarty->assign("PRICE_DETAILS", $price_details); + +$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); + +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($tabid, '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("Inventory/InventoryDetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/DetailViewAjax.php b/oss/vtiger/trunk/modules/Products/DetailViewAjax.php new file mode 100644 index 00000000..43da8072 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/DetailViewAjax.php @@ -0,0 +1,39 @@ +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'; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/EditListPrice.php b/oss/vtiger/trunk/modules/Products/EditListPrice.php new file mode 100644 index 00000000..4cf8eb78 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/EditListPrice.php @@ -0,0 +1,65 @@ + + + + + + +
    '.$mod_strings["LBL_EDITLISTPRICE"].''.$app_strings[
    + + + + +
    + + + + + +
    '.$mod_strings["LBL_EDITLISTPRICE"].'
    +
    + + + + +
    + + +
    +
    '; + +echo $output; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/EditView.php b/oss/vtiger/trunk/modules/Products/EditView.php new file mode 100644 index 00000000..539f871a --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/EditView.php @@ -0,0 +1,262 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if($record) { + $focus->id = $record; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($record, $currentModule); + $product_base_currency = getProductBaseCurrency($focus->id,$currentModule); +} else { + $product_base_currency = fetchCurrency($current_user->id); +} + +if($image_error=="true") +{ + $explode_decode_val=explode("&",$decode_val); + for($i=1;$icolumn_fields[$field_name_val]=$field_value; + } +} + +if($isduplicate == 'true') { + $focus->id = ''; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +//needed when creating a new product with a default vtiger_vendor name to passed +if (isset($_REQUEST['name']) && is_null($focus->name)) { + $focus->name = $_REQUEST['name']; + +} +if (isset($_REQUEST['vendorid']) && is_null($focus->vendorid)) { + $focus->vendorid = $_REQUEST['vendorid']; +} + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') { + $smarty->assign('BLOCKS', getBlocks($currentModule, $disp_view, $focus->mode, $focus->column_fields)); +} else { + $bas_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS'); + $adv_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'ADV'); + + $blocks['basicTab'] = $bas_block; + if(is_array($adv_block)) + $blocks['moreTab'] = $adv_block; + + $smarty->assign("BLOCKS",$blocks); + $smarty->assign("BLOCKS_COUNT",count($blocks)); +} + +$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($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)); +} + +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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + 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->id != '') + $smarty->assign("ROWCOUNT", getImageCount($focus->id)); + +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +//Tax handling (get the available taxes only) - starts +if($focus->mode == 'edit') +{ + $retrieve_taxes = true; + $productid = $focus->id; + $tax_details = getTaxDetailsForProduct($productid,'available_associated'); +} +elseif($_REQUEST['isDuplicate'] == 'true') +{ + $retrieve_taxes = true; + $productid = $_REQUEST['record']; + $tax_details = getTaxDetailsForProduct($productid,'available_associated'); +} +else + $tax_details = getAllTaxes('available'); + +for($i=0;$iassign("TAX_DETAILS", $tax_details); +//Tax handling - ends + +$unit_price = $focus->column_fields['unit_price']; +$price_details = getPriceDetailsForProduct($productid, $unit_price, 'available',$currentModule); +$smarty->assign("PRICE_DETAILS", $price_details); + +$base_currency = 'curname' . $product_base_currency; +$smarty->assign("BASE_CURRENCY", $base_currency); + +if(isset($focus->id) && $_REQUEST['isDuplicate'] != 'true') + $is_parent = $focus->isparent_check(); +else + $is_parent = 0; +$smarty->assign("IS_PARENT",$is_parent); + +if($_REQUEST['return_module']=='Products' && isset($_REQUEST['return_action'])){ + $return_name = getProductName($_REQUEST['return_id']); + $smarty->assign("RETURN_NAME", $return_name); +} + +if($errormessage==2) +{ + $msg =$mod_strings['LBL_MAXIMUM_LIMIT_ERROR']; + $errormessage ="".$msg."

    "; +} +else if($errormessage==3) +{ + $msg = $mod_strings['LBL_UPLOAD_ERROR']; + $errormessage ="".$msg."

    "; + +} +else if($errormessage=="image") +{ + $msg = $mod_strings['LBL_IMAGE_ERROR']; + $errormessage ="".$msg."

    "; +} +else if($errormessage =="invalid") +{ + $msg = $mod_strings['LBL_INVALID_IMAGE']; + $errormessage ="".$msg."

    "; +} +else +{ + $errormessage=""; +} +if($errormessage!="") +{ + $smarty->assign("ERROR_MESSAGE",$errormessage); +} + +// Added to set product active when creating a new product +$mode=$focus->mode; +if($mode != "edit" && $_REQUEST['isDuplicate'] != "true") + $smarty->assign("PROD_MODE", "create"); + + +if($focus->mode == 'edit') { + $smarty->display('Inventory/InventoryEditView.tpl'); +} else { + $smarty->display('Inventory/InventoryCreateView.tpl'); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/ExportRecords.php b/oss/vtiger/trunk/modules/Products/ExportRecords.php new file mode 100644 index 00000000..31029bc0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/ExportRecords.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Products/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/Products/FindDuplicateRecords.php new file mode 100644 index 00000000..a1ff9757 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/FindDuplicateRecords.php @@ -0,0 +1,106 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    + $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/Import.php b/oss/vtiger/trunk/modules/Products/Import.php new file mode 100644 index 00000000..576068f5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/Import.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Products/InventoryPriceAjax.php b/oss/vtiger/trunk/modules/Products/InventoryPriceAjax.php new file mode 100644 index 00000000..453479f0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/InventoryPriceAjax.php @@ -0,0 +1,38 @@ + 0) { + $prices_for_products = getPricesForProducts($currencyid, $product_ids); + $prices_for_services = getPricesForProducts($currencyid, $product_ids, 'Services'); +} + +// To get the Price Values in the same order as the Products +for ($i=0;$i diff --git a/oss/vtiger/trunk/modules/Products/InventoryTaxAjax.php b/oss/vtiger/trunk/modules/Products/InventoryTaxAjax.php new file mode 100644 index 00000000..4c859ea8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/InventoryTaxAjax.php @@ -0,0 +1,68 @@ + + + '.$app_strings['LABEL_SET_TAX_FOR'].' : '.$product_total.' +   + + + '; + +$net_tax_total = 0.00; +for($i=0,$j=$i+1;$i % + + + '.$tax_label.' + + + + + '; +} + +$tax_div .= ''; + +if($associated_tax_count == 0) +{ + $tax_div .= '
    '.$mod_strings['LBL_NO_TAXES_ASSOCIATED'].'.
    '; +} + +$tax_div .= ''; + +echo $tax_div; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/ListView.php b/oss/vtiger/trunk/modules/Products/ListView.php new file mode 100644 index 00000000..5a09af30 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/ListView.php @@ -0,0 +1,212 @@ +initSortbyField($currentModule); +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['PRODUCTS_ORDER_BY'] = $order_by; +$_SESSION['PRODUCTS_SORT_ORDER'] = $sorder; + +$smarty = new vtigerCRM_Smarty(); + +$smarty->assign('MOD', $mod_strings); +$smarty->assign('APP', $app_strings); +$smarty->assign("THEME", $theme); +$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('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 "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_PERMISSION]
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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); + +$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); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +$url_string = '&smodule=PRODUCTS'; // assigning http url string + +if(isset($where) && $where != '') +{ + $list_query .= ' and '.$where; + + $_SESSION['export_where'] = $where; +} +else + unset($_SESSION['export_where']); + +$smarty->assign("SELECT_SCRIPT", $view_script); + +$smarty->assign("AVALABLE_FIELDS", getMergeFields($currentModule,"available_fields")); +$smarty->assign("FIELDS_TO_MERGE", getMergeFields($currentModule,"fileds_to_merge")); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display('ListView.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/ListViewPagging.php b/oss/vtiger/trunk/modules/Products/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/MassEdit.php b/oss/vtiger/trunk/modules/Products/MassEdit.php new file mode 100644 index 00000000..4a57ce1e --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/MassEdit.php @@ -0,0 +1,43 @@ +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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/MassEditSave.php b/oss/vtiger/trunk/modules/Products/MassEditSave.php new file mode 100644 index 00000000..90fcd98c --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/MassEditSave.php @@ -0,0 +1,59 @@ +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(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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Products/Popup.php b/oss/vtiger/trunk/modules/Products/Popup.php new file mode 100644 index 00000000..40aae3fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/Popup.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/Products/ProcessDuplicates.php b/oss/vtiger/trunk/modules/Products/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Products/Products.js b/oss/vtiger/trunk/modules/Products/Products.js new file mode 100644 index 00000000..fba7143f --- /dev/null +++ b/oss/vtiger/trunk/modules/Products/Products.js @@ -0,0 +1,172 @@ +/*+********************************************************************************** + * 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. + ************************************************************************************/ +document.write(""; +exit(); +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/Settings.php b/oss/vtiger/trunk/modules/PurchaseOrder/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/TagCloud.php b/oss/vtiger/trunk/modules/PurchaseOrder/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/UnifiedSearch.php b/oss/vtiger/trunk/modules/PurchaseOrder/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/index.php b/oss/vtiger/trunk/modules/PurchaseOrder/index.php new file mode 100644 index 00000000..f28f3a9b --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/index.php @@ -0,0 +1,53 @@ + diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/language/en_us.lang.php b/oss/vtiger/trunk/modules/PurchaseOrder/language/en_us.lang.php new file mode 100644 index 00000000..911742c7 --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/language/en_us.lang.php @@ -0,0 +1,203 @@ +'PurchaseOrder', +'LBL_RELATED_PRODUCTS'=>'Product Details', +'LBL_MODULE_TITLE'=>'Purchase Order: Home', +'LBL_SEARCH_FORM_TITLE'=>'Purchase Order Search', +'LBL_LIST_FORM_TITLE'=>'Purchase Order List', +'LBL_NEW_FORM_TITLE'=>'New Purchase Order', +'LBL_MEMBER_ORG_FORM_TITLE'=>'Member Organizations', + +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_LIST_CITY'=>'City', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_STATE'=>'State', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_EMAIL_ADDRESS'=>'Email Address', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'Account:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_PHONE'=>'Phone:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_TICKER_SYMBOL'=>'Ticker Symbol:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_MEMBER_OF'=>'Member of:', +'LBL_EMAIL'=>'Email:', +'LBL_EMPLOYEES'=>'Employees:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_OWNERSHIP'=>'Ownership:', +'LBL_RATING'=>'Rating:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_SIC_CODE'=>'SIC Code:', +'LBL_TYPE'=>'Type:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_Quote_INFORMATION'=>'Account Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_BILLING_ADDRESS'=>'Billing Address:', +'LBL_SHIPPING_ADDRESS'=>'Shipping Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_TERMS_INFORMATION'=>'Terms & Conditions', +'LBL_DESCRIPTION'=>'Description:', +'NTC_COPY_BILLING_ADDRESS'=>'Copy billing address to shipping address', +'NTC_COPY_SHIPPING_ADDRESS'=>'Copy shipping address to billing address', +'NTC_REMOVE_MEMBER_ORG_CONFIRMATION'=>'Are you sure you want to remove this record as a member organization?', +'LBL_DUPLICATE'=>'Potential Duplicate Accounts', +'MSG_DUPLICATE' => 'Creating this vtiger_account may vtiger_potentialy create a duplicate vtiger_account. You may either select an vtiger_account from the list below or you may click on Create New Account to continue creating a new vtiger_account with the previously entered data.', + +'LBL_INVITEE'=>'Contacts', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", + +'LBL_SELECT_ACCOUNT'=>'Select Account', +'LBL_GENERAL_INFORMATION'=>'General Information', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_PROSPECT'=>'Prospect', +'LBL_INVESTOR'=>'Investor', +'LBL_RESELLER'=>'Reseller', +'LBL_PARTNER'=>'Partner', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Account Tools', +//Added for 4GA +'Subject'=>'Subject', +'Quote Name'=>'Quote Name', +'Vendor Name'=>'Vendor Name', +'Requisition No'=>'Requisition No', +'Tracking Number'=>'Tracking Number', +'Contact Name'=>'Contact Name', +'Due Date'=>'Due Date', +'Carrier'=>'Carrier', +'Type'=>'Type', +'Sales Tax'=>'Sales Tax', +'Sales Commission'=>'Sales Commission', +'Excise Duty'=>'Excise Duty', +'Total'=>'Total', +'Product Name'=>'Product Name', +'Assigned To'=>'Assigned To', +'Billing Address'=>'Billing Address', +'Shipping Address'=>'Shipping Address', +'Billing City'=>'Billing City', +'Billing State'=>'Billing State', +'Billing Code'=>'Billing Postal Code', +'Billing Country'=>'Billing Country', +'Billing Po Box'=>'Billing PO Box', +'Shipping Po Box'=>'Shipping PO Box', +'Shipping City'=>'Shipping City', +'Shipping State'=>'Shipping State', +'Shipping Code'=>'Shipping Postal Code', +'Shipping Country'=>'Shipping Country', +'City'=>'City', +'State'=>'State', +'Code'=>'Code', +'Country'=>'Country', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Description'=>'Description', +'Potential Name'=>'Potential Name', +'Customer No'=>'Customer No', +'Purchase Order'=>'Purchase Order', +'Vendor Terms'=>'Vendor Terms', +'Pending'=>'Pending', +'Account Name'=>'Account Name', +'Terms & Conditions'=>'Terms & Conditions', +//Quote Info +'LBL_PO_INFORMATION'=>'Purchase Order Information', +'LBL_PO'=>'Purchase Order:', + + //Added for 4.2 GA +'LBL_SO_FORM_TITLE'=>'Sales', +'LBL_PO_FORM_TITLE'=>'Purchase', +'LBL_SUBJECT_TITLE'=>'Subject', +'LBL_VENDOR_NAME_TITLE'=>'Vendor Name', +'LBL_TRACKING_NO_TITLE'=>'Tracking No:', +'LBL_PO_SEARCH_TITLE'=>'Purchase Order Search', +'LBL_SO_SEARCH_TITLE'=>'Sales Order Search', +'LBL_QUOTE_NAME_TITLE'=>'Quote Name', +'Order No'=>'Order No', +'Status'=>'Status', +'PurchaseOrder'=>'Purchase Order', +'LBL_MY_TOP_PO'=>'My Top Open Purchase Orders', + +//Added for existing Picklist Entries + +'FedEx'=>'FedEx', +'UPS'=>'UPS', +'USPS'=>'USPS', +'DHL'=>'DHL', +'BlueDart'=>'BlueDart', + +'Created'=>'Created', +'Approved'=>'Approved', +'Delivered'=>'Delivered', +'Cancelled'=>'Cancelled', +'Received Shipment'=>'Received Shipment', + +//Added for Reports (5.0.4) +'Tax Type'=>'Tax Type', +'Discount Percent'=>'Discount Percent', +'Discount Amount'=>'Discount Amount', +'Terms & Conditions'=>'Terms & Conditions', +'Adjustment'=>'Adjustment', +'Sub Total'=>'Sub Total', +'S&H Amount'=>'S&H Amount', + +//Added after 5.0.4 GA +'PurchaseOrder No'=>'PurchaseOrder No', + +); + +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/PurchaseOrder/language/zh_cn.lang.php new file mode 100644 index 00000000..52dafc5d --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/language/zh_cn.lang.php @@ -0,0 +1,188 @@ + '采购订单', + 'LBL_RELATED_PRODUCTS' => '产品细节', + 'LBL_MODULE_TITLE' => '采购订单:首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻采购订单', + 'LBL_LIST_FORM_TITLE' => '采购订单列表', + 'LBL_NEW_FORM_TITLE' => '新增采购订单', + 'LBL_MEMBER_ORG_FORM_TITLE' => '成员组织', + + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_LIST_CITY' => '乡镇市区', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '县市', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件', + 'LBL_LIST_CONTACT_NAME' => '联络人名称', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT' => '客户:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_PHONE' => '电话:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_TICKER_SYMBOL' => '传票符号:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_ANY_PHONE' => '其它电话:', + 'LBL_MEMBER_OF' => '群组:', + 'LBL_EMAIL' => '电子信箱:', + 'LBL_EMPLOYEES' => '员工人数:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子信箱:', + 'LBL_ANY_EMAIL' => '其它电子信箱:', + 'LBL_OWNERSHIP' => '负责人:', + 'LBL_RATING' => '评分:', + 'LBL_INDUSTRY' => '产业别:', + 'LBL_SIC_CODE' => '统一编号:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年收入:', + 'LBL_ADDRESS_INFORMATION' => '住址信息', + 'LBL_Quote_INFORMATION' => '客户信息', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + 'LBL_BILLING_ADDRESS' => '发票住址:', + 'LBL_SHIPPING_ADDRESS' => '送货住址:', + 'LBL_ANY_ADDRESS' => '其它住址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '县市:', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '国家:', +'LBL_DESCRIPTION_INFORMATION' => '说明信息', + 'LBL_TERMS_INFORMATION' => '期限与条件', + 'LBL_DESCRIPTION' => '说明:', + 'NTC_COPY_BILLING_ADDRESS' => '复制发票地址到送货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '复制送货地址到送货发票地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '您确定要删除这笔数据?', + 'LBL_DUPLICATE' => '客户数据重复', + 'MSG_DUPLICATE' => '建立这个客户数据可能与现有数据重复,您可以选择将数据归属于下面其中一个项目中,或是点选建立新客户来透过刚刚输入的数据建立新项目。', + +'LBL_INVITEE' => '联络人', + 'ERR_DELETE_RECORD' => '必须指定数据编号才能删除客户。', + 'LBL_SELECT_ACCOUNT' => '选择客户', + 'LBL_GENERAL_INFORMATION' => '一般信息', + +//for v4 release added +'LBL_NEW_POTENTIAL' => '新潜在机会', + 'LBL_POTENTIAL_TITLE' => '潜在机会', + 'LBL_NEW_TASK' => '新任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => ' 安排电话联系', + 'LBL_CALL_TITLE' => '电话联系', + 'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '寄发电子邮件', + 'LBL_EMAIL_TITLE' => '电子邮件', + 'LBL_NEW_CONTACT' => '新增联络人', + 'LBL_CONTACT_TITLE' => '联络人', + +//Added vtiger_fields after RC1 - Release + 'LBL_ALL' => '全部', + 'LBL_PROSPECT' => '预期', + 'LBL_INVESTOR' => '投资者', + 'LBL_RESELLER' => '经销商', + 'LBL_PARTNER' => '合作伙伴', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '客户管理工具', +//Added for 4GA + 'Subject' => '主旨', + 'Quote Name' => '报价单名称', + 'Vendor Name' => '厂商名称', + 'Requisition No' => '申请书编号', + 'Tracking Number' => '追踪编号', + 'Contact Name' => '联络人名称', + 'Due Date' => '到期日', + 'Carrier' => '货运商', + 'Type' => '类型', + 'Sales Tax' => '销售税额', + 'Sales Commission' => '销售佣金', + 'Excise Duty' => '货物税', + 'Total' => '总计', + 'Product Name' => '产品名称', + 'Assigned To' => '负责人', + 'Billing Address' => '付款住址', + 'Shipping Address' => '送货住址', + 'Billing City' => '[付款住址]乡镇市区', + 'Billing State' => '[付款住址]县市', + 'Billing Code' => '[付款住址]邮政编码', + 'Billing Country' => '[付款住址]国家', + 'Billing Po Box' => '[付款住址]采购订单信箱', + 'Shipping Po Box' => '[送货住址]采购订单信箱', + 'Shipping City' => '[送货住址]乡镇市区', + 'Shipping State' => '[送货住址]县市', + 'Shipping Code' => '[送货住址]邮政编码', + 'Shipping Country' => '[送货住址]国家', + 'City' => '乡镇市区', + 'State' => '县市', + 'Code' => '邮政编码', + 'Country' => '国家', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Description' => '说明', + 'Potential Name' => '潜在机会名称', + 'Customer No' => '客户编号', + 'Purchase Order' => '采购订单', + 'Vendor Terms' => '厂商条件', + 'Pending' => '等待', + 'Account Name' => '客户名称', + 'Terms & Conditions' => '期限与条件', +//Quote Info + 'LBL_PO_INFORMATION' => '采购订单信息', + 'LBL_PO' => '采购订单:', + + //Added for 4.2 GA + 'LBL_SO_FORM_TITLE' => '业务', + 'LBL_PO_FORM_TITLE' => '采购', + 'LBL_SUBJECT_TITLE' => '主旨', + 'LBL_VENDOR_NAME_TITLE' => '厂商名称', + 'LBL_TRACKING_NO_TITLE' => '追踪编号', + 'LBL_PO_SEARCH_TITLE' => '搜寻采购订单', + 'LBL_SO_SEARCH_TITLE' => '搜寻销售订单', + 'LBL_QUOTE_NAME_TITLE' => '报价单名称', + 'Order Id' => '订单编号', + 'Status' => '状态', + 'PurchaseOrder' => '采购订单', + 'LBL_MY_TOP_PO' => '进行中的最佳采购订单', + +//Added for existing Picklist Entries + +'FedEx'=>'FedEx', +'UPS'=>'UPS', +'USPS'=>'USPS', +'DHL'=>'DHL', +'BlueDart'=>'BlueDart', + + 'Created' => '建立日期', + 'Approved' => '审核日期', + 'Delivered' => '递送日期', + 'Cancelled' => '取消日期', + 'Received Shipment' => '收件日期', +); + +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/footer.php b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/footer.php new file mode 100644 index 00000000..e5b2b016 --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/footer.php @@ -0,0 +1,35 @@ +addDescBlock($description, $app_strings["Description"], $descBlock); + +/* ************** End Description *********************** */ + + + +/* **************** Begin Terms ****************** */ +$termBlock=array("107",$top,"53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/header.php b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/header.php new file mode 100644 index 00000000..00186cf4 --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/header.php @@ -0,0 +1,103 @@ +addImage( $logo_name, $imageBlock); + +// x,y,width +if($org_phone != '') + $phone ="\n".$app_strings["Phone"].":".$org_phone; +$companyBlockPositions=array( "10","23","62" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone."\n".$org_website; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + +// ************** End company information ******************* + + + +// ************* Begin Top-Right Header *************** +// title +$titleBlock=array("147","7"); +$pdf->title( $app_strings["PurchaseOrder"],"", $titleBlock ); + +$soBubble=array("168","17","12"); +$pdf->addBubbleBlock($reqno, $app_strings["Req. No."], $soBubble); + +$poBubble=array("114","17","12"); +$pdf->addBubbleBlock($trno, $app_strings["Tracking No."], $poBubble); + +// page number +$pageBubble=array("147","17",0); +$pdf->addBubbleBlock($page_num, $app_strings["Page"], $pageBubble); +// ************** End Top-Right Header ***************** + + + +// ************** Begin Addresses ************** +// shipping Address +$shipLocation = array("147","40","61"); +if(trim($ship_street)!='') + $shipText = $ship_street."\n"; +if(trim($ship_city) !='') + $shipText .= $ship_city.", "; +if(trim($ship_state)!='' || trim($ship_code)!= '') + $shipText .= $ship_state." ".$ship_code."\n"; + + $shipText .=$ship_country; +$pdf->addTextBlock( $app_strings["Shipping Address"].":", $shipText, $shipLocation ); + +// billing Address +$billPositions = array("10","51","61"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); +// ********** End Addresses ****************** + + + +/* ******** Begin Invoice Data ************************ */ +// issue date block +$issueBlock=array("80","37"); +$pdf->addRecBlock(getDisplayDate(date("Y-m-d")), $app_strings["Issue Date"],$issueBlock); + +// due date block +$dueBlock=array("81","52"); +$pdf->addRecBlock($valid_till, $app_strings["Due Date"],$dueBlock); + +// terms block +$termBlock=array("10","67"); +$pdf->addRecBlock($vendor_name, $app_strings["Vendor Name"], $termBlock); + +// Contact Name block +$conBlock=array("79","67"); +$pdf->addRecBlock($contact_name, $app_strings["Contact Name"],$conBlock); + + +// vtiger_invoice number block +$invBlock=array("145","65"); +$pdf->addRecBlock($po_no, $app_strings["PO Number"],$invBlock); + +/* ************ End Invoice Data ************************ */ + + + +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/lastpage/body.php b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/lastpage/body.php new file mode 100644 index 00000000..fc4720c1 --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/lastpage/body.php @@ -0,0 +1,62 @@ +watermark( $app_strings["Thank You"], $waterMarkPositions, $waterMarkRotate ); +$waterMarkPositions=array("30","130"); +$pdf->watermark( $app_strings["For Your Business"], $waterMarkPositions, $waterMarkRotate ); + +// blowing bubbles +$Bubble=array("10","80","170","4"); +$pdf->addBubble("", "", $Bubble); + +$Bubble=array("168","131","12"); +//$pdf->addBubbleBlock("Neat Look", "For A", $Bubble); +$Bubble=array("10","131","12"); +//$pdf->addBubbleBlock("The Corners", "Line Up", $Bubble); + + +/* ************* Begin Totals ************************** */ +$totalBlock=array("59","135"); +$names=array($app_strings["Subtotal"],$app_strings["Tax"],$app_strings["Adjustment"],$app_strings["Total"]); +$totals=array($price_subtotal,$price_salestax,$price_adjustment,$price_total); +$pdf->addTotalsRec($names,$totals,$totalBlock); +/* ************* End Totals *************************** */ + +// lets add an image :) +$imageBlock=array("15","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); +$imageBlock=array("185","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); + +// descriptions that change sizes! +$descc=count(explode("\n",$description)); +$condc=count(explode("\n",$conditions)); +if( (strlen($description) > 256) || (strlen($conditions) > 256) || $condc >6 || $descc > 6 ) + $num=255; +else + $num=150; + +/* **************** Begin Description ****************** */ +$descBlock=array("10","160","53", $num); +$pdf->addDescBlock($description, $app_strings["Description"], $descBlock); + + +$termBlock=array("107","160","53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/lastpage/footer.php b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/lastpage/footer.php new file mode 100644 index 00000000..fbc268a3 --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/pdf_templates/lastpage/footer.php @@ -0,0 +1,60 @@ +drawLine($linePos); + $i = (($i+$width)+$pad)-1; +} + + +// company addy +if($org_phone != '') +$phone="\n".$app_strings["Phone"].": ".$org_phone; +if($org_fax != '') + $fax ="\n".$app_strings["Fax"].": ".$org_fax; +$companyBlockPositions=array( "10","220","60" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone." ".$fax."\n".$org_website ; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + + +// billing Address +$billPositions = array("85","235","60"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); + +// totals +$totalBlock=array("145","235","10", "110"); +$totalText=$app_strings["Subtotal"].": ".$price_subtotal."\n". + $app_strings["Tax"].": ".$price_salestax."\n". + $app_strings["Adjustment"].": ".$price_adjustment."\n". + $app_strings["Total"].": ".$price_total; +$pdf->addDescBlock($totalText, $app_strings["Total Due"], $totalBlock); + +$blurbBlock=array("10","265","150", "60"); +$blockText=$app_strings["Detach_Info"]; +$pdf->addDescBlock($blockText, $app_strings["Instructions"], $blurbBlock); + +?> diff --git a/oss/vtiger/trunk/modules/PurchaseOrder/updateRelations.php b/oss/vtiger/trunk/modules/PurchaseOrder/updateRelations.php new file mode 100644 index 00000000..b2fe9cbc --- /dev/null +++ b/oss/vtiger/trunk/modules/PurchaseOrder/updateRelations.php @@ -0,0 +1,47 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/CallRelatedList.php b/oss/vtiger/trunk/modules/Quotes/CallRelatedList.php new file mode 100644 index 00000000..abd73162 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/CallRelatedList.php @@ -0,0 +1,70 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['subject']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings,$currentModule; + global $app_strings; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array=getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("CATEGORY",$category); + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + + // 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 + + $smarty->assign("ID",$focus->id); + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$app_strings['Quote']); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/CreatePDF.php b/oss/vtiger/trunk/modules/Quotes/CreatePDF.php new file mode 100644 index 00000000..de0223ab --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/CreatePDF.php @@ -0,0 +1,28 @@ +Output($filepath,'F'); //added file name to make it work in IE, also forces the download giving the user the option to save + +}else { + $pdf->Output('Quotes.pdf','D'); //added file name to make it work in IE, also forces the download giving the user the option to save + exit(); +} + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/CustomView.php b/oss/vtiger/trunk/modules/Quotes/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Quotes/Delete.php b/oss/vtiger/trunk/modules/Quotes/Delete.php new file mode 100644 index 00000000..ca991da1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/Delete.php @@ -0,0 +1,39 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/DetailView.php b/oss/vtiger/trunk/modules/Quotes/DetailView.php new file mode 100644 index 00000000..02634d8d --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/DetailView.php @@ -0,0 +1,137 @@ +retrieve_entity_info($_REQUEST['record'],"Quotes"); + $focus->id = $_REQUEST['record']; + $focus->name=$focus->column_fields['subject']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("Quote detail view"); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); + +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +// 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 + +$smarty->assign("SINGLE_MOD",'Quote'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +if(isPermitted("Quotes","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + + +$smarty->assign("CREATEPDF","permitted"); + +if(isPermitted("SalesOrder","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("CONVERTSALESORDER","permitted"); + +if(isPermitted("Invoice","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("CONVERTINVOICE","permitted"); + +if(isPermitted("Quotes","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + + +$smarty->assign("CONVERTMODE",'quotetoinvoice'); +$smarty->assign("MODULE", $currentModule); + +//Get the associated Products and then display above Terms and Conditions +$smarty->assign("ASSOCIATED_PRODUCTS",getDetailAssociatedProducts('Quotes',$focus)); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + + $tabid = getTabid("Quotes"); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("SinglePane_View", $singlepane_view); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("Inventory/InventoryDetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/DetailViewAjax.php b/oss/vtiger/trunk/modules/Quotes/DetailViewAjax.php new file mode 100644 index 00000000..f116e5c0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/DetailViewAjax.php @@ -0,0 +1,45 @@ +retrieve_entity_info($crmid,"Quotes"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Quotes"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/EditView.php b/oss/vtiger/trunk/modules/Quotes/EditView.php new file mode 100644 index 00000000..90a4a935 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/EditView.php @@ -0,0 +1,276 @@ +debug("Inside Quote EditView"); + +$focus = CRMEntity::getInstance($currentModule); +$smarty = new vtigerCRM_Smarty; +//added to fix the issue4600 +$searchurl = getBasic_Advance_SearchURL(); +$smarty->assign("SEARCH", $searchurl); +//4600 ends + +$currencyid=fetchCurrency($current_user->id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; + +if(isset($_REQUEST['record']) && $_REQUEST['record'] != ''){ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $log->debug("Mode is Edit. Quoteid is ".$focus->id); + $focus->retrieve_entity_info($_REQUEST['record'],"Quotes"); + $focus->name=$focus->column_fields['subject']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $smarty->assign("DUPLICATE_FROM", $focus->id); + $QUOTE_associated_prod = getAssociatedProducts("Quotes",$focus); + $log->debug("Mode is Duplicate. Quoteid to be duplicated is ".$focus->id); + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +if(isset($_REQUEST['potential_id']) && $_REQUEST['potential_id'] !=''){ + $focus->column_fields['potential_id'] = $_REQUEST['potential_id']; + $relatedInfo = getRelatedInfo($_REQUEST['potential_id']); + if(!empty($relatedInfo)){ + $setype = $relatedInfo["setype"]; + $relID = $relatedInfo["relID"]; + } + if($setype == 'Accounts'){ + $_REQUEST['account_id'] = $relID; + }elseif($setype == 'Contacts'){ + $_REQUEST['contact_id'] = $relID; + } + $log->debug("Quotes EditView: Potential Id from the request is ".$_REQUEST['potential_id']); + $associated_prod = getAssociatedProducts("Potentials",$focus,$focus->column_fields['potential_id']); +} + +if(isset($_REQUEST['product_id']) && $_REQUEST['product_id'] !=''){ + $focus->column_fields['product_id'] = $_REQUEST['product_id']; + $log->debug("Product Id from the request is ".$_REQUEST['product_id']); + $associated_prod = getAssociatedProducts("Products",$focus,$focus->column_fields['product_id']); + for ($i=1; $i<=count($associated_prod);$i++) { + $associated_prod_id = $associated_prod[$i]['hdnProductId'.$i]; + $associated_prod_prices = getPricesForProducts($currencyid,array($associated_prod_id),'Products'); + $associated_prod[$i]['listPrice'.$i] = $associated_prod_prices[$associated_prod_id]; + } + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); +} + +if(!empty($_REQUEST['parent_id']) && !empty($_REQUEST['return_module'])){ + if ($_REQUEST['return_module'] == 'Services') { + $focus->column_fields['product_id'] = $_REQUEST['parent_id']; + $log->debug("Service Id from the request is ".$_REQUEST['parent_id']); + $associated_prod = getAssociatedProducts("Services",$focus,$focus->column_fields['product_id']); + for ($i=1; $i<=count($associated_prod);$i++) { + $associated_prod_id = $associated_prod[$i]['hdnProductId'.$i]; + $associated_prod_prices = getPricesForProducts($currencyid,array($associated_prod_id),'Services'); + $associated_prod[$i]['listPrice'.$i] = $associated_prod_prices[$associated_prod_id]; + } + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + } +} + +// Get Account address if vtiger_account is given +if(isset($_REQUEST['account_id']) && $_REQUEST['account_id']!='' && $_REQUEST['record']==''){ + require_once('modules/Accounts/Accounts.php'); + $acct_focus = new Accounts(); + $acct_focus->retrieve_entity_info($_REQUEST['account_id'],"Accounts"); + $focus->column_fields['bill_city']=$acct_focus->column_fields['bill_city']; + $focus->column_fields['ship_city']=$acct_focus->column_fields['ship_city']; + //added to fix the issue 4526 + $focus->column_fields['bill_pobox']=$acct_focus->column_fields['bill_pobox']; + $focus->column_fields['ship_pobox']=$acct_focus->column_fields['ship_pobox']; + $focus->column_fields['bill_street']=$acct_focus->column_fields['bill_street']; + $focus->column_fields['ship_street']=$acct_focus->column_fields['ship_street']; + $focus->column_fields['bill_state']=$acct_focus->column_fields['bill_state']; + $focus->column_fields['ship_state']=$acct_focus->column_fields['ship_state']; + $focus->column_fields['bill_code']=$acct_focus->column_fields['bill_code']; + $focus->column_fields['ship_code']=$acct_focus->column_fields['ship_code']; + $focus->column_fields['bill_country']=$acct_focus->column_fields['bill_country']; + $focus->column_fields['ship_country']=$acct_focus->column_fields['ship_country']; + $log->debug("Accountid Id from the request is ".$_REQUEST['account_id']); +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +$mode = $focus->mode; +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $bas_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS'); + $adv_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'ADV'); + $blocks['basicTab'] = $bas_block; + if(is_array($adv_block )) + $blocks['moreTab'] = $adv_block; + + $smarty->assign("BLOCKS",$blocks); + $smarty->assign("BLOCKS_COUNT",count($blocks)); +} +$smarty->assign("OP_MODE",$disp_view); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Quote'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$log->info("Quote view"); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + + +if (isset($focus->name)) $smarty->assign("NAME", $focus->name); +else $smarty->assign("NAME", ""); +if(isset($cust_fld)) +{ + + $log->debug("Custom Field is present"); + $smarty->assign("CUSTOMFIELD", $cust_fld); +} + + + +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $associated_prod = getAssociatedProducts("Quotes",$focus);//getProductDetailsBlockInfo('edit','Quotes',$focus); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $focus->mode); + +} +elseif(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $smarty->assign("ASSOCIATEDPRODUCTS", $QUOTE_associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + $smarty->assign("MODE", $focus->mode); + +} +elseif((isset($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '') || (isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != '')) { + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $focus->mode); + + //this is to display the Product Details in first row when we create new PO from Product relatedlist + if($_REQUEST['return_module'] == 'Products') + { + $smarty->assign("PRODUCT_ID",vtlib_purify($_REQUEST['product_id'])); + $smarty->assign("PRODUCT_NAME",getProductName($_REQUEST['product_id'])); + $smarty->assign("UNIT_PRICE",vtlib_purify($_REQUEST['product_id'])); + $smarty->assign("QTY_IN_STOCK",getPrdQtyInStck($_REQUEST['product_id'])); + $smarty->assign("VAT_TAX",getProductTaxPercentage("VAT",$_REQUEST['product_id'])); + $smarty->assign("SALES_TAX",getProductTaxPercentage("Sales",$_REQUEST['product_id'])); + $smarty->assign("SERVICE_TAX",getProductTaxPercentage("Service",$_REQUEST['product_id'])); + } +} +else +{ + $smarty->assign("ROWCOUNT", '1'); +} + +if(isset($_REQUEST['return_module'])) $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else $smarty->assign("RETURN_MODULE","Quotes"); +if(isset($_REQUEST['return_action'])) $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else $smarty->assign("RETURN_ACTION","index"); +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +//in create new Quote, get all available product taxes and shipping & Handling taxes + +if($focus->mode != 'edit') +{ + $tax_details = getAllTaxes('available'); + $sh_tax_details = getAllTaxes('available','sh'); +} +else +{ + $tax_details = getAllTaxes('available','',$focus->mode,$focus->id); + $sh_tax_details = getAllTaxes('available','sh','edit',$focus->id); +} +$smarty->assign("GROUP_TAXES",$tax_details); +$smarty->assign("SH_TAXES",$sh_tax_details); + +$tabid = getTabid("Quotes"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$smarty->assign("MODULE", $module); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +$smarty->assign("CURRENCIES_LIST", getAllCurrencies()); +if($focus->mode == 'edit' || $_REQUEST['isDuplicate'] == 'true') { + $inventory_cur_info = getInventoryCurrencyInfo('Quotes', $focus->id); + $smarty->assign("INV_CURRENCY_ID", $inventory_cur_info['currency_id']); +} else { + $smarty->assign("INV_CURRENCY_ID", $currencyid); +} + +if($focus->mode == 'edit') + $smarty->display("Inventory/InventoryEditView.tpl"); +else + $smarty->display('Inventory/InventoryCreateView.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/ListTopQuotes.php b/oss/vtiger/trunk/modules/Quotes/ListTopQuotes.php new file mode 100644 index 00000000..534e78fd --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/ListTopQuotes.php @@ -0,0 +1,137 @@ +$title,'Header'=>$listview_header,'Entries'=>$listview_entries) where as listview_header and listview_entries are arrays of header and entity values which are returned from function getListViewHeader and getListViewEntries + */ +function getTopQuotes($maxval,$calCnt) +{ + require_once("data/Tracker.php"); + require_once('modules/Quotes/Quotes.php'); + require_once('include/logging.php'); + require_once('include/ListView/ListView.php'); + require_once('include/utils/utils.php'); + require_once('modules/CustomView/CustomView.php'); + + global $app_strings,$current_language,$current_user; + $current_module_strings = return_module_language($current_language, 'Quotes'); + + global $list_max_entries_per_page,$adb,$theme,$mod_strings; + $log = LoggerManager::getLogger('quote_list'); + + $url_string = ''; + $sorder = ''; + $oCustomView = new CustomView("Quotes"); + $customviewcombo_html = $oCustomView->getCustomViewCombo(); + if(isset($_REQUEST['viewname']) == false || $_REQUEST['viewname']=='') + { + if($oCustomView->setdefaultviewid != "") + { + $viewid = $oCustomView->setdefaultviewid; + }else + { + $viewid = "0"; + } + } + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + //Retreive the list from Database + //<<<<<<<<>>>>>>>> + $date_var = date('Y-m-d'); + + $where = " and vtiger_crmentity.smownerid=".$current_user->id." and vtiger_quotes.quotestage not in('Rejected','Accepted','".$current_module_strings['Rejected']."','".$current_module_strings['Accepted']."') and vtiger_quotes.validtill >= '".$date_var."'"; + //$where = ' and vtiger_crmentity.smownerid='.$current_user->id.' and vtiger_quotes.validtill >= \''.$date_var.'\''; + + + $query = getListQuery("Quotes",$where); + $query .=" ORDER BY total DESC"; + //<<<<<<<>>>>>>>> + + $query .= " LIMIT " . $adb->sql_escape_string($maxval); + + if($calCnt == 'calculateCnt') { + $list_result_rows = $adb->query(mkCountQuery($query)); + return $adb->query_result($list_result_rows, 0, 'count'); + } + + $list_result = $adb->query($query); + + //Retreiving the no of rows + $noofrows = $adb->num_rows($list_result); + + //Retreiving the start value from request + if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); + } else { + $start = 1; + } + + //Retreive the Navigation array + $navigation_array = getNavigationValues($start, $noofrows, $list_max_entries_per_page); + + if ($navigation_array['start'] == 1) + { + if($noofrows != 0) + $start_rec = $navigation_array['start']; + else + $start_rec = 0; + if($noofrows > $list_max_entries_per_page) + { + $end_rec = $navigation_array['start'] + $list_max_entries_per_page - 1; + } + else + { + $end_rec = $noofrows; + } + + } + else + { + if($navigation_array['next'] > $list_max_entries_per_page) + { + $start_rec = $navigation_array['next'] - $list_max_entries_per_page; + $end_rec = $navigation_array['next'] - 1; + } + else + { + $start_rec = $navigation_array['prev'] + $list_max_entries_per_page; + $end_rec = $noofrows; + } + } + + $focus = new Quotes(); + + + $title=array('TopOpenQuotes.gif',$current_module_strings['LBL_MY_TOP_QUOTE'],'home_mytopquote'); + //Retreive the List View Table Header + $listview_header = getListViewHeader($focus,"Quotes",$url_string,$sorder,$order_by,"HomePage",$oCustomView); + $header = Array($listview_header[1],$listview_header[3]); + + $listview_entries = getListViewEntries($focus,"Quotes",$list_result,$navigation_array,"HomePage","","EditView","Delete",$oCustomView); + foreach($listview_entries as $crmid=>$valuearray) + { + $entries[$crmid] = Array($valuearray[1],$valuearray[3]); + } + + $search_qry = "&query=true&Fields0=vtiger_crmentity.smownerid&Condition0=is&Srch_value0=".$current_user->column_fields['user_name']."&Fields1=vtiger_quotes.validtill&Condition1=grteq&Srch_value1=".$date_var."&Fields2=vtiger_quotes.quotestage&Condition2=isn&Srch_value2=Rejected&Fields3=vtiger_quotes.quotestage&Condition3=isn&Srch_value3=Accepted&searchtype=advance&search_cnt=4&matchtype=all"; + + $values=Array('ModuleName'=>'Quotes','Title'=>$title,'Header'=>$header,'Entries'=>$entries,'search_qry'=>$search_qry); + + if ( ($display_empty_home_blocks && $noofrows == 0 ) || ($noofrows>0) ) + return $values; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/ListView.php b/oss/vtiger/trunk/modules/Quotes/ListView.php new file mode 100644 index 00000000..980e2955 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/ListView.php @@ -0,0 +1,221 @@ +initSortbyField('Quotes'); +// END +$smarty = new vtigerCRM_Smarty; +$other_text = Array(); + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to Change/Delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['QUOTES_ORDER_BY'] = $order_by; +$_SESSION['QUOTES_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); + +} + +//<<<>>>>>> +$oCustomView = new CustomView("Quotes"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//<<<<>>>> +$smarty->assign("CHANGE_OWNER",getUserslist()); +$smarty->assign("CHANGE_GROUP_OWNER",getGroupslist()); + +if(isPermitted('Quotes','Delete','') == 'yes') +{ + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +} +if(isPermitted('Quotes','EditView','') == 'yes') +{ + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; + $other_text['c_owner'] = $app_strings[LBL_CHANGE_OWNER]; +} +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Quote'); +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("BUTTONS", $other_text); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Quotes"); + $query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Quotes"); +}else +{ + $query = getListQuery("Quotes"); +} +//<<<<<<<>>>>>>>> + +if(isset($where) && $where != '') +{ + $query .= ' and '.$where; +} + +if(isset($order_by) && $order_by != '') +{ + if($order_by == 'smownerid') + { + $query .= " ORDER BY case when (vtiger_users.user_name not like '') then vtiger_users.user_name else vtiger_groups.groupname end ".$sorder; + } + else + { + $tablename = getTableNameForField('Quotes',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + + $query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder; + } +} + +//Postgres 8 fixes +if( $adb->dbType == "pgsql") + $query = fixPostgresQuery( $query, $log, 0); + +if(PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true){ + $count_result = $adb->query( mkCountQuery( $query)); + $noofrows = $adb->query_result($count_result,0,"count"); +}else{ + $noofrows = null; +} + +$queryMode = (isset($_REQUEST['query']) && $_REQUEST['query'] == 'true'); +$start = ListViewSession::getRequestCurrentPage($currentModule, $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($query. " OFFSET $limit_start_rec LIMIT $list_max_entries_per_page", array()); +else + $list_result = $adb->pquery($query. " LIMIT $limit_start_rec, $list_max_entries_per_page", array()); + +$recordListRangeMsg = getRecordRangeMessage($list_result, $limit_start_rec); +$smarty->assign('recordListRange',$recordListRangeMsg); + +//Retreive the List View Table Header +if($viewid !='') +$url_string .="&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"Quotes",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search = getSearchListHeaderValues($focus,"Quotes",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER",$listview_header_search); + +$listview_entries = getListViewEntries($focus,"Quotes",$list_result,$navigation_array,"","","EditView","Delete",$oCustomView); +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Quotes","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','subject','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("BUTTONS", $other_text); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/ListViewPagging.php b/oss/vtiger/trunk/modules/Quotes/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/MassEdit.php b/oss/vtiger/trunk/modules/Quotes/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/MassEditSave.php b/oss/vtiger/trunk/modules/Quotes/MassEditSave.php new file mode 100644 index 00000000..0e1f2a6f --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/Popup.php b/oss/vtiger/trunk/modules/Quotes/Popup.php new file mode 100644 index 00000000..491b56b5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/Popup.php @@ -0,0 +1,17 @@ + diff --git a/oss/vtiger/trunk/modules/Quotes/Quotes.js b/oss/vtiger/trunk/modules/Quotes/Quotes.js new file mode 100644 index 00000000..69b1a42c --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/Quotes.js @@ -0,0 +1,52 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + +document.write(""; +exit(); +?> diff --git a/oss/vtiger/trunk/modules/Quotes/Settings.php b/oss/vtiger/trunk/modules/Quotes/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Quotes/TagCloud.php b/oss/vtiger/trunk/modules/Quotes/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Quotes/UnifiedSearch.php b/oss/vtiger/trunk/modules/Quotes/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Quotes/index.php b/oss/vtiger/trunk/modules/Quotes/index.php new file mode 100644 index 00000000..8ee35e33 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/index.php @@ -0,0 +1,54 @@ + + diff --git a/oss/vtiger/trunk/modules/Quotes/language/en_us.lang.php b/oss/vtiger/trunk/modules/Quotes/language/en_us.lang.php new file mode 100644 index 00000000..d2a18bb8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/language/en_us.lang.php @@ -0,0 +1,188 @@ +'Quotes', +'LBL_MODULE_TITLE'=>'Quotes: Home', +'LBL_SEARCH_FORM_TITLE'=>'Quotes Search', +'LBL_LIST_FORM_TITLE'=>'Quotes List', +'LBL_NEW_FORM_TITLE'=>'New Quote', +'LBL_MEMBER_ORG_FORM_TITLE'=>'Member Organizations', + +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_RELATED_PRODUCTS'=>'Product Details', +'LBL_LIST_CITY'=>'City', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_STATE'=>'State', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_EMAIL_ADDRESS'=>'Email Address', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'Account:', +'LBL_PHONE'=>'Phone:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_TICKER_SYMBOL'=>'Ticker Symbol:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_MEMBER_OF'=>'Member of:', +'LBL_EMAIL'=>'Email:', +'LBL_EMPLOYEES'=>'Employees:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_OWNERSHIP'=>'Ownership:', +'LBL_RATING'=>'Rating:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_SIC_CODE'=>'SIC Code:', +'LBL_TYPE'=>'Type:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_Quote_INFORMATION'=>'Account Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_BILLING_ADDRESS'=>'Billing Address:', +'LBL_SHIPPING_ADDRESS'=>'Shipping Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_DESCRIPTION'=>'Description:', +'NTC_COPY_BILLING_ADDRESS'=>'Copy billing address to shipping address', +'NTC_COPY_SHIPPING_ADDRESS'=>'Copy shipping address to billing address', +'NTC_REMOVE_MEMBER_ORG_CONFIRMATION'=>'Are you sure you want to remove this record as a member organization?', +'LBL_DUPLICATE'=>'Potential Duplicate Accounts', +'MSG_DUPLICATE' => 'Creating this vtiger_account may vtiger_potentialy create a duplicate vtiger_account. You may either select an vtiger_account from the list below or you may click on Create New Account to continue creating a new vtiger_account with the previously entered data.', + +'LBL_INVITEE'=>'Contacts', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", + +'LBL_SELECT_ACCOUNT'=>'Select Account', +'LBL_GENERAL_INFORMATION'=>'General Information', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_PROSPECT'=>'Prospect', +'LBL_INVESTOR'=>'Investor', +'LBL_RESELLER'=>'Reseller', +'LBL_PARTNER'=>'Partner', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Account Tools', +//Added for 4GA +'Subject'=>'Subject', +'Potential Name'=>'Potential Name', +'Quote Stage'=>'Quote Stage', +'Valid Till'=>'Valid Till', +'Team'=>'Team', +'Contact Name'=>'Contact Name', +'Currency'=>'Currency', +'Carrier'=>'Carrier', +'Sub Total'=>'Sub Total', +'Shipping'=>'Shipping', +'Inventory Manager'=>'Inventory Manager', +'Type'=>'Type', +'Tax'=>'Tax', +'Total'=>'Total', +'Product Name'=>'Product Name', +'Assigned To'=>'Assigned To', +'Billing Address'=>'Billing Address', +'Shipping Address'=>'Shipping Address', +'Billing City'=>'Billing City', +'Billing State'=>'Billing State', +'Billing Code'=>'Billing Postal Code', +'Billing Country'=>'Billing Country', +'Billing Po Box'=>'Billing PO Box', +'Shipping Po Box'=>'Shipping PO Box', +'Shipping City'=>'Shipping City', +'Shipping State'=>'Shipping State', +'Shipping Code'=>'Shipping Postal Code', +'Shipping Country'=>'Shipping Country', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Description'=>'Description', +'Account Name'=>'Account Name', +'Terms & Conditions'=>'Terms & Conditions', +//Quote Info +'LBL_QUOTE_INFORMATION'=>'Quote Information', +'LBL_TERMS_INFORMATION'=>'Terms & Conditions', +'LBL_QUOTE'=>'Quote:', + +//Added during 4.2 release +'LBL_SUBJECT'=>'Subject:', +'LBL_POTENTIAL_NAME'=>'Potential Name:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_QUOTE_STAGE'=>'Quote Stage:', +'LBL_MY_TOP_QUOTE'=>'My Top Open Quotes', +//'Quote ID'=>'Quote Id', +'Quote'=>'Quote', + +//Added for existing Picklist Entries + +'Created'=>'Created', +'Delivered'=>'Delivered', +'Reviewed'=>'Reviewed', +'Accepted'=>'Accepted', +'Rejected'=>'Rejected', + +'FedEx'=>'FedEx', +'UPS'=>'UPS', +'USPS'=>'USPS', +'DHL'=>'DHL', +'BlueDart'=>'BlueDart', +'Sales Tax'=>'Sales Tax', + +//Added for Reports (5.0.4) +'Tax Type'=>'Tax Type', +'Discount Percent'=>'Discount Percent', +'Discount Amount'=>'Discount Amount', +'Terms & Conditions'=>'Terms & Conditions', +'Adjustment'=>'Adjustment', +'S&H Amount'=>'S&H Amount', + +//Added after 5.0.4 GA +'Quote No'=>'Quote No', +); + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Quotes/language/zh_cn.lang.php new file mode 100644 index 00000000..16a29bc3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/language/zh_cn.lang.php @@ -0,0 +1,178 @@ + '报价单', + 'LBL_MODULE_TITLE' => '报价单: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻报价单', + 'LBL_LIST_FORM_TITLE' => '报价单列表', + 'LBL_NEW_FORM_TITLE' => '新增报价单', + 'LBL_MEMBER_ORG_FORM_TITLE' => '会员所属单位', + + 'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_RELATED_PRODUCTS' => '在线清单', + 'LBL_LIST_CITY' => '乡镇市区', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '县市', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件地址', + 'LBL_LIST_CONTACT_NAME' => '联系人名称', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'客户:', +'LBL_PHONE'=>'电话:', +'LBL_WEBSITE'=>'网站:', +'LBL_FAX'=>'传真:', +'LBL_TICKER_SYMBOL' => '传票符号:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_ANY_PHONE' => '任一电话:', + 'LBL_MEMBER_OF' => '会员:', + 'LBL_EMAIL' => '电子邮件:', + 'LBL_EMPLOYEES' => '员工:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子邮件:', + 'LBL_ANY_EMAIL' => '任一电子邮件:', + 'LBL_OWNERSHIP' => '负责人:', + 'LBL_RATING' => '级别:', + 'LBL_INDUSTRY' => '企业:', + 'LBL_SIC_CODE' => '统一编号:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年收益:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_Quote_INFORMATION' => '客户信息', + 'LBL_CUSTOM_INFORMATION' => '客制信息', + 'LBL_BILLING_ADDRESS' => '发票地址:', + 'LBL_SHIPPING_ADDRESS' => '送货地址:', + 'LBL_ANY_ADDRESS' => '任一地址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '县市:', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '国家:', +'LBL_DESCRIPTION_INFORMATION' => '细节内容', + 'LBL_DESCRIPTION' => '描述:', + 'NTC_COPY_BILLING_ADDRESS' => '复制发票地址到送货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '复制送货地址到发票地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '你确定要移除这笔会员所属单位记录?', + 'LBL_DUPLICATE' => '潜在机会内容复制到客户', + 'MSG_DUPLICATE' => '建立这笔客户数据来自于潜在机会内容,您可以点选公司列表中的公司以复制建立新的公司,并且继承它的相关数据。', + + 'LBL_INVITEE' => '联系人', + 'ERR_DELETE_RECORD' => '要删除账号你必须指定一笔记录编号.', + + 'LBL_SELECT_ACCOUNT' => '选择客户', + 'LBL_GENERAL_INFORMATION' => '一般信息', + +//for v4 release added + 'LBL_NEW_POTENTIAL' => '新增潜在机会', + 'LBL_POTENTIAL_TITLE' => '潜在机会', + + 'LBL_NEW_TASK' => '新增任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => '新增电话记录', + 'LBL_CALL_TITLE' => '电话记录', + 'LBL_NEW_MEETING' => '新增会议记录', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '新增电子邮件', + 'LBL_EMAIL_TITLE' => '邮件', + 'LBL_NEW_CONTACT' => '新增联系人', + 'LBL_CONTACT_TITLE' => '联系人', + +//Added vtiger_fields after RC1 - Release + 'LBL_ALL' => '全部', + 'LBL_PROSPECT' => '期望', + 'LBL_INVESTOR' => '投资者', + 'LBL_RESELLER' => '转售人', + 'LBL_PARTNER' => '伙伴', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '客户工具', +//Added for 4GA + 'Subject' => '标题', + 'Potential Name' => '潜在机会名称', + 'Quote Stage' => '报价单状态', + 'Valid Till' => '有效期至', + 'Team' => '团队', + 'Contact Name' => '联系人名称', + 'Currency' => '货币', + 'Carrier' => '承运单位', + 'Sub Total' => '小计', + 'Shipping' => '运费', + 'Inventory Manager' => '详细目录管理', + 'Type' => '类型', + 'Tax' => '税', + 'Total' => '总计', + 'Product Name' => '商品名称', + 'Assigned To' => '负责人', + 'Billing Address' => '发票地址', + 'Shipping Address' => '送货地址', + 'Billing City' => '[发票地址]乡镇市区', + 'Billing State' => '[发票地址]市(县)', + 'Billing Code' => '[发票地址]邮政编码', + 'Billing Country' => '[发票地址]省(市/自治区)', + 'Billing Po Box' => '[发票地址]采购订单信箱', + 'Shipping Po Box' => '[送货地址]采购订单信箱', + 'Shipping City' => '[送货地址]乡镇市区', + 'Shipping State' => '[送货地址]市(县)', + 'Shipping Code' => '[送货地址]邮政编码', + 'Shipping Country' => '[送货地址]省(市/自治区)', + 'Created Time' => '建档时间', + 'Modified Time' => '修改时间', + 'Description' => '描述', + 'Account Name' => '客户名称', + 'Terms & Conditions' => '期限与条件', +//Quote Info +'LBL_QUOTE_INFORMATION' => '报价单信息', + 'LBL_TERMS_INFORMATION' => '期限与条件', + 'LBL_QUOTE' => '报价单:', + +//Added during 4.2 release + 'LBL_SUBJECT' => '主旨:', + 'LBL_POTENTIAL_NAME' => '潜在机会名称:', + 'LBL_QUOTE_STAGE' => '报价策略:', + 'LBL_MY_TOP_QUOTE' => '我进行中的最佳报价单', + 'Quote ID' => '报价单编号', +//'Quote ID'=>'Quote Id', + 'Quote' => '报价单', + +//Added for existing Picklist Entries + +'Created' => '建立日期', + 'Delivered' => '递送日期', + 'Reviewed' => '已审阅', + 'Accepted' => '已接受', + 'Rejected' => '被拒绝', + 'FedEx' => 'FedEx', + 'UPS' => 'UPS', + 'USPS' => 'USPS', + 'DHL' => 'DHL', + 'BlueDart' => 'BlueDart', +'Sales Tax'=>'销售税', + + +); + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/pdf_templates/footer.php b/oss/vtiger/trunk/modules/Quotes/pdf_templates/footer.php new file mode 100644 index 00000000..dc333d90 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/pdf_templates/footer.php @@ -0,0 +1,32 @@ +addDescBlock($description, $app_strings["Description"], $descBlock); + +/* ************** End Description *********************** */ + + + +/* **************** Begin Terms ****************** */ +$termBlock=array("107",$top,"53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/pdf_templates/header.php b/oss/vtiger/trunk/modules/Quotes/pdf_templates/header.php new file mode 100644 index 00000000..4ad7fe95 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/pdf_templates/header.php @@ -0,0 +1,99 @@ +addImage( $logo_name, $imageBlock); + +// x,y,width +if($org_phone != '') + $phone ="\n".$app_strings["Phone"].":".$org_phone; +$companyBlockPositions=array( "10","23","62" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone."\n".$org_website; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + +// ************** End company information ******************* + + + +// ************* Begin Top-Right Header *************** +// Quote title +$titleBlock=array("163","7"); +$pdf->title( $app_strings["Quote"],"", $titleBlock ); + +// Account Number +$acctBubble=array("147","17","12"); +$pdf->addBubbleBlock($account_id, $app_strings["Account Number"], $acctBubble); + +// page number +$pageBubble=array("180","17",0); +$pdf->addBubbleBlock($page_num, $app_strings["Page"], $pageBubble); +// ************** End Top-Right Header ***************** + + + +// ************** Begin Addresses ************** +// shipping Address +$shipLocation = array("147","40","61"); +if(trim($ship_street)!='') + $shipText = $ship_street."\n"; +if(trim($ship_city) !='') + $shipText .= $ship_city.", "; +if(trim($ship_state)!='' || trim($ship_code)!= '') + $shipText .= $ship_state." ".$ship_code."\n"; + + $shipText .=$ship_country; +$pdf->addTextBlock( $app_strings["Shipping Address"].":", $shipText, $shipLocation ); + +// billing Address +$billPositions = array("10","51","61"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); +// ********** End Addresses ****************** + + + +/* ******** Begin Quote Data ************************ */ +// issue date block +$issueBlock=array("80","35"); +$pdf->addRecBlock(getDisplayDate(date("Y-m-d")), $app_strings["Issue Date"],$issueBlock); + +// valid till block +$dueBlock=array("80","50"); +$pdf->addRecBlock($valid_till, $app_strings["Valid Till"],$dueBlock); + +// customer name block +$termBlock=array("10","67"); +$pdf->addRecBlock($account_name, $app_strings["Customer Name"], $termBlock); + + +// Contact Name block +$conBlock=array("79","65"); +$pdf->addRecBlock($contact_name, $app_strings["Contact Name"],$conBlock); + + +// quote number block +$invBlock=array("147","65"); +$pdf->addRecBlock($quote_no, $app_strings["Quote Number"],$invBlock); + +/* ************ End Quote Data ************************ */ + + + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/pdf_templates/lastpage/body.php b/oss/vtiger/trunk/modules/Quotes/pdf_templates/lastpage/body.php new file mode 100644 index 00000000..fc4720c1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/pdf_templates/lastpage/body.php @@ -0,0 +1,62 @@ +watermark( $app_strings["Thank You"], $waterMarkPositions, $waterMarkRotate ); +$waterMarkPositions=array("30","130"); +$pdf->watermark( $app_strings["For Your Business"], $waterMarkPositions, $waterMarkRotate ); + +// blowing bubbles +$Bubble=array("10","80","170","4"); +$pdf->addBubble("", "", $Bubble); + +$Bubble=array("168","131","12"); +//$pdf->addBubbleBlock("Neat Look", "For A", $Bubble); +$Bubble=array("10","131","12"); +//$pdf->addBubbleBlock("The Corners", "Line Up", $Bubble); + + +/* ************* Begin Totals ************************** */ +$totalBlock=array("59","135"); +$names=array($app_strings["Subtotal"],$app_strings["Tax"],$app_strings["Adjustment"],$app_strings["Total"]); +$totals=array($price_subtotal,$price_salestax,$price_adjustment,$price_total); +$pdf->addTotalsRec($names,$totals,$totalBlock); +/* ************* End Totals *************************** */ + +// lets add an image :) +$imageBlock=array("15","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); +$imageBlock=array("185","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); + +// descriptions that change sizes! +$descc=count(explode("\n",$description)); +$condc=count(explode("\n",$conditions)); +if( (strlen($description) > 256) || (strlen($conditions) > 256) || $condc >6 || $descc > 6 ) + $num=255; +else + $num=150; + +/* **************** Begin Description ****************** */ +$descBlock=array("10","160","53", $num); +$pdf->addDescBlock($description, $app_strings["Description"], $descBlock); + + +$termBlock=array("107","160","53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/pdf_templates/lastpage/footer.php b/oss/vtiger/trunk/modules/Quotes/pdf_templates/lastpage/footer.php new file mode 100644 index 00000000..83ece8c5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/pdf_templates/lastpage/footer.php @@ -0,0 +1,61 @@ +drawLine($linePos); + $i = (($i+$width)+$pad)-1; +} + + +// company addy +if($org_phone != '') +$phone="\n".$app_strings["Phone"].": ".$org_phone; +if($org_fax != '') + $fax ="\n".$app_strings["Fax"].": ".$org_fax; +$companyBlockPositions=array( "10","220","60" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone." ".$fax."\n".$org_website ; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + + +// billing Address +$billPositions = array("85","235","60"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; + +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); + +// totals +$totalBlock=array("145","235","10", "110"); +$totalText=$app_strings["Subtotal"].": ".$price_subtotal."\n". + $app_strings["Tax"].": ".$price_salestax."\n". + $app_strings["Adjustment"].": ".$price_adjustment."\n". + $app_strings["Total"].": ".$price_total; +$pdf->addDescBlock($totalText, $app_strings["Total Due"], $totalBlock); + +$blurbBlock=array("10","265","150", "60"); +$blockText=$app_strings["Detach_Info"]; +$pdf->addDescBlock($blockText, $app_strings["Instructions"], $blurbBlock); + +?> diff --git a/oss/vtiger/trunk/modules/Quotes/updateRelations.php b/oss/vtiger/trunk/modules/Quotes/updateRelations.php new file mode 100644 index 00000000..85798501 --- /dev/null +++ b/oss/vtiger/trunk/modules/Quotes/updateRelations.php @@ -0,0 +1,48 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/RecycleBin/EmptyRecyclebin.php b/oss/vtiger/trunk/modules/RecycleBin/EmptyRecyclebin.php new file mode 100644 index 00000000..c646d537 --- /dev/null +++ b/oss/vtiger/trunk/modules/RecycleBin/EmptyRecyclebin.php @@ -0,0 +1,24 @@ +query('DELETE FROM vtiger_crmentity WHERE deleted = 1'); +//TODO Related records for the module records deleted from vtiger_crmentity has to be deleted. +//It needs lookup in the related tables and needs to be removed if doesn't have a reference record in vtiger_crmentity + +$adb->query('DELETE FROM vtiger_relatedlists_rb'); + +$parenttab = getParentTab(); + +header("Location: index.php?module=RecycleBin&action=RecycleBinAjax&file=index&parenttab=$parenttab&mode=ajax"); +?> + diff --git a/oss/vtiger/trunk/modules/RecycleBin/ListView.php b/oss/vtiger/trunk/modules/RecycleBin/ListView.php new file mode 100644 index 00000000..aa6c1b88 --- /dev/null +++ b/oss/vtiger/trunk/modules/RecycleBin/ListView.php @@ -0,0 +1,224 @@ +id.".php"); + +$smarty = new vtigerCRM_Smarty; + +// Data from the below modules will not be allowed to restore +$skip_modules = array('Webmails'); +$skip_tab_ids = array(); + +for($i=0; $i 0) { + $sql .= ' AND tabid NOT IN ('. generateQuestionMarks($skip_tab_ids) .')'; +} +$sql .= ' ORDER BY name'; +$result =$adb->pquery($sql, array($skip_tab_ids)); +$noofrows = $adb->num_rows($result); + +$module_name =Array(); +$module_data =Array(); + +if($noofrows > 0) { + for($x=0,$y=0; $x<$noofrows;$x++) { + $tabid = $adb->query_result($result,$x,'tabid'); + if($is_admin || $profileGlobalPermission[2]==0 || $profileGlobalPermission[1]==0 || $profileTabsPermission[$tabid]==0) { + $mod_name = $adb->query_result($result,$x,"name"); + $module_name[$y] = $mod_name; + $y++; + } + } +} + +if(isset($_REQUEST['selected_module']) && $_REQUEST['selected_module'] != '') { + $select_module = vtlib_purify($_REQUEST['selected_module']); + if (!in_array($select_module, $module_name)) { + show_error_msg(); + } +} else { + if (count($module_name) > 0) { + $select_module = $module_name[0]; + } else { + show_error_msg('no_permitted_modules'); + } +} + +$url_string = ''; +if(isset($_REQUEST['query']) && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",RBSearch($select_module)); + + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); + +} + +$focus = CRMEntity::getInstance($select_module); + +if(count($module_name) > 0) +{ + $cur_mod_view = new CustomView($select_module); + $viewid = $cur_mod_view->getViewId($select_module); + + $list_query = getListQuery($select_module, ''); + $list_query = $cur_mod_view->getModifiedCvListQuery($viewid,$list_query,$select_module); + $list_query = preg_replace("/vtiger_crmentity.deleted\s*=\s*0/i", 'vtiger_crmentity.deleted = 1', $list_query); + //Search criteria added to the list Query + if(isset($where) && $where != '') + { + $list_query .= ' AND '.$where; + } + $count_result = $adb->query( mkCountQuery($list_query)); + $noofrows = $adb->query_result($count_result,0,"count"); + + $rb_listview_header = getListViewHeader($focus, $select_module, '','','','global',$cur_mod_view,'',true); + $listview_header_search=getSearchListHeaderValues($focus,$select_module,$url_string,$sorder,$order_by,"",$cur_mod_view); + $smarty->assign("SEARCHLISTHEADER", $listview_header_search); + + if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') + $start = vtlib_purify($_REQUEST['start']); + else + $start = 1; + + $navigation_array = getNavigationValues($start, $noofrows, $list_max_entries_per_page); + + // Setting the record count string + //modified by rdhital + $start_rec = $navigation_array['start']; + $end_rec = $navigation_array['end_val']; + //By Raju Ends + + //limiting the query + if ($start_rec ==0) + $limit_start_rec = 0; + else + $limit_start_rec = $start_rec -1; + + if( $adb->dbType == "pgsql") + $list_result = $adb->query($list_query. " OFFSET ".$limit_start_rec." LIMIT ".$list_max_entries_per_page); + else + $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] ." ".$noofrows; + + $navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Recyclebin","index",""); + + $lvEntries = getListViewEntries($focus,$select_module,$list_result,$navigation_array,"","","","",$cur_mod_view,'','','',true); +} + +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("RECORD_COUNTS", $record_string); + +//to get the field name that mentions the module +$query = "select fieldname from vtiger_entityname where modulename =?"; +$module_fielaname = $adb->query_result($adb->pquery($query, array($select_module)),0,'fieldname'); + +if(strpos($module_fielaname,',')) +{ + $field_array = explode(',',$module_fielaname); + $index_field = $field_array[0]; +} +else +{ + $index_field = $module_fielaname; +} + +$alphabetical = AlphabeticalSearch($currentModule,'index',$index_field,'true','basic',"","","","",$viewid); + +$category = getParentTab();; + +$check_button = Button_Check($_REQUEST['module']); +$check_button['EditView'] = 'no'; +$smarty->assign("CHECK", $check_button); + +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NUMBER_MODULES",$noofrows); +$smarty->assign("MODULE_NAME",$module_name); +$smarty->assign("SELECTED_MODULE",$select_module); +$smarty->assign("MODULE_DATA",$rb_listview_header); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("CATEGORY",$category); +$smarty->assign("THEME",$theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", return_module_language($current_language,$select_module)); +$smarty->assign("lvEntries", $lvEntries); + +$smarty->assign("IS_ADMIN", $is_admin); + +if($_REQUEST['mode'] != 'ajax') { + $smarty->display(vtlib_getModuleTemplate($currentModule,'RecycleBin.tpl')); +} else { + $smarty->display(vtlib_getModuleTemplate($currentModule,'RecycleBinContents.tpl')); +} + +function show_error_msg($error_type='permission_denied') { + global $theme; + if ($error_type == 'permission_denied') { + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    " + . getTranslatedString('LBL_PERMISSION') . "
    + " . getTranslatedString('LBL_GO_BACK') . "
    +
    +
    "; + echo "
    "; + die(); + } else if ($error_type == 'no_permitted_modules') { + echo ""; + echo "
    "; + echo "
    + + + + + + +
    " + . getTranslatedString('LBL_NO_PERMITTED_MODULES') . "
    +
    "; + echo "
    "; + die(); + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/RecycleBin/RecycleBin.js b/oss/vtiger/trunk/modules/RecycleBin/RecycleBin.js new file mode 100644 index 00000000..21d1d2d1 --- /dev/null +++ b/oss/vtiger/trunk/modules/RecycleBin/RecycleBin.js @@ -0,0 +1,199 @@ +/*+******************************************************************************** + * 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. + *********************************************************************************/ + +document.write("'; +$list_report_form->assign('DATE_FORMAT',$date_format); + +$list_report_form->assign('PRI_MODULE',$primarymodule); +$list_report_form->assign('SEC_MODULE',$secondarymodule); +$reportname = htmlspecialchars($reportname, ENT_COMPAT, $default_charset); +$list_report_form->assign('REPORT_NAME',$reportname); +$reportdescription = htmlspecialchars($reportdescription, ENT_COMPAT, $default_charset); +$list_report_form->assign('REPORT_DESC',$reportdescription); +$list_report_form->assign('FOLDERID',$folderid); +$list_report_form->assign("IMAGE_PATH", $image_path); +$list_report_form->assign("THEME_PATH", $theme_path); +if(isPermitted($primarymodule,'index') == "yes" && $permission==false) +{ + $list_report_form->display("ReportsStep1.tpl"); +} +else +{ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    ".$mod_strings['LBL_NO_PERMISSION']." ".$primarymodule." ".$secondarymodule."
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; +} +?> diff --git a/oss/vtiger/trunk/modules/Reports/PopulateReports.php b/oss/vtiger/trunk/modules/Reports/PopulateReports.php new file mode 100644 index 00000000..1b70f12d --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/PopulateReports.php @@ -0,0 +1,584 @@ +'Account and Contact Reports'), + Array('Lead Reports'=>'Lead Reports'), + Array('Potential Reports'=>'Potential Reports'), + Array('Activity Reports'=>'Activity Reports'), + Array('HelpDesk Reports'=>'HelpDesk Reports'), + Array('Product Reports'=>'Product Reports'), + Array('Quote Reports' =>'Quote Reports'), + Array('PurchaseOrder Reports'=>'PurchaseOrder Reports'), + Array('Invoice Reports'=>'Invoice Reports'), + Array('SalesOrder Reports'=>'SalesOrder Reports'), + Array('Campaign Reports'=>'Campaign Reports') + ); + +$reportmodules = Array(Array('primarymodule'=>'Contacts','secondarymodule'=>'Accounts'), + Array('primarymodule'=>'Contacts','secondarymodule'=>'Accounts'), + Array('primarymodule'=>'Contacts','secondarymodule'=>'Potentials'), + Array('primarymodule'=>'Leads','secondarymodule'=>''), + Array('primarymodule'=>'Leads','secondarymodule'=>''), + Array('primarymodule'=>'Potentials','secondarymodule'=>''), + Array('primarymodule'=>'Potentials','secondarymodule'=>''), + Array('primarymodule'=>'Calendar','secondarymodule'=>''), + Array('primarymodule'=>'Calendar','secondarymodule'=>''), + Array('primarymodule'=>'HelpDesk','secondarymodule'=>'Products'), + Array('primarymodule'=>'HelpDesk','secondarymodule'=>''), + Array('primarymodule'=>'HelpDesk','secondarymodule'=>''), + Array('primarymodule'=>'Products','secondarymodule'=>''), + Array('primarymodule'=>'Products','secondarymodule'=>'Contacts'), + Array('primarymodule'=>'Quotes','secondarymodule'=>''), + Array('primarymodule'=>'Quotes','secondarymodule'=>''), + Array('primarymodule'=>'PurchaseOrder','secondarymodule'=>'Contacts'), + Array('primarymodule'=>'PurchaseOrder','secondarymodule'=>''), + Array('primarymodule'=>'Invoice','secondarymodule'=>''), + Array('primarymodule'=>'SalesOrder','secondarymodule'=>''), + Array('primarymodule'=>'Campaigns','secondarymodule'=>'') + ); + +$selectcolumns = Array(Array('vtiger_contactdetails:firstname:Contacts_First_Name:firstname:V', + 'vtiger_contactdetails:lastname:Contacts_Last_Name:lastname:V', + 'vtiger_contactsubdetails:leadsource:Contacts_Lead_Source:leadsource:V', + 'vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V', + 'vtiger_account:industry:Accounts_industry:industry:V', + 'vtiger_contactdetails:email:Contacts_Email:email:E'), + + Array('vtiger_contactdetails:firstname:Contacts_First_Name:firstname:V', + 'vtiger_contactdetails:lastname:Contacts_Last_Name:lastname:V', + 'vtiger_contactsubdetails:leadsource:Contacts_Lead_Source:leadsource:V', + 'vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V', + 'vtiger_account:industry:Accounts_industry:industry:V', + 'vtiger_contactdetails:email:Contacts_Email:email:E'), + + Array('vtiger_contactdetails:firstname:Contacts_First_Name:firstname:V', + 'vtiger_contactdetails:lastname:Contacts_Last_Name:lastname:V', + 'vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V', + 'vtiger_contactdetails:email:Contacts_Email:email:E', + 'vtiger_potential:potentialname:Potentials_Potential_Name:potentialname:V', + 'vtiger_potential:sales_stage:Potentials_Sales_Stage:sales_stage:V'), + + Array('vtiger_leaddetails:firstname:Leads_First_Name:firstname:V', + 'vtiger_leaddetails:lastname:Leads_Last_Name:lastname:V', + 'vtiger_leaddetails:company:Leads_Company:company:V', + 'vtiger_leaddetails:email:Leads_Email:email:E', + 'vtiger_leaddetails:leadsource:Leads_Lead_Source:leadsource:V'), + + Array('vtiger_leaddetails:firstname:Leads_First_Name:firstname:V', + 'vtiger_leaddetails:lastname:Leads_Last_Name:lastname:V', + 'vtiger_leaddetails:company:Leads_Company:company:V', + 'vtiger_leaddetails:email:Leads_Email:email:E', + 'vtiger_leaddetails:leadsource:Leads_Lead_Source:leadsource:V', + 'vtiger_leaddetails:leadstatus:Leads_Lead_Status:leadstatus:V'), + + Array('vtiger_potential:potentialname:Potentials_Potential_Name:potentialname:V', + 'vtiger_potential:amount:Potentials_Amount:amount:N', + 'vtiger_potential:potentialtype:Potentials_Type:opportunity_type:V', + 'vtiger_potential:leadsource:Potentials_Lead_Source:leadsource:V', + 'vtiger_potential:sales_stage:Potentials_Sales_Stage:sales_stage:V'), + + Array('vtiger_potential:potentialname:Potentials_Potential_Name:potentialname:V', + 'vtiger_potential:amount:Potentials_Amount:amount:N', + 'vtiger_potential:potentialtype:Potentials_Type:opportunity_type:V', + 'vtiger_potential:leadsource:Potentials_Lead_Source:leadsource:V', + 'vtiger_potential:sales_stage:Potentials_Sales_Stage:sales_stage:V'), + + Array('vtiger_activity:subject:Calendar_Subject:subject:V', + 'vtiger_contactdetailsCalendar:lastname:Calendar_Contact_Name:contact_id:I', + 'vtiger_activity:status:Calendar_Status:taskstatus:V', + 'vtiger_activity:priority:Calendar_Priority:taskpriority:V', + 'vtiger_usersCalendar:user_name:Calendar_Assigned_To:assigned_user_id:V'), + + Array('vtiger_activity:subject:Calendar_Subject:subject:V', + 'vtiger_contactdetailsCalendar:lastname:Calendar_Contact_Name:contact_id:I', + 'vtiger_activity:status:Calendar_Status:taskstatus:V', + 'vtiger_activity:priority:Calendar_Priority:taskpriority:V', + 'vtiger_usersCalendar:user_name:Calendar_Assigned_To:assigned_user_id:V'), + + Array('vtiger_troubletickets:title:HelpDesk_Title:ticket_title:V', + 'vtiger_troubletickets:status:HelpDesk_Status:ticketstatus:V', + 'vtiger_products:productname:Products_Product_Name:productname:V', + 'vtiger_products:discontinued:Products_Product_Active:discontinued:V', + 'vtiger_products:productcategory:Products_Product_Category:productcategory:V', + 'vtiger_products:manufacturer:Products_Manufacturer:manufacturer:V'), + + Array('vtiger_troubletickets:title:HelpDesk_Title:ticket_title:V', + 'vtiger_troubletickets:priority:HelpDesk_Priority:ticketpriorities:V', + 'vtiger_troubletickets:severity:HelpDesk_Severity:ticketseverities:V', + 'vtiger_troubletickets:status:HelpDesk_Status:ticketstatus:V', + 'vtiger_troubletickets:category:HelpDesk_Category:ticketcategories:V', + 'vtiger_usersHelpDesk:user_name:HelpDesk_Assigned_To:assigned_user_id:V'), + + Array('vtiger_troubletickets:title:HelpDesk_Title:ticket_title:V', + 'vtiger_troubletickets:priority:HelpDesk_Priority:ticketpriorities:V', + 'vtiger_troubletickets:severity:HelpDesk_Severity:ticketseverities:V', + 'vtiger_troubletickets:status:HelpDesk_Status:ticketstatus:V', + 'vtiger_troubletickets:category:HelpDesk_Category:ticketcategories:V', + 'vtiger_usersHelpDesk:user_name:HelpDesk_Assigned_To:assigned_user_id:V'), + + Array('vtiger_products:productname:Products_Product_Name:productname:V', + 'vtiger_products:productcode:Products_Product_Code:productcode:V', + 'vtiger_products:discontinued:Products_Product_Active:discontinued:V', + 'vtiger_products:productcategory:Products_Product_Category:productcategory:V', + 'vtiger_products:website:Products_Website:website:V', + 'vtiger_vendorRelProducts:vendorname:Products_Vendor_Name:vendor_id:I', + 'vtiger_products:mfr_part_no:Products_Mfr_PartNo:mfr_part_no:V'), + + Array('vtiger_products:productname:Products_Product_Name:productname:V', + 'vtiger_products:manufacturer:Products_Manufacturer:manufacturer:V', + 'vtiger_products:productcategory:Products_Product_Category:productcategory:V', + 'vtiger_contactdetails:firstname:Contacts_First_Name:firstname:V', + 'vtiger_contactdetails:lastname:Contacts_Last_Name:lastname:V', + 'vtiger_contactsubdetails:leadsource:Contacts_Lead_Source:leadsource:V'), + + Array('vtiger_quotes:subject:Quotes_Subject:subject:V', + 'vtiger_potentialRelQuotes:potentialname:Quotes_Potential_Name:potential_id:I', + 'vtiger_quotes:quotestage:Quotes_Quote_Stage:quotestage:V', + 'vtiger_contactdetailsQuotes:lastname:Quotes_Contact_Name:contact_id:V', + 'vtiger_usersRel1:user_name:Quotes_Inventory_Manager:assigned_user_id1:I', + 'vtiger_accountQuotes:accountname:Quotes_Account_Name:account_id:I'), + + Array('vtiger_quotes:subject:Quotes_Subject:subject:V', + 'vtiger_potentialRelQuotes:potentialname:Quotes_Potential_Name:potential_id:I', + 'vtiger_quotes:quotestage:Quotes_Quote_Stage:quotestage:V', + 'vtiger_contactdetailsQuotes:lastname:Quotes_Contact_Name:contact_id:V', + 'vtiger_usersRel1:user_name:Quotes_Inventory_Manager:assigned_user_id1:I', + 'vtiger_accountQuotes:accountname:Quotes_Account_Name:account_id:I', + 'vtiger_quotes:carrier:Quotes_Carrier:carrier:V', + 'vtiger_quotes:shipping:Quotes_Shipping:shipping:V'), + + Array('vtiger_purchaseorder:subject:PurchaseOrder_Subject:subject:V', + 'vtiger_vendorRelPurchaseOrder:vendorname:PurchaseOrder_Vendor_Name:vendor_id:I', + 'vtiger_purchaseorder:tracking_no:PurchaseOrder_Tracking_Number:tracking_no:V', + 'vtiger_contactdetails:firstname:Contacts_First_Name:firstname:V', + 'vtiger_contactdetails:lastname:Contacts_Last_Name:lastname:V', + 'vtiger_contactsubdetails:leadsource:Contacts_Lead_Source:leadsource:V', + 'vtiger_contactdetails:email:Contacts_Email:email:E'), + + Array('vtiger_purchaseorder:subject:PurchaseOrder_Subject:subject:V', + 'vtiger_vendorRelPurchaseOrder:vendorname:PurchaseOrder_Vendor_Name:vendor_id:I', + 'vtiger_purchaseorder:requisition_no:PurchaseOrder_Requisition_No:requisition_no:V', + 'vtiger_purchaseorder:tracking_no:PurchaseOrder_Tracking_Number:tracking_no:V', + 'vtiger_contactdetailsPurchaseOrder:lastname:PurchaseOrder_Contact_Name:contact_id:I', + 'vtiger_purchaseorder:carrier:PurchaseOrder_Carrier:carrier:V', + 'vtiger_purchaseorder:salescommission:PurchaseOrder_Sales_Commission:salescommission:N', + 'vtiger_purchaseorder:exciseduty:PurchaseOrder_Excise_Duty:exciseduty:N', + 'vtiger_usersPurchaseOrder:user_name:PurchaseOrder_Assigned_To:assigned_user_id:V'), + + Array('vtiger_invoice:subject:Invoice_Subject:subject:V', + 'vtiger_invoice:salesorderid:Invoice_Sales_Order:salesorder_id:I', + 'vtiger_invoice:customerno:Invoice_Customer_No:customerno:V', + 'vtiger_invoice:exciseduty:Invoice_Excise_Duty:exciseduty:N', + 'vtiger_invoice:salescommission:Invoice_Sales_Commission:salescommission:N', + 'vtiger_accountInvoice:accountname:Invoice_Account_Name:account_id:I'), + + Array('vtiger_salesorder:subject:SalesOrder_Subject:subject:V', + 'vtiger_quotesSalesOrder:subject:SalesOrder_Quote_Name:quote_id:I', + 'vtiger_contactdetailsSalesOrder:lastname:SalesOrder_Contact_Name:contact_id:I', + 'vtiger_salesorder:duedate:SalesOrder_Due_Date:duedate:D', + 'vtiger_salesorder:carrier:SalesOrder_Carrier:carrier:V', + 'vtiger_salesorder:sostatus:SalesOrder_Status:sostatus:V', + 'vtiger_accountSalesOrder:accountname:SalesOrder_Account_Name:account_id:I', + 'vtiger_salesorder:salescommission:SalesOrder_Sales_Commission:salescommission:N', + 'vtiger_salesorder:exciseduty:SalesOrder_Excise_Duty:exciseduty:N', + 'vtiger_usersSalesOrder:user_name:SalesOrder_Assigned_To:assigned_user_id:V'), + + Array('vtiger_campaign:campaignname:Campaigns_Campaign_Name:campaignname:V', + 'vtiger_campaign:campaigntype:Campaigns_Campaign_Type:campaigntype:V', + 'vtiger_campaign:targetaudience:Campaigns_Target_Audience:targetaudience:V', + 'vtiger_campaign:budgetcost:Campaigns_Budget_Cost:budgetcost:I', + 'vtiger_campaign:actualcost:Campaigns_Actual_Cost:actualcost:I', + 'vtiger_campaign:expectedrevenue:Campaigns_Expected_Revenue:expectedrevenue:I', + 'vtiger_campaign:expectedsalescount:Campaigns_Expected_Sales_Count:expectedsalescount:N', + 'vtiger_campaign:actualsalescount:Campaigns_Actual_Sales_Count:actualsalescount:N', + 'vtiger_usersCampaigns:user_name:Campaigns_Assigned_To:assigned_user_id:V') + ); + +$reports = Array(Array('reportname'=>'Contacts by Accounts', + 'reportfolder'=>'Account and Contact Reports', + 'description'=>'Contacts related to Accounts', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'0'), + + Array('reportname'=>'Contacts without Accounts', + 'reportfolder'=>'Account and Contact Reports', + 'description'=>'Contacts not related to Accounts', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'1'), + + Array('reportname'=>'Contacts by Potentials', + 'reportfolder'=>'Account and Contact Reports', + 'description'=>'Contacts related to Potentials', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'2'), + + Array('reportname'=>'Lead by Source', + 'reportfolder'=>'Lead Reports', + 'description'=>'Lead by Source', + 'reporttype'=>'summary', + 'sortid'=>'0','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Lead Status Report', + 'reportfolder'=>'Lead Reports', + 'description'=>'Lead Status Report', + 'reporttype'=>'summary', + 'sortid'=>'1','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Potential Pipeline', + 'reportfolder'=>'Potential Reports', + 'description'=>'Potential Pipeline', + 'reporttype'=>'summary', + 'sortid'=>'2','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Closed Potentials', + 'reportfolder'=>'Potential Reports', + 'description'=>'Potential that have Won', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'3'), + + Array('reportname'=>'Last Month Activities', + 'reportfolder'=>'Activity Reports', + 'description'=>'Last Month Activities', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'0','advfilterid'=>''), + + Array('reportname'=>'This Month Activities', + 'reportfolder'=>'Activity Reports', + 'description'=>'This Month Activities', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'1','advfilterid'=>''), + + Array('reportname'=>'Tickets by Products', + 'reportfolder'=>'HelpDesk Reports', + 'description'=>'Tickets related to Products', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Tickets by Priority', + 'reportfolder'=>'HelpDesk Reports', + 'description'=>'Tickets by Priority', + 'reporttype'=>'summary', + 'sortid'=>'3','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Open Tickets', + 'reportfolder'=>'HelpDesk Reports', + 'description'=>'Tickets that are Open', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'4'), + + Array('reportname'=>'Product Details', + 'reportfolder'=>'Product Reports', + 'description'=>'Product Detailed Report', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Products by Contacts', + 'reportfolder'=>'Product Reports', + 'description'=>'Products related to Contacts', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Open Quotes', + 'reportfolder'=>'Quote Reports', + 'description'=>'Quotes that are Open', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'5'), + + Array('reportname'=>'Quotes Detailed Report', + 'reportfolder'=>'Quote Reports', + 'description'=>'Quotes Detailed Report', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'PurchaseOrder by Contacts', + 'reportfolder'=>'PurchaseOrder Reports', + 'description'=>'PurchaseOrder related to Contacts', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'PurchaseOrder Detailed Report', + 'reportfolder'=>'PurchaseOrder Reports', + 'description'=>'PurchaseOrder Detailed Report', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Invoice Detailed Report', + 'reportfolder'=>'Invoice Reports', + 'description'=>'Invoice Detailed Report', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'SalesOrder Detailed Report', + 'reportfolder'=>'SalesOrder Reports', + 'description'=>'SalesOrder Detailed Report', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>''), + + Array('reportname'=>'Campaign Expectations and Actuals', + 'reportfolder'=>'Campaign Reports', + 'description'=>'Campaign Expectations and Actuals', + 'reporttype'=>'tabular', + 'sortid'=>'','stdfilterid'=>'','advfilterid'=>'') + + ); + +$sortorder = Array( + Array( + Array('columnname'=>'vtiger_leaddetails:leadsource:Leads_Lead_Source:leadsource:V', + 'sortorder'=>'Ascending' + ) + ), + Array( + Array('columnname'=>'vtiger_leaddetails:leadstatus:Leads_Lead_Status:leadstatus:V', + 'sortorder'=>'Ascending' + ) + ), + Array( + Array('columnname'=>'vtiger_potential:sales_stage:Potentials_Sales_Stage:sales_stage:V', + 'sortorder'=>'Ascending' + ) + ), + Array( + Array('columnname'=>'vtiger_troubletickets:priority:HelpDesk_Priority:ticketpriorities:V', + 'sortorder'=>'Ascending' + ) + ) + ); + +$stdfilters = Array(Array('columnname'=>'vtiger_crmentity:modifiedtime:modifiedtime:Calendar_Modified_Time', + 'datefilter'=>'lastmonth', + 'startdate'=>'2005-05-01', + 'enddate'=>'2005-05-31'), + + Array('columnname'=>'vtiger_crmentity:modifiedtime:modifiedtime:Calendar_Modified_Time', + 'datefilter'=>'thismonth', + 'startdate'=>'2005-06-01', + 'enddate'=>'2005-06-30') + ); + +$advfilters = Array( + Array( + Array('columnname'=>'vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V', + 'comparator'=>'n', + 'value'=>'' + ) + ), + Array( + Array('columnname'=>'vtiger_accountContacts:accountname:Contacts_Account_Name:account_id:V', + 'comparator'=>'e', + 'value'=>'' + ) + ), + Array( + Array('columnname'=>'vtiger_potential:potentialname:Potentials_Potential_Name:potentialname:V', + 'comparator'=>'n', + 'value'=>'' + ) + ), + Array( + Array('columnname'=>'vtiger_potential:sales_stage:Potentials_Sales_Stage:sales_stage:V', + 'comparator'=>'e', + 'value'=>'Closed Won' + ) + ), + Array( + Array('columnname'=>'vtiger_troubletickets:status:HelpDesk_Status:ticketstatus:V', + 'comparator'=>'n', + 'value'=>'Closed' + ) + ), + Array( + Array('columnname'=>'vtiger_quotes:quotestage:Quotes_Quote_Stage:quotestage:V', + 'comparator'=>'n', + 'value'=>'Accepted' + ), + Array('columnname'=>'vtiger_quotes:quotestage:Quotes_Quote_Stage:quotestage:V', + 'comparator'=>'n', + 'value'=>'Rejected' + ) + ) + ); +//quotes:quotestage:Quotes_Quote_Stage:quotestage:V +foreach($rptfolder as $key=>$rptarray) +{ + foreach($rptarray as $foldername=>$folderdescription) + { + PopulateReportFolder($foldername,$folderdescription); + $reportid[$foldername] = $key+1; + } +} + +foreach($reports as $key=>$report) +{ + $queryid = insertSelectQuery(); + insertReports($queryid,$reportid[$report['reportfolder']],$report['reportname'],$report['description'],$report['reporttype']); + insertSelectColumns($queryid,$selectcolumns[$key]); + insertReportModules($queryid,$reportmodules[$key]['primarymodule'],$reportmodules[$key]['secondarymodule']); + + if(isset($stdfilters[$report['stdfilterid']])) + { + $i = $report['stdfilterid']; + insertStdFilter($queryid,$stdfilters[$i]['columnname'],$stdfilters[$i]['datefilter'],$stdfilters[$i]['startdate'],$stdfilters[$i]['enddate']); + } + + if(isset($advfilters[$report['advfilterid']])) + { + insertAdvFilter($queryid,$advfilters[$report['advfilterid']]); + } + + if($report['reporttype'] == "summary") + { + insertSortColumns($queryid,$sortorder[$report['sortid']]); + } +} +$adb->pquery("UPDATE vtiger_report SET sharingtype='Public'",array()); +/** Function to store the foldername and folderdescription to database + * This function accepts the given folder name and description + * ans store it in db as SAVED + */ + +function PopulateReportFolder($fldrname,$fldrdescription) +{ + global $adb; + $sql = "INSERT INTO vtiger_reportfolder (FOLDERNAME,DESCRIPTION,STATE) VALUES(?,?,?)"; + $params = array($fldrname, $fldrdescription, 'SAVED'); + $result = $adb->pquery($sql, $params); +} + +/** Function to add an entry in selestquery vtiger_table + * + */ + +function insertSelectQuery() +{ + global $adb; + $genQueryId = $adb->getUniqueID("vtiger_selectquery"); + if($genQueryId != "") + { + $iquerysql = "insert into vtiger_selectquery (QUERYID,STARTINDEX,NUMOFOBJECTS) values (?,?,?)"; + $iquerysqlresult = $adb->pquery($iquerysql, array($genQueryId,0,0)); + } + + return $genQueryId; +} + +/** Function to store the vtiger_field names selected for a vtiger_report to a database + * + * + */ + +function insertSelectColumns($queryid,$columnname) +{ + global $adb; + if($queryid != "") + { + for($i=0;$i < count($columnname);$i++) + { + $icolumnsql = "insert into vtiger_selectcolumn (QUERYID,COLUMNINDEX,COLUMNNAME) values (?,?,?)"; + $icolumnsqlresult = $adb->pquery($icolumnsql, array($queryid, $i, $columnname[$i])); + } + } +} + + +/** Function to store the vtiger_report details to database + * This function accepts queryid,folderid,reportname,description,reporttype + * as arguments and store the informations in vtiger_report vtiger_table + */ + +function insertReports($queryid,$folderid,$reportname,$description,$reporttype) +{ + global $adb; + if($queryid != "") + { + $ireportsql = "insert into vtiger_report (REPORTID,FOLDERID,REPORTNAME,DESCRIPTION,REPORTTYPE,QUERYID,STATE) values (?,?,?,?,?,?,?)"; + $ireportparams = array($queryid, $folderid, $reportname, $description, $reporttype, $queryid, 'SAVED'); + $ireportresult = $adb->pquery($ireportsql, $ireportparams); + } +} + +/** Function to store the vtiger_report modules to database + * This function accepts queryid,primary module and secondary module + * as arguments and store the informations in vtiger_reportmodules vtiger_table + */ + + +function insertReportModules($queryid,$primarymodule,$secondarymodule) +{ + global $adb; + if($queryid != "") + { + $ireportmodulesql = "insert into vtiger_reportmodules (REPORTMODULESID,PRIMARYMODULE,SECONDARYMODULES) values (?,?,?)"; + $ireportmoduleresult = $adb->pquery($ireportmodulesql, array($queryid, $primarymodule, $secondarymodule)); + } +} + + +/** Function to store the vtiger_report sortorder to database + * This function accepts queryid,sortlists + * as arguments and store the informations sort columns and + * and sortorder in vtiger_reportsortcol vtiger_table + */ + + +function insertSortColumns($queryid,$sortlists) +{ + global $adb; + if($queryid != "") + { + foreach($sortlists as $i=>$sort) + { + $sort_bysql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_byresult = $adb->pquery($sort_bysql, array(($i+1), $queryid, $sort['columnname'], $sort['sortorder'])); + } + } + +} + + +/** Function to store the vtiger_report sort date details to database + * This function accepts queryid,filtercolumn,datefilter,startdate,enddate + * as arguments and store the informations in vtiger_reportdatefilter vtiger_table + */ + + +function insertStdFilter($queryid,$filtercolumn,$datefilter,$startdate,$enddate) +{ + global $adb; + if($queryid != "") + { + $ireportmodulesql = "insert into vtiger_reportdatefilter (DATEFILTERID,DATECOLUMNNAME,DATEFILTER,STARTDATE,ENDDATE) values (?,?,?,?,?)"; + $ireportmoduleresult = $adb->pquery($ireportmodulesql, array($queryid, $filtercolumn, $datefilter, $startdate, $enddate)); + } + +} + +/** Function to store the vtiger_report conditions to database + * This function accepts queryid,filters + * as arguments and store the informations in vtiger_relcriteria vtiger_table + */ + + +function insertAdvFilter($queryid,$filters) +{ + global $adb; + if($queryid != "") + { + foreach($filters as $i=>$filter) + { + $irelcriteriasql = "insert into vtiger_relcriteria(QUERYID,COLUMNINDEX,COLUMNNAME,COMPARATOR,VALUE) values (?,?,?,?,?)"; + $irelcriteriaresult = $adb->pquery($irelcriteriasql, array($queryid,$i,$filter['columnname'],$filter['comparator'],$filter['value'])); + } + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Reports/PrintReport.php b/oss/vtiger/trunk/modules/Reports/PrintReport.php new file mode 100644 index 00000000..800885a8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/PrintReport.php @@ -0,0 +1,37 @@ +RunTimeFilter($filtercolumn,$filter,$startdate,$enddate); + +$arr_values = $oReportRun->GenerateReport("PRINT",$filterlist); +$total_report = $oReportRun->GenerateReport("PRINT_TOTAL",$filterlist); +$oPrint_smarty->assign("COUNT",$arr_values[1]); +$oPrint_smarty->assign("APP",$app_strings); +$oPrint_smarty->assign("MOD",$mod_strings); +$oPrint_smarty->assign("REPORT_NAME",$oReport->reportname); +$oPrint_smarty->assign("PRINT_CONTENTS",$arr_values[0]); +$oPrint_smarty->assign("TOTAL_HTML",$total_report); +$oPrint_smarty->display("PrintReport.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Reports/ReportColumns.php b/oss/vtiger/trunk/modules/Reports/ReportColumns.php new file mode 100644 index 00000000..05f72991 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportColumns.php @@ -0,0 +1,158 @@ +assign("MOD", $mod_strings); +$report_column->assign("APP", $app_strings); +$report_column->assign("IMAGE_PATH",$image_path); +$report_column->assign("THEME_PATH",$theme_path); +if(isset($_REQUEST["record"]) && $_REQUEST['record']!='') +{ + $recordid = vtlib_purify($_REQUEST["record"]); + $oReport = new Reports($recordid); + $BLOCK1 = getPrimaryColumnsHTML($oReport->primodule); + + $oRep = new Reports(); + $secondarymodule = ''; + $secondarymodules =Array(); + if(!empty($oRep->related_modules[$oReport->primodule])) { + foreach($oRep->related_modules[$oReport->primodule] as $key=>$value){ + if(isset($_REQUEST["secondarymodule_".$value]))$secondarymodules []= $_REQUEST["secondarymodule_".$value]; + } + } + $secondarymodule = implode(":",$secondarymodules); + + $oReport->secmodule = $secondarymodule; + $BLOCK1 .= getSecondaryColumnsHTML($oReport->secmodule); + $BLOCK2 = $oReport->getSelectedColumnsList($recordid); + $report_column->assign("BLOCK1",$BLOCK1); + $report_column->assign("BLOCK2",$BLOCK2); +}else +{ + $primarymodule = vtlib_purify($_REQUEST["primarymodule"]); + $BLOCK1 = getPrimaryColumnsHTML($primarymodule); + $ogReport = new Reports(); + if(!empty($ogReport->related_modules[$primarymodule])) { + foreach($ogReport->related_modules[$primarymodule] as $key=>$value){ + $BLOCK1 .= getSecondaryColumnsHTML($_REQUEST["secondarymodule_".$value]); + } + } + + $report_column->assign("BLOCK1",$BLOCK1); + +} + +/** Function to formulate the vtiger_fields for the primary modules + * This function accepts the module name + * as arguments and generates the vtiger_fields for the primary module as + * a HTML Combo values + */ + +function getPrimaryColumnsHTML($module) +{ + global $ogReport; + global $app_list_strings; + global $app_strings; + global $current_language; + $id_added=false; + $mod_strings = return_module_language($current_language,$module); + $block_listed = array(); + foreach($ogReport->module_list[$module] as $key=>$value) + { + if(isset($ogReport->pri_module_columnslist[$module][$value]) && !$block_listed[$value]) + { + $block_listed[$value] = true; + $shtml .= ""; + if($id_added==false){ + $shtml .= ""; + $id_added=true; + } + foreach($ogReport->pri_module_columnslist[$module][$value] as $field=>$fieldlabel) + { + if(isset($mod_strings[$fieldlabel])) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + } + } + } + return $shtml; +} + +/** Function to formulate the vtiger_fields for the secondary modules + * This function accepts the module name + * as arguments and generates the vtiger_fields for the secondary module as + * a HTML Combo values + */ + + +function getSecondaryColumnsHTML($module) +{ + global $ogReport; + global $app_list_strings,$app_strings; + global $current_language; + + if($module != "") + { + $secmodule = explode(":",$module); + for($i=0;$i < count($secmodule) ;$i++) + { + $mod_strings = return_module_language($current_language,$secmodule[$i]); + if(vtlib_isModuleActive($secmodule[$i])){ + $block_listed = array(); + foreach($ogReport->module_list[$secmodule[$i]] as $key=>$value) + { + if(isset($ogReport->sec_module_columnslist[$secmodule[$i]][$value]) && !$block_listed[$value]) + { + $block_listed[$value] = true; + $shtml .= ""; + foreach($ogReport->sec_module_columnslist[$secmodule[$i]][$value] as $field=>$fieldlabel) + { + if(isset($mod_strings[$fieldlabel])) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + } + } + } + } + } + } + return $shtml; +} + +$report_column->display("ReportColumns.tpl"); +?> + diff --git a/oss/vtiger/trunk/modules/Reports/ReportColumnsTotal.php b/oss/vtiger/trunk/modules/Reports/ReportColumnsTotal.php new file mode 100644 index 00000000..add6a387 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportColumnsTotal.php @@ -0,0 +1,75 @@ +assign("MOD", $mod_strings); +$report_column_tot->assign("APP", $app_strings); +$report_column_tot->assign("IMAGE_PATH",$image_path); + +if(isset($_REQUEST["record"]) && $_REQUEST['record']!='') +{ + $recordid = vtlib_purify($_REQUEST["record"]); + $oReport = new Reports($recordid); + $oRep = new Reports(); + $secondarymodule = ''; + $secondarymodules =Array(); + + if(!empty($oRep->related_modules[$oReport->primodule])) { + foreach($oRep->related_modules[$oReport->primodule] as $key=>$value){ + if(isset($_REQUEST["secondarymodule_".$value]))$secondarymodules []= vtlib_purify($_REQUEST["secondarymodule_".$value]); + } + } + $secondarymodule = implode(":",$secondarymodules); + $oReport->secmodule = $secondarymodule; + + $BLOCK1 = $oReport->sgetColumntoTotalSelected($oReport->primodule,$oReport->secmodule,$recordid); + $report_column_tot->assign("BLOCK1",$BLOCK1); + $report_column_tot->assign("RECORDID",$recordid); +}else +{ + $primarymodule = vtlib_purify($_REQUEST["primarymodule"]); + $oReport = new Reports(); + $secondarymodule = Array(); + if(!empty($ogReport->related_modules[$primarymodule])) { + foreach($ogReport->related_modules[$primarymodule] as $key=>$value){ + $secondarymodule[] = vtlib_purify($_REQUEST["secondarymodule_".$value]); + + } + } + $BLOCK1 = $oReport->sgetColumntoTotal($primarymodule,$secondarymodule); + $report_column_tot->assign("BLOCK1",$BLOCK1); +} +//added to avoid displaying "No data avaiable to total" when using related modules in report. +if(count($BLOCK1[0]) == 0 && count($BLOCK1[1])==0) + $report_column_tot->assign("ROWS_COUNT",0); +else + $report_column_tot->assign("ROWS_COUNT","-1"); + +$report_column_tot->display('ReportColumnsTotal.tpl'); +?> diff --git a/oss/vtiger/trunk/modules/Reports/ReportFilters.php b/oss/vtiger/trunk/modules/Reports/ReportFilters.php new file mode 100644 index 00000000..14feedc5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportFilters.php @@ -0,0 +1,42 @@ +***************************/ + +require_once('Smarty_setup.php'); +require_once("data/Tracker.php"); +require_once('include/logging.php'); +require_once('include/utils/utils.php'); +require_once('modules/Reports/Reports.php'); + +global $app_strings; +global $app_list_strings; +global $mod_strings; +$current_module_strings = return_module_language($current_language, 'Reports'); +global $list_max_entries_per_page; +global $urlPrefix; + +$log = LoggerManager::getLogger('report_type'); +global $currentModule; +global $image_path; +global $theme; +global $current_user; + +$report_std_filter = new vtigerCRM_Smarty; +$report_std_filter->assign("MOD", $mod_strings); +$report_std_filter->assign("APP", $app_strings); +$report_std_filter->assign("IMAGE_PATH",$image_path); +$report_std_filter->assign("DATEFORMAT",$current_user->date_format); +$report_std_filter->assign("JS_DATEFORMAT",parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +include("modules/Reports/StandardFilter.php"); +include("modules/Reports/AdvancedFilter.php"); + +$report_std_filter->display('ReportFilters.tpl'); +?> diff --git a/oss/vtiger/trunk/modules/Reports/ReportGrouping.php b/oss/vtiger/trunk/modules/Reports/ReportGrouping.php new file mode 100644 index 00000000..6e2e8619 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportGrouping.php @@ -0,0 +1,221 @@ +assign("MOD", $mod_strings); +$report_group->assign("APP", $app_strings); +$report_group->assign("IMAGE_PATH",$image_path); + +if(isset($_REQUEST["record"]) && $_REQUEST['record']!='') +{ + $reportid = vtlib_purify($_REQUEST["record"]); + $oReport = new Reports($reportid); + $list_array = $oReport->getSelctedSortingColumns($reportid); + + $oRep = new Reports(); + $secondarymodule = ''; + $secondarymodules =Array(); + + if(!empty($oRep->related_modules[$oReport->primodule])) { + foreach($oRep->related_modules[$oReport->primodule] as $key=>$value){ + if(isset($_REQUEST["secondarymodule_".$value]))$secondarymodules []= vtlib_purify($_REQUEST["secondarymodule_".$value]); + } + } + $secondarymodule = implode(":",$secondarymodules); + + if($secondarymodule!='') + $oReport->secmodule = $secondarymodule; + + $BLOCK1 = getPrimaryColumns_GroupingHTML($oReport->primodule,$list_array[0]); + $BLOCK1 .= getSecondaryColumns_GroupingHTML($oReport->secmodule,$list_array[0]); + $report_group->assign("BLOCK1",$BLOCK1); + + $BLOCK2 = getPrimaryColumns_GroupingHTML($oReport->primodule,$list_array[1]); + $BLOCK2 .= getSecondaryColumns_GroupingHTML($oReport->secmodule,$list_array[1]); + $report_group->assign("BLOCK2",$BLOCK2); + + $BLOCK3 = getPrimaryColumns_GroupingHTML($oReport->primodule,$list_array[2]); + $BLOCK3 .= getSecondaryColumns_GroupingHTML($oReport->secmodule,$list_array[2]); + $report_group->assign("BLOCK3",$BLOCK3); + + $sortorder = $oReport->ascdescorder; + +}else +{ + $primarymodule = vtlib_purify($_REQUEST["primarymodule"]); + $BLOCK1 = getPrimaryColumns_GroupingHTML($primarymodule); + $ogReport = new Reports(); + if(!empty($ogReport->related_modules[$primarymodule])) { + foreach($ogReport->related_modules[$primarymodule] as $key=>$value){ + $BLOCK1 .= getSecondaryColumns_GroupingHTML($_REQUEST["secondarymodule_".$value]); + } + } + $report_group->assign("BLOCK1",$BLOCK1); + $report_group->assign("BLOCK2",$BLOCK1); + $report_group->assign("BLOCK3",$BLOCK1); +} + + + /** Function to get the combo values for the Primary module Columns + * @ param $module(module name) :: Type String + * @ param $selected () :: Type String + * This function generates the combo values for the columns for the given module + * and return a HTML string + */ + +function getPrimaryColumns_GroupingHTML($module,$selected="") +{ + global $ogReport, $app_list_strings, $current_language; + $id_added=false; + $mod_strings = return_module_language($current_language,$module); + + $block_listed = array(); + $selected = decode_html($selected); + foreach($ogReport->module_list[$module] as $key=>$value) + { + if(isset($ogReport->pri_module_columnslist[$module][$value]) && !$block_listed[$value]) + { + $block_listed[$value] = true; + $shtml .= ""; + if($id_added==false){ + $is_selected =''; + if($selected == "vtiger_crmentity:crmid:".$module."_ID:crmid:I"){ + $is_selected = 'selected'; + } + $shtml .= ""; + $id_added=true; + } + foreach($ogReport->pri_module_columnslist[$module][$value] as $field=>$fieldlabel) + { + if(isset($mod_strings[$fieldlabel])) + { + if($selected == decode_html($field)) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + }else + { + if($selected == decode_html($field)) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + + } + } + } + } + return $shtml; +} + + /** Function to get the combo values for the Secondary module Columns + * @ param $module(module name) :: Type String + * @ param $selected () :: Type String + * This function generates the combo values for the columns for the given module + * and return a HTML string + */ +function getSecondaryColumns_GroupingHTML($module,$selected="") +{ + global $ogReport; + global $app_list_strings; + global $current_language; + + $selected = decode_html($selected); + if($module != "") + { + $secmodule = explode(":",$module); + for($i=0;$i < count($secmodule) ;$i++) + { + $mod_strings = return_module_language($current_language,$secmodule[$i]); + if(vtlib_isModuleActive($secmodule[$i])){ + $block_listed = array(); + foreach($ogReport->module_list[$secmodule[$i]] as $key=>$value) + { + if(isset($ogReport->sec_module_columnslist[$secmodule[$i]][$value]) && !$block_listed[$value]) { + $block_listed[$value] = true; + $shtml .= ""; + foreach($ogReport->sec_module_columnslist[$secmodule[$i]][$value] as $field=>$fieldlabel) + { + if(isset($mod_strings[$fieldlabel])) { + if($selected == decode_html($field)) { + $shtml .= ""; + } else { + $shtml .= ""; + } + } else { + if($selected == decode_html($field)) { + $shtml .= ""; + } else { + $shtml .= ""; + } + } + } + } + } + } + } + } + return $shtml; +} + +if($sortorder[0] != "Descending") +{ +$shtml = " + "; +}else +{ +$shtml = " + "; +} +$report_group->assign("ASCDESC1",$shtml); + +if($sortorder[1] != "Descending") +{ +$shtml = " + "; +}else +{ +$shtml = " + "; +} +$report_group->assign("ASCDESC2",$shtml); + +if($sortorder[2] != "Descending") +{ +$shtml = " + "; +}else +{ +$shtml = " + "; +} +$report_group->assign("ASCDESC3",$shtml); +$report_group->display("ReportGrouping.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Reports/ReportRun.php b/oss/vtiger/trunk/modules/Reports/ReportRun.php new file mode 100644 index 00000000..2341c7b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportRun.php @@ -0,0 +1,2767 @@ +reportid = $reportid; + $this->primarymodule = $oReport->primodule; + $this->secondarymodule = $oReport->secmodule; + $this->reporttype = $oReport->reporttype; + $this->reportname = $oReport->reportname; + } + + /** Function to get the columns for the reportid + * This function accepts the $reportid + * This function returns $columnslist Array($tablename:$columnname:$fieldlabel:$fieldname:$typeofdata=>$tablename.$columnname As Header value, + * $tablename1:$columnname1:$fieldlabel1:$fieldname1:$typeofdata1=>$tablename1.$columnname1 As Header value, + * | + * $tablenamen:$columnnamen:$fieldlabeln:$fieldnamen:$typeofdatan=>$tablenamen.$columnnamen As Header value + * ) + * + */ + function getQueryColumnsList($reportid) + { + // Have we initialized information already? + if($this->_columnslist !== false) { + return $this->_columnslist; + } + + global $adb; + global $modules; + global $log,$current_user,$current_language; + $ssql = "select vtiger_selectcolumn.* from vtiger_report inner join vtiger_selectquery on vtiger_selectquery.queryid = vtiger_report.queryid"; + $ssql .= " left join vtiger_selectcolumn on vtiger_selectcolumn.queryid = vtiger_selectquery.queryid"; + $ssql .= " where vtiger_report.reportid = ?"; + $ssql .= " order by vtiger_selectcolumn.columnindex"; + $result = $adb->pquery($ssql, array($reportid)); + $permitted_fields = Array(); + + while($columnslistrow = $adb->fetch_array($result)) + { + $fieldname =""; + $fieldcolname = $columnslistrow["columnname"]; + list($tablename,$colname,$module_field,$fieldname,$single) = split(":",$fieldcolname); + list($module,$field) = split("_",$module_field); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + if(sizeof($permitted_fields) == 0 && $is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + { + list($module,$field) = split("_",$module_field); + $permitted_fields = $this->getaccesfield($module); + } + $selectedfields = explode(":",$fieldcolname); + $querycolumns = $this->getEscapedColumns($selectedfields); + + $mod_strings = return_module_language($current_language,$module); + $fieldlabel = trim(str_replace($module," ",$selectedfields[2])); + $mod_arr=explode('_',$fieldlabel); + $mod = ($mod_arr[0] == '')?$module:$mod_arr[0]; + $fieldlabel = trim(str_replace("_"," ",$fieldlabel)); + //modified code to support i18n issue + $fld_arr = explode(" ",$fieldlabel); + $mod_lbl = getTranslatedString($fld_arr[0],$module); //module + array_shift($fld_arr); + $fld_lbl_str = implode(" ",$fld_arr); + $fld_lbl = getTranslatedString($fld_lbl_str,$module); //fieldlabel + $fieldlabel = $mod_lbl." ".$fld_lbl; + if(CheckFieldPermission($fieldname,$mod) != 'true' && $colname!="crmid") + { + continue; + } + else + { + $header_label = $selectedfields[2]; // Header label to be displayed in the reports table + // To check if the field in the report is a custom field + // and if yes, get the label of this custom field freshly from the vtiger_field as it would have been changed. + // Asha - Reference ticket : #4906 + + if($querycolumns == "") + { + if($selectedfields[4] == 'C') + { + $field_label_data = split("_",$selectedfields[2]); + $module= $field_label_data[0]; + if($module!=$this->primarymodule) + $columnslist[$fieldcolname] = "case when (".$selectedfields[0].".".$selectedfields[1]."='1')then 'yes' else case when (vtiger_crmentity$module.crmid !='') then 'no' else '-' end end as '$selectedfields[2]'"; + else + $columnslist[$fieldcolname] = "case when (".$selectedfields[0].".".$selectedfields[1]."='1')then 'yes' else case when (vtiger_crmentity.crmid !='') then 'no' else '-' end end as '$selectedfields[2]'"; + } + elseif($selectedfields[0] == 'vtiger_activity' && $selectedfields[1] == 'status') + { + $columnslist[$fieldcolname] = " case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end as Calendar_Status"; + } + elseif($selectedfields[0] == 'vtiger_activity' && $selectedfields[1] == 'date_start') + { + $columnslist[$fieldcolname] = "concat(vtiger_activity.date_start,' ',vtiger_activity.time_start) as Calendar_Start_Date_and_Time"; + } + elseif(stristr($selectedfields[0],"vtiger_users") && ($selectedfields[1] == 'user_name') && $module_field != 'Products_Handler' && $module_field!='Services_Owner') + { + $temp_module_from_tablename = str_replace("vtiger_users","",$selectedfields[0]); + if($module!=$this->primarymodule){ + $condition = "and vtiger_crmentity".$module.".crmid!=''"; + } else { + $condition = "and vtiger_crmentity.crmid!=''"; + } + if($temp_module_from_tablename == $module) + $columnslist[$fieldcolname] = " case when (".$selectedfields[0].".user_name not like '' $condition) then ".$selectedfields[0].".user_name else vtiger_groups".$module.".groupname end as ".$module."_Assigned_To"; + else//Some Fields can't assigned to groups so case avoided (fields like inventory manager) + $columnslist[$fieldcolname] = $selectedfields[0].".user_name as '".$header_label."'"; + + } + elseif(stristr($selectedfields[0],"vtiger_users") && ($selectedfields[1] == 'user_name') && $module_field == 'Products_Handler')//Products cannot be assiged to group only to handler so group is not included + { + $columnslist[$fieldcolname] = $selectedfields[0].".user_name as ".$module."_Handler"; + } + elseif($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + { + $columnslist[$fieldcolname] = "vtiger_crmentity.".$selectedfields[1]." AS '".$header_label."'"; + } + elseif($selectedfields[0] == 'vtiger_invoice' && $selectedfields[1] == 'salesorderid')//handled for salesorder fields in Invoice Module Reports + { + $columnslist[$fieldcolname] = 'vtiger_salesorderInvoice.subject AS "'.$selectedfields[2].'"'; + } + elseif($selectedfields[0] == 'vtiger_campaign' && $selectedfields[1] == 'product_id')//handled for product fields in Campaigns Module Reports + { + $columnslist[$fieldcolname] = 'vtiger_productsCampaigns.productname AS "'.$header_label.'"'; + } + elseif($selectedfields[0] == 'vtiger_products' && $selectedfields[1] == 'unit_price')//handled for product fields in Campaigns Module Reports + { + $columnslist[$fieldcolname] = 'concat('.$selectedfields[0].'.currency_id,"::",innerProduct.actual_unit_price) as "' . $header_label .'"'; + } + elseif(in_array($selectedfields[2], $this->append_currency_symbol_to_value)) { + $columnslist[$fieldcolname] = 'concat('.$selectedfields[0].'.currency_id,"::",'.$selectedfields[0].'.'.$selectedfields[1].') as "' . $header_label .'"'; + } + elseif($selectedfields[0] == 'vtiger_notes' && ($selectedfields[1] == 'filelocationtype' || $selectedfields[1] == 'filesize' || $selectedfields[1] == 'folderid' || $selectedfields[1]=='filestatus'))//handled for product fields in Campaigns Module Reports + { + if($selectedfields[1] == 'filelocationtype'){ + $columnslist[$fieldcolname] = "case ".$selectedfields[0].".".$selectedfields[1]." when 'I' then 'Internal' when 'E' then 'External' else '-' end as '$selectedfields[2]'"; + } else if($selectedfields[1] == 'folderid'){ + $columnslist[$fieldcolname] = "vtiger_attachmentsfolder.foldername as '$selectedfields[2]'"; + } elseif($selectedfields[1] == 'filestatus'){ + $columnslist[$fieldcolname] = "case ".$selectedfields[0].".".$selectedfields[1]." when '1' then 'yes' when '0' then 'no' else '-' end as '$selectedfields[2]'"; + } elseif($selectedfields[1] == 'filesize'){ + $columnslist[$fieldcolname] = "case ".$selectedfields[0].".".$selectedfields[1]." when '' then '-'else concat(".$selectedfields[0].".".$selectedfields[1]."/1024,' ','KB') end as '$selectedfields[2]'"; + } + }elseif(stristr($selectedfields[1],'cf_')==true && stripos($selectedfields[1],'cf_')==0) + { + $columnslist[$fieldcolname] = $selectedfields[0].".".$selectedfields[1].' AS "'.$adb->sql_escape_string(decode_html($header_label)).'"'; + } + else + { + $columnslist[$fieldcolname] = $selectedfields[0].".".$selectedfields[1].' AS "'.$header_label.'"'; + } + } + else + { + $columnslist[$fieldcolname] = $querycolumns; + } + } + } + // Save the information + $this->_columnslist = $columnslist; + + $log->info("ReportRun :: Successfully returned getQueryColumnsList".$reportid); + return $columnslist; + } + + /** Function to get field columns based on profile + * @ param $module : Type string + * returns permitted fields in array format + */ + function getaccesfield($module) + { + global $current_user; + global $adb; + $access_fields = Array(); + + $profileList = getCurrentUserProfileList(); + $query = "select vtiger_field.fieldname from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where"; + $params = array(); + if($module == "Calendar") + { + if (count($profileList) > 0) { + $query .= " vtiger_field.tabid in (9,16) and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .") group by vtiger_field.fieldid order by block,sequence"; + array_push($params, $profileList); + } else { + $query .= " vtiger_field.tabid in (9,16) and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 group by vtiger_field.fieldid order by block,sequence"; + } + } + else + { + array_push($params, $this->primarymodule, $this->secondarymodule); + if (count($profileList) > 0) { + $query .= " vtiger_field.tabid in (select tabid from vtiger_tab where vtiger_tab.name in (?,?)) and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .") group by vtiger_field.fieldid order by block,sequence"; + array_push($params, $profileList); + } else { + $query .= " vtiger_field.tabid in (select tabid from vtiger_tab where vtiger_tab.name in (?,?)) and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 group by vtiger_field.fieldid order by block,sequence"; + } + } + $result = $adb->pquery($query, $params); + + while($collistrow = $adb->fetch_array($result)) + { + $access_fields[] = $collistrow["fieldname"]; + } + //added to include ticketid for Reports module in select columnlist for all users + if($module == "HelpDesk") + $access_fields[] = "ticketid"; + return $access_fields; + } + + /** Function to get Escapedcolumns for the field in case of multiple parents + * @ param $selectedfields : Type Array + * returns the case query for the escaped columns + */ + function getEscapedColumns($selectedfields) + { + global $current_user,$adb; + $fieldname = $selectedfields[3]; + $tmp = split("_",$selectedfields[2]); + $module = $tmp[0]; + + if($fieldname == "parent_id" && ($module == "HelpDesk" || $module == "Calendar")) + { + if($module == "HelpDesk" && $selectedfields[0] == "vtiger_crmentityRelHelpDesk") + { + $querycolumn = "case vtiger_crmentityRelHelpDesk.setype when 'Accounts' then vtiger_accountRelHelpDesk.accountname when 'Contacts' then concat(vtiger_contactdetailsRelHelpDesk.lastname,' ',vtiger_contactdetailsRelHelpDesk.firstname) End"." '".$selectedfields[2]."', vtiger_crmentityRelHelpDesk.setype 'Entity_type'"; + return $querycolumn; + } + if($module == "Calendar") { + $querycolumn = "case vtiger_crmentityRelCalendar.setype when 'Accounts' then vtiger_accountRelCalendar.accountname when 'Leads' then concat(vtiger_leaddetailsRelCalendar.lastname,' ',vtiger_leaddetailsRelCalendar.firstname) when 'Potentials' then vtiger_potentialRelCalendar.potentialname when 'Quotes' then vtiger_quotesRelCalendar.subject when 'PurchaseOrder' then vtiger_purchaseorderRelCalendar.subject when 'Invoice' then vtiger_invoiceRelCalendar.subject when 'SalesOrder' then vtiger_salesorderRelCalendar.subject when 'HelpDesk' then vtiger_troubleticketsRelCalendar.title when 'Campaigns' then vtiger_campaignRelCalendar.campaignname End"." '".$selectedfields[2]."', vtiger_crmentityRelCalendar.setype 'Entity_type'"; + } + } elseif($fieldname == "contact_id" && strpos($selectedfields[2],"Contact_Name")) { + if(($this->primarymodule == 'PurchaseOrder' || $this->primarymodule == 'SalesOrder' || $this->primarymodule == 'Quotes' || $this->primarymodule == 'Invoice' || $this->primarymodule == 'Calendar') && $module==$this->primarymodule) { + if (getFieldVisibilityPermission("Contacts", $current_user->id, "firstname") == '0') + $querycolumn = " case when vtiger_crmentity.crmid!='' then concat(vtiger_contactdetails".$this->primarymodule.".lastname,' ',vtiger_contactdetails".$this->primarymodule.".firstname) else '-' end as ".$selectedfields[2]; + else + $querycolumn = " case when vtiger_crmentity.crmid!='' then vtiger_contactdetails".$this->primarymodule.".lastname else '-' end as ".$selectedfields[2]; + } + if(stristr($this->secondarymodule,$module) && ($module== 'Quotes' || $module== 'SalesOrder' || $module== 'PurchaseOrder' ||$module== 'Calendar' || $module == 'Invoice')) { + if (getFieldVisibilityPermission("Contacts", $current_user->id, "firstname") == '0') + $querycolumn = " case when vtiger_crmentity".$module.".crmid!='' then concat(vtiger_contactdetails".$module.".lastname,' ',vtiger_contactdetails".$module.".firstname) else '-' end as ".$selectedfields[2]; + else + $querycolumn = " case when vtiger_crmentity".$module.".crmid!='' then vtiger_contactdetails".$module.".lastname else '-' end as ".$selectedfields[2]; + } + } + else{ + if(stristr($selectedfields[0],"vtiger_crmentityRel")){ + $module = str_replace("vtiger_crmentityRel","",$selectedfields[0]); + $fields_query = $adb->pquery("SELECT vtiger_field.fieldname,vtiger_field.tablename,vtiger_field.fieldid from vtiger_field INNER JOIN vtiger_tab on vtiger_tab.name = ? WHERE vtiger_tab.tabid=vtiger_field.tabid and vtiger_field.fieldname=?",array($module,$selectedfields[3])); + + if($adb->num_rows($fields_query)>0){ + for($i=0;$i<$adb->num_rows($fields_query);$i++){ + $field_name = $selectedfields[3]; + $field_id = $adb->query_result($fields_query,$i,'fieldid'); + $tab_name = $selectedfields[1]; + $ui10_modules_query = $adb->pquery("SELECT relmodule FROM vtiger_fieldmodulerel WHERE fieldid=?",array($field_id)); + + if($adb->num_rows($ui10_modules_query)>0){ + $querycolumn = " case vtiger_crmentityRel$module.setype"; + for($j=0;$j<$adb->num_rows($ui10_modules_query);$j++){ + $rel_mod = $adb->query_result($ui10_modules_query,$j,'relmodule'); + $rel_obj = CRMEntity::getInstance($rel_mod); + vtlib_setup_modulevars($rel_mod, $rel_obj); + + $rel_tab_name = $rel_obj->table_name; + $link_field = $rel_tab_name."Rel".$module.".".$rel_obj->list_link_field; + + if($rel_mod=="Contacts" || $rel_mod=="Leads"){ + if(getFieldVisibilityPermission($rel_mod,$current_user->id,'firstname')==0){ + $link_field = "concat($link_field,' ',".$rel_tab_name."Rel$module.firstname)"; + } + } + $querycolumn.= " when '$rel_mod' then $link_field "; + } + $querycolumn .= "end as '".$selectedfields[2]."', vtiger_crmentityRel$module.setype as 'Entity_type'" ; + } + } + } + + } + } + return $querycolumn; + } + + /** Function to get selectedcolumns for the given reportid + * @ param $reportid : Type Integer + * returns the query of columnlist for the selected columns + */ + function getSelectedColumnsList($reportid) + { + + global $adb; + global $modules; + global $log; + + $ssql = "select vtiger_selectcolumn.* from vtiger_report inner join vtiger_selectquery on vtiger_selectquery.queryid = vtiger_report.queryid"; + $ssql .= " left join vtiger_selectcolumn on vtiger_selectcolumn.queryid = vtiger_selectquery.queryid where vtiger_report.reportid = ? "; + $ssql .= " order by vtiger_selectcolumn.columnindex"; + + $result = $adb->pquery($ssql, array($reportid)); + $noofrows = $adb->num_rows($result); + + if ($this->orderbylistsql != "") + { + $sSQL .= $this->orderbylistsql.", "; + } + + for($i=0; $i<$noofrows; $i++) + { + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $ordercolumnsequal = true; + if($fieldcolname != "") + { + for($j=0;$jorderbylistcolumns);$j++) + { + if($this->orderbylistcolumns[$j] == $fieldcolname) + { + $ordercolumnsequal = false; + break; + }else + { + $ordercolumnsequal = true; + } + } + if($ordercolumnsequal) + { + $selectedfields = explode(":",$fieldcolname); + if($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + $selectedfields[0] = "vtiger_crmentity"; + $sSQLList[] = $selectedfields[0].".".$selectedfields[1]." '".$selectedfields[2]."'"; + } + } + } + $sSQL .= implode(",",$sSQLList); + + $log->info("ReportRun :: Successfully returned getSelectedColumnsList".$reportid); + return $sSQL; + } + + /** Function to get advanced comparator in query form for the given Comparator and value + * @ param $comparator : Type String + * @ param $value : Type String + * returns the check query for the comparator + */ + function getAdvComparator($comparator,$value,$datatype="") + { + + global $log,$adb,$default_charset,$ogReport; + $value=html_entity_decode(trim($value),ENT_QUOTES,$default_charset); + $value_len = strlen($value); + $is_field = false; + if($value[0]=='$' && $value[$value_len-1]=='$'){ + $temp = str_replace('$','',$value); + $is_field = true; + } + if($datatype=='C'){ + $value = str_replace("yes","1",str_replace("no","0",$value)); + } + + if($is_field==true){ + $value = $this->getFilterComparedField($temp); + } + if($comparator == "e") + { + if(trim($value) == "NULL") + { + $rtvalue = " is NULL"; + }elseif(trim($value) != "") + { + $rtvalue = " = ".$adb->quote($value); + }elseif(trim($value) == "" && $datatype == "V") + { + $rtvalue = " = ".$adb->quote($value); + }else + { + $rtvalue = " is NULL"; + } + } + if($comparator == "n") + { + if(trim($value) == "NULL") + { + $rtvalue = " is NOT NULL"; + }elseif(trim($value) != "") + { + $rtvalue = " <> ".$adb->quote($value); + }elseif(trim($value) == "" && $datatype == "V") + { + $rtvalue = " <> ".$adb->quote($value); + }else + { + $rtvalue = " is NOT NULL"; + } + } + if($comparator == "s") + { + $rtvalue = " like '". formatForSqlLike($value, 2,$is_field) ."'"; + } + if($comparator == "ew") + { + $rtvalue = " like '". formatForSqlLike($value, 1,$is_field) ."'"; + } + if($comparator == "c") + { + $rtvalue = " like '". formatForSqlLike($value,0,$is_field) ."'"; + } + if($comparator == "k") + { + $rtvalue = " not like '". formatForSqlLike($value,0,$is_field) ."'"; + } + if($comparator == "l") + { + $rtvalue = " < ".$adb->quote($value); + } + if($comparator == "g") + { + $rtvalue = " > ".$adb->quote($value); + } + if($comparator == "m") + { + $rtvalue = " <= ".$adb->quote($value); + } + if($comparator == "h") + { + $rtvalue = " >= ".$adb->quote($value); + } + if($is_field==true){ + $rtvalue = str_replace("'","",$rtvalue); + $rtvalue = str_replace("\\","",$rtvalue); + } + $log->info("ReportRun :: Successfully returned getAdvComparator"); + return $rtvalue; + } + + /** Function to get field that is to be compared in query form for the given Comparator and field + * @ param $field : field + * returns the value for the comparator + */ + function getFilterComparedField($field){ + global $adb,$ogReport; + $field = split('#',$field); + $module = $field[0]; + $fieldname = trim($field[1]); + $tabid = getTabId($module); + $field_query = $adb->pquery("SELECT tablename,columnname,typeofdata,fieldname,uitype FROM vtiger_field WHERE tabid = ? AND fieldname= ?",array($tabid,$fieldname)); + $fieldtablename = $adb->query_result($field_query,0,'tablename'); + $fieldcolname = $adb->query_result($field_query,0,'columnname'); + $typeofdata = $adb->query_result($field_query,0,'typeofdata'); + $fieldtypeofdata=ChangeTypeOfData_Filter($fieldtablename,$fieldcolname,$typeofdata[0]); + $uitype = $adb->query_result($field_query,0,'uitype'); + /*if($tr[0]==$ogReport->primodule) + $value = $adb->query_result($field_query,0,'tablename').".".$adb->query_result($field_query,0,'columnname'); + else + $value = $adb->query_result($field_query,0,'tablename').$tr[0].".".$adb->query_result($field_query,0,'columnname'); + */ + if($uitype == 68 || $uitype == 59) + { + $fieldtypeofdata = 'V'; + } + if($fieldtablename == "vtiger_crmentity") + { + $fieldtablename = $fieldtablename.$module; + } + if($fieldname == "assigned_user_id") + { + $fieldtablename = "vtiger_users".$module; + $fieldcolname = "user_name"; + } + if($fieldname == "account_id") + { + $fieldtablename = "vtiger_account".$module; + $fieldcolname = "accountname"; + } + if($fieldname == "contact_id") + { + $fieldtablename = "vtiger_contactdetails".$module; + $fieldcolname = "lastname"; + } + if($fieldname == "parent_id") + { + $fieldtablename = "vtiger_crmentityRel".$module; + $fieldcolname = "setype"; + } + if($fieldname == "vendor_id") + { + $fieldtablename = "vtiger_vendorRel".$module; + $fieldcolname = "vendorname"; + } + if($fieldname == "potential_id") + { + $fieldtablename = "vtiger_potentialRel".$module; + $fieldcolname = "potentialname"; + } + if($fieldname == "assigned_user_id1") + { + $fieldtablename = "vtiger_usersRel1"; + $fieldcolname = "user_name"; + } + if($fieldname == 'quote_id') + { + $fieldtablename = "vtiger_quotes".$module; + $fieldcolname = "subject"; + } + if($fieldname == 'product_id' && $fieldtablename == 'vtiger_troubletickets') + { + $fieldtablename = "vtiger_productsRel"; + $fieldcolname = "productname"; + } + if($fieldname == 'product_id' && $fieldtablename == 'vtiger_campaign') + { + $fieldtablename = "vtiger_productsCampaigns"; + $fieldcolname = "productname"; + } + if($fieldname == 'product_id' && $fieldtablename == 'vtiger_products') + { + $fieldtablename = "vtiger_productsProducts"; + $fieldcolname = "productname"; + } + if($fieldname == 'campaignid' && $module=='Potentials') + { + $fieldtablename = "vtiger_campaign".$module; + $fieldcolname = "campaignname"; + } + $value = $fieldtablename.".".$fieldcolname; + return $value; + } + /** Function to get the advanced filter columns for the reportid + * This function accepts the $reportid + * This function returns $columnslist Array($columnname => $tablename:$columnname:$fieldlabel:$fieldname:$typeofdata=>$tablename.$columnname filtercriteria, + * $tablename1:$columnname1:$fieldlabel1:$fieldname1:$typeofdata1=>$tablename1.$columnname1 filtercriteria, + * | + * $tablenamen:$columnnamen:$fieldlabeln:$fieldnamen:$typeofdatan=>$tablenamen.$columnnamen filtercriteria + * ) + * + */ + + + function getAdvFilterList($reportid) + { + // Have we initialized information already? + if($this->_advfilterlist !== false) { + return $this->_advfilterlist; + } + + global $adb; + global $modules; + global $log; + + $advfiltersql = "select vtiger_relcriteria.* from vtiger_report"; + $advfiltersql .= " inner join vtiger_selectquery on vtiger_selectquery.queryid = vtiger_report.queryid"; + $advfiltersql .= " left join vtiger_relcriteria on vtiger_relcriteria.queryid = vtiger_selectquery.queryid"; + $advfiltersql .= " where vtiger_report.reportid =?"; + $advfiltersql .= " order by vtiger_relcriteria.columnindex"; + + $result = $adb->pquery($advfiltersql, array($reportid)); + while($advfilterrow = $adb->fetch_array($result)) + { + $fieldcolname = $advfilterrow["columnname"]; + $comparator = $advfilterrow["comparator"]; + $value = $advfilterrow["value"]; + if($fieldcolname != "" && $comparator != "") + { + $selectedfields = explode(":",$fieldcolname); + //Added to handle yes or no for checkbox field in reports advance filters. -shahul + if($selectedfields[4] == 'C') + { + if(strcasecmp(trim($value),"yes")==0) + $value="1"; + if(strcasecmp(trim($value),"no")==0) + $value="0"; + } + $valuearray = explode(",",trim($value)); + $datatype = (isset($selectedfields[4])) ? $selectedfields[4] : ""; + if(isset($valuearray) && count($valuearray) > 1) + { + $advorsql = ""; + for($n=0;$ngetAdvComparator($comparator,trim($valuearray[$n]),$datatype); + } + elseif($selectedfields[0] == 'vtiger_crmentityRelCalendar' && $selectedfields[1]=='setype') + { + $advorsql[] = "(case vtiger_crmentityRelHelpDesk.setype when 'Accounts' then vtiger_accountRelHelpDesk.accountname else concat(vtiger_contactdetailsRelHelpDesk.lastname,' ',vtiger_contactdetailsRelHelpDesk.firstname) end) ". $this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + } + elseif(($selectedfields[0] == "vtiger_users".$this->primarymodule || $selectedfields[0] == "vtiger_users".$this->secondarymodule) && $selectedfields[1] == 'user_name') + { + $module_from_tablename = str_replace("vtiger_users","",$selectedfields[0]); + if($this->primarymodule == 'Products') + { + $advorsql[] = ($selectedfields[0].".user_name ".$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype)); + }else + { + $advorsql[] = " ".$selectedfields[0].".user_name".$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype)." or vtiger_groups".$module_from_tablename.".groupname ".$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + } + } + elseif($selectedfields[1] == 'status')//when you use comma seperated values. + { + if($selectedfields[2] == 'Calendar_Status') + $advorsql[] = "(case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end)".$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + elseif($selectedfields[2] == 'HelpDesk_Status') + $advorsql[] = "vtiger_troubletickets.status".$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + } + elseif($selectedfields[1] == 'description')//when you use comma seperated values. + { + if($selectedfields[0]=='vtiger_crmentity'.$this->primarymodule) + $advorsql[] = "vtiger_crmentity.description".$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + else + $advorsql[] = $selectedfields[0].".".$selectedfields[1].$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + }else + { + $advorsql[] = $selectedfields[0].".".$selectedfields[1].$this->getAdvComparator($comparator,trim($valuearray[$n]),$datatype); + } + } + //If negative logic filter ('not equal to', 'does not contain') is used, 'and' condition should be applied instead of 'or' + if($comparator == 'n' || $comparator == 'k') + $advorsqls = implode(" and ",$advorsql); + else + $advorsqls = implode(" or ",$advorsql); + $fieldvalue = " (".$advorsqls.") "; + } + + elseif(($selectedfields[0] == "vtiger_users".$this->primarymodule || $selectedfields[0] == "vtiger_users".$this->secondarymodule) && $selectedfields[1] == 'user_name') + { + $module_from_tablename = str_replace("vtiger_users","",$selectedfields[0]); + if($this->primarymodule == 'Products') + { + $fieldvalue = ($selectedfields[0].".user_name ".$this->getAdvComparator($comparator,trim($value),$datatype)); + }else + { + $fieldvalue = " case when (".$selectedfields[0].".user_name not like '') then ".$selectedfields[0].".user_name else vtiger_groups".$module_from_tablename.".groupname end ".$this->getAdvComparator($comparator,trim($value),$datatype); + } + } + elseif($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + { + $fieldvalue = "vtiger_crmentity.".$selectedfields[1]." ".$this->getAdvComparator($comparator,trim($value),$datatype); + } + elseif($selectedfields[0] == 'vtiger_crmentityRelHelpDesk' && $selectedfields[1]=='setype') + { + $fieldvalue = "(vtiger_accountRelHelpDesk.accountname ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_contactdetailsRelHelpDesk.lastname ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_contactdetailsRelHelpDesk.firstname ".$this->getAdvComparator($comparator,trim($value),$datatype).")"; + + } + elseif($selectedfields[0] == 'vtiger_crmentityRelCalendar' && $selectedfields[1]=='setype') + { + $fieldvalue = "(vtiger_accountRelCalendar.accountname ".$this->getAdvComparator($comparator,trim($value),$datatype)." or concat(vtiger_leaddetailsRelCalendar.lastname,' ',vtiger_leaddetailsRelCalendar.firstname) ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_potentialRelCalendar.potentialname ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_invoiceRelCalendar.subject ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_quotesRelCalendar.subject ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_purchaseorderRelCalendar.subject ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_salesorderRelCalendar.subject ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_troubleticketsRelCalendar.title ".$this->getAdvComparator($comparator,trim($value),$datatype)." or vtiger_campaignRelCalendar.campaignname ".$this->getAdvComparator($comparator,trim($value),$datatype).")"; + } + // fix for the ticket#4016 -- when you use only one value in its field. + elseif($selectedfields[0] == "vtiger_activity" && $selectedfields[1] == 'status') + { + $fieldvalue = "(case when (vtiger_activity.status not like '') then vtiger_activity.status else vtiger_activity.eventstatus end)".$this->getAdvComparator($comparator,trim($value),$datatype); + } + //end fix + elseif($selectedfields[3] == "contact_id" && strpos($selectedfields[2],"Contact_Name")) + { + if($this->primarymodule == 'PurchaseOrder' || $this->primarymodule == 'SalesOrder' || $this->primarymodule == 'Quotes' || $this->primarymodule == 'Invoice' || $this->primarymodule == 'Calendar') + $fieldvalue = "concat(vtiger_contactdetails". $this->primarymodule .".lastname,' ',vtiger_contactdetails". $this->primarymodule .".firstname)".$this->getAdvComparator($comparator,trim($value),$datatype); + if($this->secondarymodule == 'Quotes' || $this->secondarymodule == 'Invoice') + $fieldvalue = "concat(vtiger_contactdetails". $this->secondarymodule .".lastname,' ',vtiger_contactdetails". $this->secondarymodule .".firstname)".$this->getAdvComparator($comparator,trim($value),$datatype); + } elseif($comparator == 'e' && (trim($value) == "NULL" || trim($value) == '')) { + $fieldvalue = "(".$selectedfields[0].".".$selectedfields[1]." IS NULL OR ".$selectedfields[0].".".$selectedfields[1]." = '')"; + } else { + $fieldvalue = $selectedfields[0].".".$selectedfields[1].$this->getAdvComparator($comparator,trim($value),$datatype); + } + if(isset($advfilterlist[$fieldcolname])) + $advfilterlist[$fieldcolname] = $advfilterlist[$fieldcolname].' and '.$fieldvalue; + else $advfilterlist[$fieldcolname] = $fieldvalue; + } + + } + // Save the information + $this->_advfilterlist = $advfilterlist; + + $log->info("ReportRun :: Successfully returned getAdvFilterList".$reportid); + return $advfilterlist; + } + + /** Function to get the Standard filter columns for the reportid + * This function accepts the $reportid datatype Integer + * This function returns $stdfilterlist Array($columnname => $tablename:$columnname:$fieldlabel:$fieldname:$typeofdata=>$tablename.$columnname filtercriteria, + * $tablename1:$columnname1:$fieldlabel1:$fieldname1:$typeofdata1=>$tablename1.$columnname1 filtercriteria, + * ) + * + */ + function getStdFilterList($reportid) + { + // Have we initialized information already? + if($this->_stdfilterlist !== false) { + return $this->_stdfilterlist; + } + + global $adb; + global $modules; + global $log; + + $stdfiltersql = "select vtiger_reportdatefilter.* from vtiger_report"; + $stdfiltersql .= " inner join vtiger_reportdatefilter on vtiger_report.reportid = vtiger_reportdatefilter.datefilterid"; + $stdfiltersql .= " where vtiger_report.reportid = ?"; + + $result = $adb->pquery($stdfiltersql, array($reportid)); + $stdfilterrow = $adb->fetch_array($result); + if(isset($stdfilterrow)) + { + $fieldcolname = $stdfilterrow["datecolumnname"]; + $datefilter = $stdfilterrow["datefilter"]; + $startdate = $stdfilterrow["startdate"]; + $enddate = $stdfilterrow["enddate"]; + + if($fieldcolname != "none") + { + $selectedfields = explode(":",$fieldcolname); + if($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + $selectedfields[0] = "vtiger_crmentity"; + if($datefilter == "custom") + { + if($startdate != "0000-00-00" && $enddate != "0000-00-00" && $selectedfields[0] != "" && $selectedfields[1] != "") + { + $stdfilterlist[$fieldcolname] = $selectedfields[0].".".$selectedfields[1]." between '".$startdate." 00:00:00' and '".$enddate." 23:59:59'"; + } + }else + { + $startenddate = $this->getStandarFiltersStartAndEndDate($datefilter); + if($startenddate[0] != "" && $startenddate[1] != "" && $selectedfields[0] != "" && $selectedfields[1] != "") + { + $stdfilterlist[$fieldcolname] = $selectedfields[0].".".$selectedfields[1]." between '".$startenddate[0]." 00:00:00' and '".$startenddate[1]." 23:59:59'"; + } + } + + } + } + // Save the information + $this->_stdfilterlist = $stdfilterlist; + + $log->info("ReportRun :: Successfully returned getStdFilterList".$reportid); + return $stdfilterlist; + } + + /** Function to get the RunTime filter columns for the given $filtercolumn,$filter,$startdate,$enddate + * @ param $filtercolumn : Type String + * @ param $filter : Type String + * @ param $startdate: Type String + * @ param $enddate : Type String + * This function returns $stdfilterlist Array($columnname => $tablename:$columnname:$fieldlabel=>$tablename.$columnname 'between' $startdate 'and' $enddate) + * + */ + function RunTimeFilter($filtercolumn,$filter,$startdate,$enddate) + { + if($filtercolumn != "none") + { + $selectedfields = explode(":",$filtercolumn); + if($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + $selectedfields[0] = "vtiger_crmentity"; + if($filter == "custom") + { + if($startdate != "" && $enddate != "" && $selectedfields[0] != "" && $selectedfields[1] != "") + { + $stdfilterlist[$filtercolumn] = $selectedfields[0].".".$selectedfields[1]." between '".$startdate." 00:00:00' and '".$enddate." 23:59:00'"; + } + }else + { + if($startdate != "" && $enddate != "") + { + $startenddate = $this->getStandarFiltersStartAndEndDate($filter); + if($startenddate[0] != "" && $startenddate[1] != "" && $selectedfields[0] != "" && $selectedfields[1] != "") + { + $stdfilterlist[$filtercolumn] = $selectedfields[0].".".$selectedfields[1]." between '".$startenddate[0]." 00:00:00' and '".$startenddate[1]." 23:59:00'"; + } + } + } + + } + return $stdfilterlist; + + } + + /** Function to get standardfilter for the given reportid + * @ param $reportid : Type Integer + * returns the query of columnlist for the selected columns + */ + + function getStandardCriterialSql($reportid) + { + global $adb; + global $modules; + global $log; + + $sreportstdfiltersql = "select vtiger_reportdatefilter.* from vtiger_report"; + $sreportstdfiltersql .= " inner join vtiger_reportdatefilter on vtiger_report.reportid = vtiger_reportdatefilter.datefilterid"; + $sreportstdfiltersql .= " where vtiger_report.reportid = ?"; + + $result = $adb->pquery($sreportstdfiltersql, array($reportid)); + $noofrows = $adb->num_rows($result); + + for($i=0; $i<$noofrows; $i++) + { + $fieldcolname = $adb->query_result($result,$i,"datecolumnname"); + $datefilter = $adb->query_result($result,$i,"datefilter"); + $startdate = $adb->query_result($result,$i,"startdate"); + $enddate = $adb->query_result($result,$i,"enddate"); + + if($fieldcolname != "none") + { + $selectedfields = explode(":",$fieldcolname); + if($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + $selectedfields[0] = "vtiger_crmentity"; + if($datefilter == "custom") + { + if($startdate != "0000-00-00" && $enddate != "0000-00-00" && $selectedfields[0] != "" && $selectedfields[1] != "") + { + $sSQL .= $selectedfields[0].".".$selectedfields[1]." between '".$startdate."' and '".$enddate."'"; + } + }else + { + $startenddate = $this->getStandarFiltersStartAndEndDate($datefilter); + if($startenddate[0] != "" && $startenddate[1] != "" && $selectedfields[0] != "" && $selectedfields[1] != "") + { + $sSQL .= $selectedfields[0].".".$selectedfields[1]." between '".$startenddate[0]."' and '".$startenddate[1]."'"; + } + } + } + } + $log->info("ReportRun :: Successfully returned getStandardCriterialSql".$reportid); + return $sSQL; + } + + /** Function to get standardfilter startdate and enddate for the given type + * @ param $type : Type String + * returns the $datevalue Array in the given format + * $datevalue = Array(0=>$startdate,1=>$enddate) + */ + + + function getStandarFiltersStartAndEndDate($type) + { + $today = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d"), date("Y"))); + $tomorrow = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); + $yesterday = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-1, date("Y"))); + + $currentmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y"))); + $currentmonth1 = date("Y-m-t"); + $lastmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")-1, "01", date("Y"))); + $lastmonth1 = date("Y-m-t", strtotime("-1 Month")); + $nextmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")+1, "01", date("Y"))); + $nextmonth1 = date("Y-m-t", strtotime("+1 Month")); + + $lastweek0 = date("Y-m-d",strtotime("-2 week Sunday")); + $lastweek1 = date("Y-m-d",strtotime("-1 week Saturday")); + + $thisweek0 = date("Y-m-d",strtotime("-1 week Sunday")); + $thisweek1 = date("Y-m-d",strtotime("this Saturday")); + + $nextweek0 = date("Y-m-d",strtotime("this Sunday")); + $nextweek1 = date("Y-m-d",strtotime("+1 week Saturday")); + + $next7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+6, date("Y"))); + $next30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+29, date("Y"))); + $next60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+59, date("Y"))); + $next90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+89, date("Y"))); + $next120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+119, date("Y"))); + + $last7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-6, date("Y"))); + $last30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-29, date("Y"))); + $last60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-59, date("Y"))); + $last90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-89, date("Y"))); + $last120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-119, date("Y"))); + + $currentFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y"))); + $currentFY1 = date("Y-m-t",mktime(0, 0, 0, "12", date("d"), date("Y"))); + $lastFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")-1)); + $lastFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")-1)); + $nextFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")+1)); + $nextFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")+1)); + + if(date("m") <= 3) + { + $cFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y")-1)); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y")-1)); + }else if(date("m") > 3 and date("m") <= 6) + { + $pFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + + }else if(date("m") > 6 and date("m") <= 9) + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + } + else if(date("m") > 9 and date("m") <= 12) + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y")+1)); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y")+1)); + $pFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + + } + + if($type == "today" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $today; + } + elseif($type == "yesterday" ) + { + + $datevalue[0] = $yesterday; + $datevalue[1] = $yesterday; + } + elseif($type == "tomorrow" ) + { + + $datevalue[0] = $tomorrow; + $datevalue[1] = $tomorrow; + } + elseif($type == "thisweek" ) + { + + $datevalue[0] = $thisweek0; + $datevalue[1] = $thisweek1; + } + elseif($type == "lastweek" ) + { + + $datevalue[0] = $lastweek0; + $datevalue[1] = $lastweek1; + } + elseif($type == "nextweek" ) + { + + $datevalue[0] = $nextweek0; + $datevalue[1] = $nextweek1; + } + elseif($type == "thismonth" ) + { + + $datevalue[0] =$currentmonth0; + $datevalue[1] = $currentmonth1; + } + + elseif($type == "lastmonth" ) + { + + $datevalue[0] = $lastmonth0; + $datevalue[1] = $lastmonth1; + } + elseif($type == "nextmonth" ) + { + + $datevalue[0] = $nextmonth0; + $datevalue[1] = $nextmonth1; + } + elseif($type == "next7days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next7days; + } + elseif($type == "next30days" ) + { + + $datevalue[0] =$today; + $datevalue[1] =$next30days; + } + elseif($type == "next60days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next60days; + } + elseif($type == "next90days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next90days; + } + elseif($type == "next120days" ) + { + + $datevalue[0] = $today; + $datevalue[1] = $next120days; + } + elseif($type == "last7days" ) + { + + $datevalue[0] = $last7days; + $datevalue[1] = $today; + } + elseif($type == "last30days" ) + { + + $datevalue[0] = $last30days; + $datevalue[1] = $today; + } + elseif($type == "last60days" ) + { + + $datevalue[0] = $last60days; + $datevalue[1] = $today; + } + else if($type == "last90days" ) + { + + $datevalue[0] = $last90days; + $datevalue[1] = $today; + } + elseif($type == "last120days" ) + { + + $datevalue[0] = $last120days; + $datevalue[1] = $today; + } + elseif($type == "thisfy" ) + { + + $datevalue[0] = $currentFY0; + $datevalue[1] = $currentFY1; + } + elseif($type == "prevfy" ) + { + + $datevalue[0] = $lastFY0; + $datevalue[1] = $lastFY1; + } + elseif($type == "nextfy" ) + { + + $datevalue[0] = $nextFY0; + $datevalue[1] = $nextFY1; + } + elseif($type == "nextfq" ) + { + + $datevalue[0] = $nFq; + $datevalue[1] = $nFq1; + } + elseif($type == "prevfq" ) + { + + $datevalue[0] = $pFq; + $datevalue[1] = $pFq1; + } + elseif($type == "thisfq" ) + { + $datevalue[0] = $cFq; + $datevalue[1] = $cFq1; + } + else + { + $datevalue[0] = ""; + $datevalue[1] = ""; + } + return $datevalue; + } + + /** Function to get getGroupingList for the given reportid + * @ param $reportid : Type Integer + * returns the $grouplist Array in the following format + * $grouplist = Array($tablename:$columnname:$fieldlabel:fieldname:typeofdata=>$tablename:$columnname $sorder, + * $tablename1:$columnname1:$fieldlabel1:fieldname1:typeofdata1=>$tablename1:$columnname1 $sorder, + * $tablename2:$columnname2:$fieldlabel2:fieldname2:typeofdata2=>$tablename2:$columnname2 $sorder) + * This function also sets the return value in the class variable $this->groupbylist + */ + + + function getGroupingList($reportid) + { + global $adb; + global $modules; + global $log; + + // Have we initialized information already? + if($this->_groupinglist !== false) { + return $this->_groupinglist; + } + + $sreportsortsql = "select vtiger_reportsortcol.* from vtiger_report"; + $sreportsortsql .= " inner join vtiger_reportsortcol on vtiger_report.reportid = vtiger_reportsortcol.reportid"; + $sreportsortsql .= " where vtiger_report.reportid =? AND vtiger_reportsortcol.columnname IN (SELECT columnname from vtiger_selectcolumn WHERE queryid=?) order by vtiger_reportsortcol.sortcolid"; + + $result = $adb->pquery($sreportsortsql, array($reportid,$reportid)); + + while($reportsortrow = $adb->fetch_array($result)) + { + $fieldcolname = $reportsortrow["columnname"]; + list($tablename,$colname,$module_field,$fieldname,$single) = split(":",$fieldcolname); + $sortorder = $reportsortrow["sortorder"]; + + if($sortorder == "Ascending") + { + $sortorder = "ASC"; + + }elseif($sortorder == "Descending") + { + $sortorder = "DESC"; + } + + if($fieldcolname != "none") + { + $selectedfields = explode(":",$fieldcolname); + if($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + $selectedfields[0] = "vtiger_crmentity"; + if(stripos($selectedfields[1],'cf_')==0 && stristr($selectedfields[1],'cf_')==true){ + $sqlvalue = "'".$adb->sql_escape_string(decode_html($selectedfields[2]))."' ".$sortorder; + } else { + $sqlvalue = "'".$selectedfields[2]."' ".$sortorder; + } + $grouplist[$fieldcolname] = $sqlvalue; + $temp = split("_",$selectedfields[2],2); + $module = $temp[0]; + if(CheckFieldPermission($fieldname,$module) == 'true') + { + $this->groupbylist[$fieldcolname] = $selectedfields[0].".".$selectedfields[1]." ".$selectedfields[2]; + } + } + } + // Save the information + $this->_groupinglist = $grouplist; + + $log->info("ReportRun :: Successfully returned getGroupingList".$reportid); + return $grouplist; + } + + /** function to get the selectedorderbylist for the given reportid + * @ param $reportid : type integer + * this returns the columns query for the sortorder columns + * this function also sets the return value in the class variable $this->orderbylistsql + */ + + + function getSelectedOrderbyList($reportid) + { + + global $adb; + global $modules; + global $log; + + $sreportsortsql = "select vtiger_reportsortcol.* from vtiger_report"; + $sreportsortsql .= " inner join vtiger_reportsortcol on vtiger_report.reportid = vtiger_reportsortcol.reportid"; + $sreportsortsql .= " where vtiger_report.reportid =? order by vtiger_reportsortcol.sortcolid"; + + $result = $adb->pquery($sreportsortsql, array($reportid)); + $noofrows = $adb->num_rows($result); + + for($i=0; $i<$noofrows; $i++) + { + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $sortorder = $adb->query_result($result,$i,"sortorder"); + + if($sortorder == "Ascending") + { + $sortorder = "ASC"; + } + elseif($sortorder == "Descending") + { + $sortorder = "DESC"; + } + + if($fieldcolname != "none") + { + $this->orderbylistcolumns[] = $fieldcolname; + $n = $n + 1; + $selectedfields = explode(":",$fieldcolname); + if($n > 1) + { + $sSQL .= ", "; + $this->orderbylistsql .= ", "; + } + if($selectedfields[0] == "vtiger_crmentity".$this->primarymodule) + $selectedfields[0] = "vtiger_crmentity"; + $sSQL .= $selectedfields[0].".".$selectedfields[1]." ".$sortorder; + $this->orderbylistsql .= $selectedfields[0].".".$selectedfields[1]." ".$selectedfields[2]; + } + } + $log->info("ReportRun :: Successfully returned getSelectedOrderbyList".$reportid); + return $sSQL; + } + + /** function to get secondary Module for the given Primary module and secondary module + * @ param $module : type String + * @ param $secmodule : type String + * this returns join query for the given secondary module + */ + + function getRelatedModulesQuery($module,$secmodule) + { + global $log,$current_user; + $query = ''; + if($secmodule!=''){ + $secondarymodule = explode(":",$secmodule); + foreach($secondarymodule as $key=>$value) { + $foc = CRMEntity::getInstance($value); + $query .= $foc->generateReportsSecQuery($module,$value); + } + } + $log->info("ReportRun :: Successfully returned getRelatedModulesQuery".$secmodule); + return $query; + } + /** function to get report query for the given module + * @ param $module : type String + * this returns join query for the given module + */ + + function getReportsQuery($module) + { + global $log, $current_user; + $secondary_module ="'"; + $secondary_module .= str_replace(":","','",$this->secondarymodule); + $secondary_module .="'"; + + if($module == "Leads") + { + $query = "from vtiger_leaddetails + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_leaddetails.leadid + inner join vtiger_leadsubdetails on vtiger_leadsubdetails.leadsubscriptionid=vtiger_leaddetails.leadid + inner join vtiger_leadaddress on vtiger_leadaddress.leadaddressid=vtiger_leadsubdetails.leadsubscriptionid + inner join vtiger_leadscf on vtiger_leaddetails.leadid = vtiger_leadscf.leadid + left join vtiger_groups as vtiger_groupsLeads on vtiger_groupsLeads.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersLeads on vtiger_usersLeads.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0 and vtiger_leaddetails.converted=0"; + } + else if($module == "Accounts") + { + $query = "from vtiger_account + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_account.accountid + inner join vtiger_accountbillads on vtiger_account.accountid=vtiger_accountbillads.accountaddressid + inner join vtiger_accountshipads on vtiger_account.accountid=vtiger_accountshipads.accountaddressid + inner join vtiger_accountscf on vtiger_account.accountid = vtiger_accountscf.accountid + left join vtiger_groups as vtiger_groupsAccounts on vtiger_groupsAccounts.groupid = vtiger_crmentity.smownerid + left join vtiger_account as vtiger_accountAccounts on vtiger_accountAccounts.accountid = vtiger_account.parentid + left join vtiger_users as vtiger_usersAccounts on vtiger_usersAccounts.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0 "; + } + + else if($module == "Contacts") + { + $query = "from vtiger_contactdetails + inner join vtiger_crmentity on vtiger_crmentity.crmid = vtiger_contactdetails.contactid + inner join vtiger_contactaddress on vtiger_contactdetails.contactid = vtiger_contactaddress.contactaddressid + inner join vtiger_customerdetails on vtiger_customerdetails.customerid = vtiger_contactdetails.contactid + inner join vtiger_contactsubdetails on vtiger_contactdetails.contactid = vtiger_contactsubdetails.contactsubscriptionid + inner join vtiger_contactscf on vtiger_contactdetails.contactid = vtiger_contactscf.contactid + left join vtiger_groups vtiger_groupsContacts on vtiger_groupsContacts.groupid = vtiger_crmentity.smownerid + left join vtiger_contactdetails as vtiger_contactdetailsContacts on vtiger_contactdetailsContacts.contactid = vtiger_contactdetails.reportsto + left join vtiger_account as vtiger_accountContacts on vtiger_accountContacts.accountid = vtiger_contactdetails.accountid + left join vtiger_users as vtiger_usersContacts on vtiger_usersContacts.id = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + } + + else if($module == "Potentials") + { + $query = "from vtiger_potential + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_potential.potentialid + inner join vtiger_potentialscf on vtiger_potentialscf.potentialid = vtiger_potential.potentialid + left join vtiger_account as vtiger_accountPotentials on vtiger_potential.related_to = vtiger_accountPotentials.accountid + left join vtiger_contactdetails as vtiger_contactdetailsPotentials on vtiger_potential.related_to = vtiger_contactdetailsPotentials.contactid + left join vtiger_campaign as vtiger_campaignPotentials on vtiger_potential.campaignid = vtiger_campaignPotentials.campaignid + left join vtiger_groups vtiger_groupsPotentials on vtiger_groupsPotentials.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersPotentials on vtiger_usersPotentials.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0 "; + } + + //For this Product - we can related Accounts, Contacts (Also Leads, Potentials) + else if($module == "Products") + { + $query = "from vtiger_products + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_products.productid + left join vtiger_productcf on vtiger_products.productid = vtiger_productcf.productid + left join vtiger_users as vtiger_usersProducts on vtiger_usersProducts.id = vtiger_products.handler + left join vtiger_vendor as vtiger_vendorRelProducts on vtiger_vendorRelProducts.vendorid = vtiger_products.vendor_id + LEFT JOIN ( + SELECT vtiger_products.productid, + (CASE WHEN (vtiger_products.currency_id = 1 ) THEN vtiger_products.unit_price + ELSE (vtiger_products.unit_price / vtiger_currency_info.conversion_rate) END + ) AS actual_unit_price + FROM vtiger_products + LEFT JOIN vtiger_currency_info ON vtiger_products.currency_id = vtiger_currency_info.id + LEFT JOIN vtiger_productcurrencyrel ON vtiger_products.productid = vtiger_productcurrencyrel.productid + AND vtiger_productcurrencyrel.currencyid = ". $current_user->currency_id . " + ) AS innerProduct ON innerProduct.productid = vtiger_products.productid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + } + + else if($module == "HelpDesk") + { + $query = "from vtiger_troubletickets + inner join vtiger_crmentity + on vtiger_crmentity.crmid=vtiger_troubletickets.ticketid + inner join vtiger_ticketcf on vtiger_ticketcf.ticketid = vtiger_troubletickets.ticketid + left join vtiger_crmentity as vtiger_crmentityRelHelpDesk on vtiger_crmentityRelHelpDesk.crmid = vtiger_troubletickets.parent_id + left join vtiger_account as vtiger_accountRelHelpDesk on vtiger_accountRelHelpDesk.accountid=vtiger_crmentityRelHelpDesk.crmid + left join vtiger_contactdetails as vtiger_contactdetailsRelHelpDesk on vtiger_contactdetailsRelHelpDesk.contactid= vtiger_crmentityRelHelpDesk.crmid + left join vtiger_products as vtiger_productsRel on vtiger_productsRel.productid = vtiger_troubletickets.product_id + left join vtiger_groups as vtiger_groupsHelpDesk on vtiger_groupsHelpDesk.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersHelpDesk on vtiger_crmentity.smownerid=vtiger_usersHelpDesk.id + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_crmentity.smownerid=vtiger_users.id + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0 "; + } + + else if($module == "Calendar") + { + $query = "from vtiger_activity + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid + left join vtiger_activitycf on vtiger_activitycf.activityid = vtiger_crmentity.crmid + left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid + left join vtiger_contactdetails as vtiger_contactdetailsCalendar on vtiger_contactdetailsCalendar.contactid= vtiger_cntactivityrel.contactid + left join vtiger_groups as vtiger_groupsCalendar on vtiger_groupsCalendar.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersCalendar on vtiger_usersCalendar.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + left join vtiger_seactivityrel on vtiger_seactivityrel.activityid = vtiger_activity.activityid + left join vtiger_activity_reminder on vtiger_activity_reminder.activity_id = vtiger_activity.activityid + left join vtiger_recurringevents on vtiger_recurringevents.activityid = vtiger_activity.activityid + left join vtiger_crmentity as vtiger_crmentityRelCalendar on vtiger_crmentityRelCalendar.crmid = vtiger_seactivityrel.crmid + left join vtiger_account as vtiger_accountRelCalendar on vtiger_accountRelCalendar.accountid=vtiger_crmentityRelCalendar.crmid + left join vtiger_leaddetails as vtiger_leaddetailsRelCalendar on vtiger_leaddetailsRelCalendar.leadid = vtiger_crmentityRelCalendar.crmid + left join vtiger_potential as vtiger_potentialRelCalendar on vtiger_potentialRelCalendar.potentialid = vtiger_crmentityRelCalendar.crmid + left join vtiger_quotes as vtiger_quotesRelCalendar on vtiger_quotesRelCalendar.quoteid = vtiger_crmentityRelCalendar.crmid + left join vtiger_purchaseorder as vtiger_purchaseorderRelCalendar on vtiger_purchaseorderRelCalendar.purchaseorderid = vtiger_crmentityRelCalendar.crmid + left join vtiger_invoice as vtiger_invoiceRelCalendar on vtiger_invoiceRelCalendar.invoiceid = vtiger_crmentityRelCalendar.crmid + left join vtiger_salesorder as vtiger_salesorderRelCalendar on vtiger_salesorderRelCalendar.salesorderid = vtiger_crmentityRelCalendar.crmid + left join vtiger_troubletickets as vtiger_troubleticketsRelCalendar on vtiger_troubleticketsRelCalendar.ticketid = vtiger_crmentityRelCalendar.crmid + left join vtiger_campaign as vtiger_campaignRelCalendar on vtiger_campaignRelCalendar.campaignid = vtiger_crmentityRelCalendar.crmid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + WHERE vtiger_crmentity.deleted=0 and (vtiger_activity.activitytype != 'Emails')"; + } + + else if($module == "Quotes") + { + $query = "from vtiger_quotes + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_quotes.quoteid + inner join vtiger_quotesbillads on vtiger_quotes.quoteid=vtiger_quotesbillads.quotebilladdressid + inner join vtiger_quotesshipads on vtiger_quotes.quoteid=vtiger_quotesshipads.quoteshipaddressid + left join vtiger_quotescf on vtiger_quotes.quoteid = vtiger_quotescf.quoteid + left join vtiger_groups as vtiger_groupsQuotes on vtiger_groupsQuotes.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersQuotes on vtiger_usersQuotes.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersRel1 on vtiger_usersRel1.id = vtiger_quotes.inventorymanager + left join vtiger_potential as vtiger_potentialRelQuotes on vtiger_potentialRelQuotes.potentialid = vtiger_quotes.potentialid + left join vtiger_contactdetails as vtiger_contactdetailsQuotes on vtiger_contactdetailsQuotes.contactid = vtiger_quotes.contactid + left join vtiger_account as vtiger_accountQuotes on vtiger_accountQuotes.accountid = vtiger_quotes.accountid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + } + + else if($module == "PurchaseOrder") + { + $query = "from vtiger_purchaseorder + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_purchaseorder.purchaseorderid + inner join vtiger_pobillads on vtiger_purchaseorder.purchaseorderid=vtiger_pobillads.pobilladdressid + inner join vtiger_poshipads on vtiger_purchaseorder.purchaseorderid=vtiger_poshipads.poshipaddressid + left join vtiger_purchaseordercf on vtiger_purchaseorder.purchaseorderid = vtiger_purchaseordercf.purchaseorderid + left join vtiger_groups as vtiger_groupsPurchaseOrder on vtiger_groupsPurchaseOrder.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersPurchaseOrder on vtiger_usersPurchaseOrder.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + left join vtiger_vendor as vtiger_vendorRelPurchaseOrder on vtiger_vendorRelPurchaseOrder.vendorid = vtiger_purchaseorder.vendorid + left join vtiger_contactdetails as vtiger_contactdetailsPurchaseOrder on vtiger_contactdetailsPurchaseOrder.contactid = vtiger_purchaseorder.contactid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + } + + else if($module == "Invoice") + { + $query = "from vtiger_invoice + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_invoice.invoiceid + inner join vtiger_invoicebillads on vtiger_invoice.invoiceid=vtiger_invoicebillads.invoicebilladdressid + inner join vtiger_invoiceshipads on vtiger_invoice.invoiceid=vtiger_invoiceshipads.invoiceshipaddressid + left join vtiger_salesorder as vtiger_salesorderInvoice on vtiger_salesorderInvoice.salesorderid=vtiger_invoice.salesorderid + left join vtiger_invoicecf on vtiger_invoice.invoiceid = vtiger_invoicecf.invoiceid + left join vtiger_groups as vtiger_groupsInvoice on vtiger_groupsInvoice.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersInvoice on vtiger_usersInvoice.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + left join vtiger_account as vtiger_accountInvoice on vtiger_accountInvoice.accountid = vtiger_invoice.accountid + left join vtiger_contactdetails as vtiger_contactdetailsInvoice on vtiger_contactdetailsInvoice.contactid = vtiger_invoice.contactid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + } + else if($module == "SalesOrder") + { + $query = "from vtiger_salesorder + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_salesorder.salesorderid + inner join vtiger_sobillads on vtiger_salesorder.salesorderid=vtiger_sobillads.sobilladdressid + inner join vtiger_soshipads on vtiger_salesorder.salesorderid=vtiger_soshipads.soshipaddressid + left join vtiger_salesordercf on vtiger_salesorder.salesorderid = vtiger_salesordercf.salesorderid + left join vtiger_contactdetails as vtiger_contactdetailsSalesOrder on vtiger_contactdetailsSalesOrder.contactid = vtiger_salesorder.contactid + left join vtiger_quotes as vtiger_quotesSalesOrder on vtiger_quotesSalesOrder.quoteid = vtiger_salesorder.quoteid + left join vtiger_account as vtiger_accountSalesOrder on vtiger_accountSalesOrder.accountid = vtiger_salesorder.accountid + left join vtiger_potential as vtiger_potentialRelSalesOrder on vtiger_potentialRelSalesOrder.potentialid = vtiger_salesorder.potentialid + left join vtiger_invoice_recurring_info on vtiger_invoice_recurring_info.salesorderid = vtiger_salesorder.salesorderid + left join vtiger_groups as vtiger_groupsSalesOrder on vtiger_groupsSalesOrder.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersSalesOrder on vtiger_usersSalesOrder.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + + + } + else if($module == "Campaigns") + { + $query = "from vtiger_campaign + inner join vtiger_campaignscf as vtiger_campaignscf on vtiger_campaignscf.campaignid=vtiger_campaign.campaignid + inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_campaign.campaignid + left join vtiger_products as vtiger_productsCampaigns on vtiger_productsCampaigns.productid = vtiger_campaign.product_id + left join vtiger_groups as vtiger_groupsCampaigns on vtiger_groupsCampaigns.groupid = vtiger_crmentity.smownerid + left join vtiger_users as vtiger_usersCampaigns on vtiger_usersCampaigns.id = vtiger_crmentity.smownerid + left join vtiger_groups on vtiger_groups.groupid = vtiger_crmentity.smownerid + left join vtiger_users on vtiger_users.id = vtiger_crmentity.smownerid + ".$this->getRelatedModulesQuery($module,$this->secondarymodule)." + where vtiger_crmentity.deleted=0"; + } + + else { + if($module!=''){ + $focus = CRMEntity::getInstance($module); + $query = $focus->generateReportsQuery($module) + .$this->getRelatedModulesQuery($module,$this->secondarymodule) + ." WHERE vtiger_crmentity.deleted=0"; + } + } + $log->info("ReportRun :: Successfully returned getReportsQuery".$module); + + return $query; + } + + + /** function to get query for the given reportid,filterlist,type + * @ param $reportid : Type integer + * @ param $filterlist : Type Array + * @ param $module : Type String + * this returns join query for the report + */ + + function sGetSQLforReport($reportid,$filterlist,$type='') + { + global $log; + + $columnlist = $this->getQueryColumnsList($reportid); + $groupslist = $this->getGroupingList($reportid); + $stdfilterlist = $this->getStdFilterList($reportid); + $columnstotallist = $this->getColumnsTotal($reportid); + $advfilterlist = $this->getAdvFilterList($reportid); + $this->totallist = $columnstotallist; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require('user_privileges/sharing_privileges_'.$current_user->id.'.php'); + $tab_id = getTabid($this->primarymodule); + //Fix for ticket #4915. + $selectlist = $columnlist; + //columns list + if(isset($selectlist)) + { + $selectedcolumns = implode(", ",$selectlist); + } + //groups list + if(isset($groupslist)) + { + $groupsquery = implode(", ",$groupslist); + } + + //standard list + if(isset($stdfilterlist)) + { + $stdfiltersql = implode(", ",$stdfilterlist); + } + if(isset($filterlist)) + { + $stdfiltersql = implode(", ",$filterlist); + } + //columns to total list + if(isset($columnstotallist)) + { + $columnstotalsql = implode(", ",$columnstotallist); + } + //advanced filterlist + if(isset($advfilterlist)) + { + $advfiltersql = implode(" and ",$advfilterlist); + } + if($stdfiltersql != "") + { + $wheresql = " and ".$stdfiltersql; + } + if($advfiltersql != "") + { + $wheresql .= " and ".$advfiltersql; + } + + $reportquery = $this->getReportsQuery($this->primarymodule); + + // If we don't have access to any columns, let us select one column and limit result to shown we have not results + // Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/4758 - Prasad + $allColumnsRestricted = false; + + if($type == 'COLUMNSTOTOTAL') + { + if($columnstotalsql != '') + { + $reportquery = "select ".$columnstotalsql." ".$reportquery." ".$wheresql; + } + }else + { + if($selectedcolumns == '') { + // Fix for: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/4758 - Prasad + + $selectedcolumns = "''"; // "''" to get blank column name + $allColumnsRestricted = true; + } + + $reportquery = "select ".$selectedcolumns." ".$reportquery." ".$wheresql; + } + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$tab_id] == 3) + { + $sec_parameter=getListViewSecurityParameter($this->primarymodule); + $reportquery .= " ".$sec_parameter; + } + + $sec_modules = split(":",$this->secondarymodule); + foreach($sec_modules as $i=>$key){ + $table_id = getTabid($key); + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $defaultOrgSharingPermission[$table_id] == 3) + { + $sec_parameter=getSecListViewSecurityParameter($key); + $reportquery .= " ".$sec_parameter; + } + } + + //if($tab_id == 9 || $tab_id == 16) + //$reportquery.=" group by vtiger_activity.activityid "; + + if(trim($groupsquery) != "" && empty($type)) + { + $reportquery .= " order by ".$groupsquery; + } + + // Prasad: No columns selected so limit the number of rows directly. + if($allColumnsRestricted) { + $reportquery .= " limit 0"; + } + + $log->info("ReportRun :: Successfully returned sGetSQLforReport".$reportid); + return $reportquery; + + } + + /** function to get the report output in HTML,PDF,TOTAL,PRINT,PRINTTOTAL formats depends on the argument $outputformat + * @ param $outputformat : Type String (valid parameters HTML,PDF,TOTAL,PRINT,PRINT_TOTAL) + * @ param $filterlist : Type Array + * This returns HTML Report if $outputformat is HTML + * Array for PDF if $outputformat is PDF + * HTML strings for TOTAL if $outputformat is TOTAL + * Array for PRINT if $outputformat is PRINT + * HTML strings for TOTAL fields if $outputformat is PRINTTOTAL + * HTML strings for + */ + + // Performance Optimization: Added parameter directOutput to avoid building big-string! + function GenerateReport($outputformat,$filterlist, $directOutput=false) + { + global $adb,$current_user,$php_max_execution_time; + global $modules,$app_strings; + global $mod_strings,$current_language; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $modules_selected = array(); + $modules_selected[] = $this->primarymodule; + if(!empty($this->secondarymodule)){ + $sec_modules = split(":",$this->secondarymodule); + for($i=0;$ipquery("SELECT tabid, fieldlabel, uitype from vtiger_field WHERE uitype in (71,72,10)", array()); + if($currencyfieldres) { + foreach($currencyfieldres as $currencyfieldrow) { + $modprefixedlabel = getTabModuleName($currencyfieldrow['tabid']).' '.$currencyfieldrow['fieldlabel']; + $modprefixedlabel = str_replace(' ','_',$modprefixedlabel); + if($currencyfieldrow['uitype']!=10){ + if(!in_array($modprefixedlabel, $this->convert_currency) && !in_array($modprefixedlabel, $this->append_currency_symbol_to_value)) { + $this->convert_currency[] = $modprefixedlabel; + } + } else { + if(!in_array($modprefixedlabel, $this->ui10_fields)) { + $this->ui10_fields[] = $modprefixedlabel; + } + } + } + } + + + if($outputformat == "HTML") + { + $sSQL = $this->sGetSQLforReport($this->reportid,$filterlist); + $result = $adb->query($sSQL); + $error_msg = $adb->database->ErrorMsg(); + if(!$result && $error_msg!=''){ + // Performance Optimization: If direct output is requried + if($directOutput) { + echo getTranslatedString('LBL_REPORT_GENERATION_FAILED', $currentModule) . "
    " . $error_msg; + $error_msg = false; + } + // END + return $error_msg; + } + + // Performance Optimization: If direct output is required + if($directOutput) { + echo ''; + } + // END + + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + $picklistarray = $this->getAccessPickListValues(); + if($result) + { + $y=$adb->num_fields($result); + $arrayHeaders = Array(); + for ($x=0; $x<$y; $x++) + { + $fld = $adb->field_name($result, $x); + if(in_array($this->getLstringforReportHeaders($fld->name), $arrayHeaders)) + { + $headerLabel = str_replace("_"," ",$fld->name); + $arrayHeaders[] = $headerLabel; + } + else + { + $headerLabel = str_replace($modules," ",$this->getLstringforReportHeaders($fld->name)); + $headerLabel = str_replace("_"," ",$this->getLstringforReportHeaders($fld->name)); + $arrayHeaders[] = $headerLabel; + } + /*STRING TRANSLATION starts */ + $mod_name = split(' ',$headerLabel,2); + $module =''; + if(in_array($mod_name[0],$modules_selected)){ + $module = getTranslatedString($mod_name[0],$mod_name[0]); + } + + if(!empty($this->secondarymodule)){ + if($module!=''){ + $headerLabel_tmp = $module." ".getTranslatedString($mod_name[1],$mod_name[0]); + } else { + $headerLabel_tmp = getTranslatedString($mod_name[0]." ".$mod_name[1]); + } + } else { + if($module!=''){ + $headerLabel_tmp = getTranslatedString($mod_name[1],$mod_name[0]); + } else { + $headerLabel_tmp = getTranslatedString($mod_name[0]." ".$mod_name[1]); + } + } + if($headerLabel == $headerLabel_tmp) $headerLabel = getTranslatedString($headerLabel_tmp); + else $headerLabel = $headerLabel_tmp; + /*STRING TRANSLATION ends */ + $header .= ""; + + // Performance Optimization: If direct output is required + if($directOutput) { + echo $header; + $header = ''; + } + // END + } + + // Performance Optimization: If direct output is required + if($directOutput) { + echo ''; + } + // END + + $noofrows = $adb->num_rows($result); + $custom_field_values = $adb->fetch_array($result); + $groupslist = $this->getGroupingList($this->reportid); + + $column_definitions = $adb->getFieldsDefinition($result); + + do + { + $arraylists = Array(); + if(count($groupslist) == 1) + { + $newvalue = $custom_field_values[0]; + }elseif(count($groupslist) == 2) + { + $newvalue = $custom_field_values[0]; + $snewvalue = $custom_field_values[1]; + }elseif(count($groupslist) == 3) + { + $newvalue = $custom_field_values[0]; + $snewvalue = $custom_field_values[1]; + $tnewvalue = $custom_field_values[2]; + } + if($newvalue == "") $newvalue = "-"; + + if($snewvalue == "") $snewvalue = "-"; + + if($tnewvalue == "") $tnewvalue = "-"; + + $valtemplate .= ""; + + // Performance Optimization + if($directOutput) { + echo $valtemplate; + $valtemplate = ''; + } + // END + + for ($i=0; $i<$y; $i++) + { + $fld = $adb->field_name($result, $i); + $fld_type = $column_definitions[$i]->type; + if (in_array($fld->name, $this->convert_currency)) { + if($custom_field_values[$i]!='') + $fieldvalue = convertFromMasterCurrency($custom_field_values[$i],$current_user->conv_rate); + else + $fieldvalue = getTranslatedString($custom_field_values[$i]); + } elseif(in_array($fld->name, $this->append_currency_symbol_to_value)) { + $curid_value = explode("::", $custom_field_values[$i]); + $currency_id = $curid_value[0]; + $currency_value = $curid_value[1]; + $cur_sym_rate = getCurrencySymbolandCRate($currency_id); + if($custom_field_values[$i]!='') + $fieldvalue = $cur_sym_rate['symbol']." ".$currency_value; + else + $fieldvalue = getTranslatedString($custom_field_values[$i]); + }elseif ($fld->name == "PurchaseOrder_Currency" || $fld->name == "SalesOrder_Currency" + || $fld->name == "Invoice_Currency" || $fld->name == "Quotes_Currency") { + if($custom_field_values[$i]!='') + $fieldvalue = getCurrencyName($custom_field_values[$i]); + else + $fieldvalue =getTranslatedString($custom_field_values[$i]); + }elseif (in_array($fld->name,$this->ui10_fields) && !empty($custom_field_values[$i])) { + $type = getSalesEntityType($custom_field_values[$i]); + $tmp =getEntityName($type,$custom_field_values[$i]); + foreach($tmp as $key=>$val){ + $fieldvalue = $val; + break; + } + } + else { + if($custom_field_values[$i]!='') + $fieldvalue = getTranslatedString($custom_field_values[$i]); + else + $fieldvalue = getTranslatedString($custom_field_values[$i]); + } + $fieldvalue = str_replace("<", "<", $fieldvalue); + $fieldvalue = str_replace(">", ">", $fieldvalue); + + //check for Roll based pick list + $temp_val= $fld->name; + if(is_array($picklistarray)) + if(array_key_exists($temp_val,$picklistarray)) + { + if(!in_array($custom_field_values[$i],$picklistarray[$fld->name]) && $custom_field_values[$i] != '') + $fieldvalue =$app_strings['LBL_NOT_ACCESSIBLE']; + + } + if(is_array($picklistarray[1])) + if(array_key_exists($temp_val,$picklistarray[1])) + { + $temp =explode(",",str_ireplace(' |##| ',',',$fieldvalue)); + $temp_val = Array(); + foreach($temp as $key =>$val) + { + if(!in_array(trim($val),$picklistarray[1][$fld->name]) && trim($val) != '') + { + $temp_val[]=$app_strings['LBL_NOT_ACCESSIBLE']; + } + else + $temp_val[]=$val; + } + $fieldvalue =(is_array($temp_val))?implode(", ",$temp_val):''; + } + + if($fieldvalue == "" ) + { + $fieldvalue = "-"; + } + else if(stristr($fieldvalue,"|##|")) + { + $fieldvalue = str_ireplace(' |##| ',', ',$fieldvalue); + } + else if($fld_type == "date" || $fld_type == "datetime") { + $fieldvalue = getDisplayDate($fieldvalue); + } + + if(($lastvalue == $fieldvalue) && $this->reporttype == "summary") + { + if($this->reporttype == "summary") + { + $valtemplate .= ""; + }else + { + $valtemplate .= ""; + } + }else if(($secondvalue === $fieldvalue) && $this->reporttype == "summary") + { + if($lastvalue === $newvalue) + { + $valtemplate .= ""; + }else + { + $valtemplate .= ""; + } + } + else if(($thirdvalue === $fieldvalue) && $this->reporttype == "summary") + { + if($secondvalue === $snewvalue) + { + $valtemplate .= ""; + }else + { + $valtemplate .= ""; + } + } + else + { + if($this->reporttype == "tabular") + { + $valtemplate .= ""; + }else + { + $valtemplate .= ""; + } + } + + // Performance Optimization: If direct output is required + if($directOutput) { + echo $valtemplate; + $valtemplate = ''; + } + // END + } + + $valtemplate .= ""; + + // Performance Optimization: If direct output is required + if($directOutput) { + echo $valtemplate; + $valtemplate = ''; + } + // END + + $lastvalue = $newvalue; + $secondvalue = $snewvalue; + $thirdvalue = $tnewvalue; + $arr_val[] = $arraylists; + set_time_limit($php_max_execution_time); + }while($custom_field_values = $adb->fetch_array($result)); + + // Performance Optimization + if($directOutput) { + echo "
    ".$headerLabel."
     ".$fieldvalue." ".$fieldvalue." ".$fieldvalue."".$fieldvalue."".$fieldvalue."
    "; + echo ""; + } else { + + $sHTML =' + '. + $header + .' + '. + $valtemplate + .' +
    '; + } + //<<<<<<<>>>>>>>>>>> + $return_data[] = $sHTML; + $return_data[] = $noofrows; + $return_data[] = $sSQL; + return $return_data; + } + }elseif($outputformat == "PDF") + { + + $sSQL = $this->sGetSQLforReport($this->reportid,$filterlist); + $result = $adb->query($sSQL); + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + $picklistarray = $this->getAccessPickListValues(); + + if($result) + { + $y=$adb->num_fields($result); + $noofrows = $adb->num_rows($result); + $custom_field_values = $adb->fetch_array($result); + $column_definitions = $adb->getFieldsDefinition($result); + + do + { + $arraylists = Array(); + for ($i=0; $i<$y; $i++) + { + $fld = $adb->field_name($result, $i); + if (in_array($fld->name, $this->convert_currency)) { + $fieldvalue = convertFromMasterCurrency($custom_field_values[$i],$current_user->conv_rate); + } elseif(in_array($fld->name, $this->append_currency_symbol_to_value)) { + $curid_value = explode("::", $custom_field_values[$i]); + $currency_id = $curid_value[0]; + $currency_value = $curid_value[1]; + $cur_sym_rate = getCurrencySymbolandCRate($currency_id); + $fieldvalue = $cur_sym_rate['symbol']." ".$currency_value; + }elseif ($fld->name == "PurchaseOrder_Currency" || $fld->name == "SalesOrder_Currency" + || $fld->name == "Invoice_Currency" || $fld->name == "Quotes_Currency") { + $fieldvalue = getCurrencyName($custom_field_values[$i]); + }elseif (in_array($fld->name,$this->ui10_fields) && !empty($custom_field_values[$i])) { + $type = getSalesEntityType($custom_field_values[$i]); + $tmp =getEntityName($type,$custom_field_values[$i]); + foreach($tmp as $key=>$val){ + $fieldvalue = $val; + break; + } + }else { + $fieldvalue = getTranslatedString($custom_field_values[$i]); + } + $append_cur = str_replace($fld->name,"",decode_html($this->getLstringforReportHeaders($fld->name))); + $headerLabel = str_replace("_"," ",$fld->name); + /*STRING TRANSLATION starts */ + $mod_name = split(' ',$headerLabel,2); + $module =''; + if(in_array($mod_name[0],$modules_selected)) + $module = getTranslatedString($mod_name[0],$mod_name[0]); + + if(!empty($this->secondarymodule)){ + if($module!=''){ + $headerLabel_tmp = $module." ".getTranslatedString($mod_name[1],$mod_name[0]); + } else { + $headerLabel_tmp = getTranslatedString($mod_name[0]." ".$mod_name[1]); + } + } else { + if($module!=''){ + $headerLabel_tmp = getTranslatedString($mod_name[1],$mod_name[0]); + } else { + $headerLabel_tmp = getTranslatedString($mod_name[0]." ".$mod_name[1]); + } + } + if($headerLabel == $headerLabel_tmp) $headerLabel = getTranslatedString($headerLabel_tmp); + else $headerLabel = $headerLabel_tmp; + /*STRING TRANSLATION starts */ + if(trim($append_cur)!="") $headerLabel .= $append_cur; + + $fieldvalue = str_replace("<", "<", $fieldvalue); + $fieldvalue = str_replace(">", ">", $fieldvalue); + + // Check for role based pick list + $temp_val= $fld->name; + if(is_array($picklistarray)) + if(array_key_exists($temp_val,$picklistarray)) + { + if(!in_array($custom_field_values[$i],$picklistarray[$fld->name]) && $custom_field_values[$i] != '') + { + $fieldvalue =$app_strings['LBL_NOT_ACCESSIBLE']; + } + } + if(is_array($picklistarray[1])) + if(array_key_exists($temp_val,$picklistarray[1])) + { + $temp =explode(",",str_ireplace(' |##| ',',',$fieldvalue)); + $temp_val = Array(); + foreach($temp as $key =>$val) + { + if(!in_array(trim($val),$picklistarray[1][$fld->name]) && trim($val) != '') + { + $temp_val[]=$app_strings['LBL_NOT_ACCESSIBLE']; + } + else + $temp_val[]=$val; + } + $fieldvalue =(is_array($temp_val))?implode(", ",$temp_val):''; + } + + if($fieldvalue == "" ) + { + $fieldvalue = "-"; + } + else if(stristr($fieldvalue,"|##|")) + { + $fieldvalue = str_ireplace(' |##| ',', ',$fieldvalue); + } + else if($fld_type == "date" || $fld_type == "datetime") { + $fieldvalue = getDisplayDate($fieldvalue); + } + if(array_key_exists($this->getLstringforReportHeaders($fld->name), $arraylists)) + $arraylists[$headerLabel] = $fieldvalue; + else + $arraylists[$headerLabel] = $fieldvalue; + } + $arr_val[] = $arraylists; + set_time_limit($php_max_execution_time); + }while($custom_field_values = $adb->fetch_array($result)); + + return $arr_val; + } + }elseif($outputformat == "TOTALHTML") + { + $escapedchars = Array('_SUM','_AVG','_MIN','_MAX'); + $sSQL = $this->sGetSQLforReport($this->reportid,$filterlist,"COLUMNSTOTOTAL"); + if(isset($this->totallist)) + { + if($sSQL != "") + { + $result = $adb->query($sSQL); + $y=$adb->num_fields($result); + $custom_field_values = $adb->fetch_array($result); + $coltotalhtml .= ""; + + // Performation Optimization: If Direct output is desired + if($directOutput) { + echo $coltotalhtml; + $coltotalhtml = ''; + } + // END + + foreach($this->totallist as $key=>$value) + { + $fieldlist = explode(":",$key); + $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid, uitype as uitype from vtiger_field where tablename = ? and columnname=?",array($fieldlist[1],$fieldlist[2])); + if($adb->num_rows($mod_query)>0){ + $module_name = getTabName($adb->query_result($mod_query,0,'tabid')); + $fieldlabel = trim(str_replace($escapedchars," ",$fieldlist[3])); + $fieldlabel = str_replace("_", " ", $fieldlabel); + if($module_name){ + $field = getTranslatedString($module_name)." ".getTranslatedString($fieldlabel,$module_name); + } else { + $field = getTranslatedString($module_name)." ".getTranslatedString($fieldlabel); + } + } + $uitype_arr[str_replace($escapedchars," ",$module_name."_".$fieldlist[3])] = $adb->query_result($mod_query,0,"uitype"); + $totclmnflds[str_replace($escapedchars," ",$module_name."_".$fieldlist[3])] = $field; + } + for($i =0;$i<$y;$i++) + { + $fld = $adb->field_name($result, $i); + $keyhdr[$fld->name] = $custom_field_values[$i]; + } + + foreach($totclmnflds as $key=>$value) + { + $coltotalhtml .= ''; + $col_header = trim(str_replace($modules," ",$value)); + $fld_name_1 = $this->primarymodule . "_" . trim($value); + $fld_name_2 = $this->secondarymodule . "_" . trim($value); + if($uitype_arr[$value]==71 || in_array($fld_name_1,$this->convert_currency) || in_array($fld_name_1,$this->append_currency_symbol_to_value) + || in_array($fld_name_2,$this->convert_currency) || in_array($fld_name_2,$this->append_currency_symbol_to_value)) { + $col_header .= " (".$app_strings['LBL_IN']." ".$current_user->currency_symbol.")"; + $convert_price = true; + } else{ + $convert_price = false; + } + $coltotalhtml .= ''; + $value = trim($key); + $arraykey = $value.'_SUM'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $arraykey = $value.'_AVG'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $arraykey = $value.'_MIN'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $arraykey = $value.'_MAX'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $coltotalhtml .= ''; + + // Performation Optimization: If Direct output is desired + if($directOutput) { + echo $coltotalhtml; + $coltotalhtml = ''; + } + // END + } + + $coltotalhtml .= "
    ".$mod_strings[Totals]."".$mod_strings[SUM]."".$mod_strings[AVG]."".$mod_strings[MIN]."".$mod_strings[MAX]."
    '. $col_header .''.$conv_value.' '.$conv_value.' '.$conv_value.' '.$conv_value.' 
    "; + + // Performation Optimization: If Direct output is desired + if($directOutput) { + echo $coltotalhtml; + $coltotalhtml = ''; + } + // END + } + } + return $coltotalhtml; + }elseif($outputformat == "PRINT") + { + $sSQL = $this->sGetSQLforReport($this->reportid,$filterlist); + $result = $adb->query($sSQL); + if($is_admin==false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + $picklistarray = $this->getAccessPickListValues(); + + if($result) + { + $y=$adb->num_fields($result); + $arrayHeaders = Array(); + for ($x=0; $x<$y; $x++) + { + $fld = $adb->field_name($result, $x); + if(in_array($this->getLstringforReportHeaders($fld->name), $arrayHeaders)) + { + $headerLabel = str_replace("_"," ",$fld->name); + $arrayHeaders[] = $headerLabel; + } + else + { + $headerLabel = str_replace($modules," ",$this->getLstringforReportHeaders($fld->name)); + $arrayHeaders[] = $headerLabel; + } + /*STRING TRANSLATION starts */ + $mod_name = split(' ',$headerLabel,2); + $module =''; + if(in_array($mod_name[0],$modules_selected)){ + $module = getTranslatedString($mod_name[0],$mod_name[0]); + } + + if(!empty($this->secondarymodule)){ + if($module!=''){ + $headerLabel_tmp = $module." ".getTranslatedString($mod_name[1],$mod_name[0]); + } else { + $headerLabel_tmp = getTranslatedString($mod_name[0]." ".$mod_name[1]); + } + } else { + if($module!=''){ + $headerLabel_tmp = getTranslatedString($mod_name[1],$mod_name[0]); + } else { + $headerLabel_tmp = getTranslatedString($mod_name[0]." ".$mod_name[1]); + } + } + if($headerLabel == $headerLabel_tmp) $headerLabel = getTranslatedString($headerLabel_tmp); + else $headerLabel = $headerLabel_tmp; + /*STRING TRANSLATION ends */ + $header .= "".$headerLabel.""; + } + $noofrows = $adb->num_rows($result); + $custom_field_values = $adb->fetch_array($result); + $groupslist = $this->getGroupingList($this->reportid); + + $column_definitions = $adb->getFieldsDefinition($result); + + do + { + $arraylists = Array(); + if(count($groupslist) == 1) + { + $newvalue = $custom_field_values[0]; + }elseif(count($groupslist) == 2) + { + $newvalue = $custom_field_values[0]; + $snewvalue = $custom_field_values[1]; + }elseif(count($groupslist) == 3) + { + $newvalue = $custom_field_values[0]; + $snewvalue = $custom_field_values[1]; + $tnewvalue = $custom_field_values[2]; + } + + if($newvalue == "") $newvalue = "-"; + + if($snewvalue == "") $snewvalue = "-"; + + if($tnewvalue == "") $tnewvalue = "-"; + + $valtemplate .= ""; + + for ($i=0; $i<$y; $i++) + { + $fld = $adb->field_name($result, $i); + if (in_array($fld->name, $this->convert_currency)) { + $fieldvalue = convertFromMasterCurrency($custom_field_values[$i],$current_user->conv_rate); + } elseif(in_array($fld->name, $this->append_currency_symbol_to_value)) { + $curid_value = explode("::", $custom_field_values[$i]); + $currency_id = $curid_value[0]; + $currency_value = $curid_value[1]; + $cur_sym_rate = getCurrencySymbolandCRate($currency_id); + $fieldvalue = $cur_sym_rate['symbol']." ".$currency_value; + }elseif ($fld->name == "PurchaseOrder_Currency" || $fld->name == "SalesOrder_Currency" + || $fld->name == "Invoice_Currency" || $fld->name == "Quotes_Currency") { + $fieldvalue = getCurrencyName($custom_field_values[$i]); + }elseif (in_array($fld->name,$this->ui10_fields) && !empty($custom_field_values[$i])) { + $type = getSalesEntityType($custom_field_values[$i]); + $tmp =getEntityName($type,$custom_field_values[$i]); + foreach($tmp as $key=>$val){ + $fieldvalue = $val; + break; + } + }else { + $fieldvalue = getTranslatedString($custom_field_values[$i]); + } + + $fieldvalue = str_replace("<", "<", $fieldvalue); + $fieldvalue = str_replace(">", ">", $fieldvalue); + + //Check For Role based pick list + $temp_val= $fld->name; + if(is_array($picklistarray)) + if(array_key_exists($temp_val,$picklistarray)) + { + if(!in_array($custom_field_values[$i],$picklistarray[$fld->name]) && $custom_field_values[$i] != '') + { + $fieldvalue =$app_strings['LBL_NOT_ACCESSIBLE']; + } + } + if(is_array($picklistarray[1])) + if(array_key_exists($temp_val,$picklistarray[1])) + { + + $temp =explode(",",str_ireplace(' |##| ',',',$fieldvalue)); + $temp_val = Array(); + foreach($temp as $key =>$val) + { + if(!in_array(trim($val),$picklistarray[1][$fld->name]) && trim($val) != '') + { + $temp_val[]=$app_strings['LBL_NOT_ACCESSIBLE']; + } + else + $temp_val[]=$val; + } + $fieldvalue =(is_array($temp_val))?implode(", ",$temp_val):''; + } + + + if($fieldvalue == "" ) + { + $fieldvalue = "-"; + } + else if(stristr($fieldvalue,"|##|")) + { + $fieldvalue = str_ireplace(' |##| ',', ',$fieldvalue); + } + else if($fld_type == "date" || $fld_type == "datetime") { + $fieldvalue = getDisplayDate($fieldvalue); + } + if(($lastvalue == $fieldvalue) && $this->reporttype == "summary") + { + if($this->reporttype == "summary") + { + $valtemplate .= " "; + }else + { + $valtemplate .= "".$fieldvalue.""; + } + }else if(($secondvalue == $fieldvalue) && $this->reporttype == "summary") + { + if($lastvalue == $newvalue) + { + $valtemplate .= " "; + }else + { + $valtemplate .= "".$fieldvalue.""; + } + } + else if(($thirdvalue == $fieldvalue) && $this->reporttype == "summary") + { + if($secondvalue == $snewvalue) + { + $valtemplate .= " "; + }else + { + $valtemplate .= "".$fieldvalue.""; + } + } + else + { + if($this->reporttype == "tabular") + { + $valtemplate .= "".$fieldvalue.""; + }else + { + $valtemplate .= "".$fieldvalue.""; + } + } + } + $valtemplate .= ""; + $lastvalue = $newvalue; + $secondvalue = $snewvalue; + $thirdvalue = $tnewvalue; + $arr_val[] = $arraylists; + set_time_limit($php_max_execution_time); + }while($custom_field_values = $adb->fetch_array($result)); + + $sHTML = ''.$header.''.$valtemplate; + $return_data[] = $sHTML; + $return_data[] = $noofrows; + return $return_data; + } + }elseif($outputformat == "PRINT_TOTAL") + { + $escapedchars = Array('_SUM','_AVG','_MIN','_MAX'); + $sSQL = $this->sGetSQLforReport($this->reportid,$filterlist,"COLUMNSTOTOTAL"); + if(isset($this->totallist)) + { + if($sSQL != "") + { + $result = $adb->query($sSQL); + $y=$adb->num_fields($result); + $custom_field_values = $adb->fetch_array($result); + + $coltotalhtml .= ''; + + foreach($this->totallist as $key=>$value) + { + $fieldlist = explode(":",$key); + $totclmnflds[str_replace($escapedchars," ",$fieldlist[3])] = str_replace($escapedchars," ",$fieldlist[3]); + } + + for($i =0;$i<$y;$i++) + { + $fld = $adb->field_name($result, $i); + $keyhdr[$fld->name] = $custom_field_values[$i]; + + } + foreach($totclmnflds as $key=>$value) + { + $coltotalhtml .= ''; + $col_header = getTranslatedString(trim(str_replace($modules," ",$value))); + $fld_name_1 = $this->primarymodule . "_" . trim($value); + $fld_name_2 = $this->secondarymodule . "_" . trim($value); + if(in_array($fld_name_1,$this->convert_currency) || in_array($fld_name_1,$this->append_currency_symbol_to_value) + || in_array($fld_name_2,$this->convert_currency) || in_array($fld_name_2,$this->append_currency_symbol_to_value)) { + $col_header .= " (".$app_strings['LBL_IN']." ".$current_user->currency_symbol.")"; + $convert_price = true; + } else { + $convert_price = false; + } + $coltotalhtml .= ''; + + $arraykey = trim($value).'_SUM'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $arraykey = trim($value).'_AVG'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $arraykey = trim($value).'_MIN'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $arraykey = trim($value).'_MAX'; + if(isset($keyhdr[$arraykey])) + { + if($convert_price) + $conv_value = convertFromMasterCurrency($keyhdr[$arraykey],$current_user->conv_rate); + else + $conv_value = $keyhdr[$arraykey]; + $coltotalhtml .= ''; + }else + { + $coltotalhtml .= ''; + } + + $coltotalhtml .= ''; + } + + $coltotalhtml .= "
    '.$mod_strings[Totals].''.$mod_strings[SUM].''.$mod_strings[AVG].''.$mod_strings[MIN].''.$mod_strings[MAX].'
    '. $col_header .''.$conv_value.' '.$conv_value.' '.$conv_value.' '.$conv_value.' 
    "; + } + } + return $coltotalhtml; + } + } + + //<<<<<<>>>>>>>>> + function getColumnsTotal($reportid) + { + // Have we initialized it already? + if($this->_columnstotallist !== false) { + return $this->_columnstotallist; + } + + global $adb; + global $modules; + global $log, $current_user; + + $query = "select * from vtiger_reportmodules where reportmodulesid =?"; + $res = $adb->pquery($query , array($reportid)); + $modrow = $adb->fetch_array($res); + $premod = $modrow["primarymodule"]; + $secmod = $modrow["secondarymodules"]; + $coltotalsql = "select vtiger_reportsummary.* from vtiger_report"; + $coltotalsql .= " inner join vtiger_reportsummary on vtiger_report.reportid = vtiger_reportsummary.reportsummaryid"; + $coltotalsql .= " where vtiger_report.reportid =?"; + + $result = $adb->pquery($coltotalsql, array($reportid)); + + while($coltotalrow = $adb->fetch_array($result)) + { + $fieldcolname = $coltotalrow["columnname"]; + if($fieldcolname != "none") + { + $fieldlist = explode(":",$fieldcolname); + $field_tablename = $fieldlist[1]; + $field_columnname = $fieldlist[2]; + + $mod_query = $adb->pquery("SELECT distinct(tabid) as tabid from vtiger_field where tablename = ? and columnname=?",array($fieldlist[1],$fieldlist[2])); + if($adb->num_rows($mod_query)>0){ + $module_name = getTabName($adb->query_result($mod_query,0,'tabid')); + $fieldlabel = trim($fieldlist[3]); + if($module_name){ + $field_columnalias = $module_name."_".$fieldlist[3]; + } else { + $field_columnalias = $module_name."_".$fieldlist[3]; + } + } + + //$field_columnalias = $fieldlist[3]; + $field_permitted = false; + if(CheckColumnPermission($field_tablename,$field_columnname,$premod) != "false"){ + $field_permitted = true; + } else { + $mod = split(":",$secmod); + foreach($mod as $key){ + if(CheckColumnPermission($field_tablename,$field_columnname,$key) != "false"){ + $field_permitted=true; + } + } + } + if($field_permitted == true) + { + $field = $field_tablename.".".$field_columnname; + if($field_tablename == 'vtiger_products' && $field_columnname == 'unit_price') { + // Query needs to be rebuild to get the value in user preferred currency. [innerProduct and actual_unit_price are table and column alias.] + $field = " innerProduct.actual_unit_price"; + } + if($field_tablename == 'vtiger_service' && $field_columnname == 'unit_price') { + // Query needs to be rebuild to get the value in user preferred currency. [innerProduct and actual_unit_price are table and column alias.] + $field = " innerService.actual_unit_price"; + } + if(($field_tablename == 'vtiger_invoice' || $field_tablename == 'vtiger_quotes' || $field_tablename == 'vtiger_purchaseorder' || $field_tablename == 'vtiger_salesorder') + && ($field_columnname == 'total' || $field_columnname == 'subtotal' || $field_columnname == 'discount_amount' || $field_columnname == 's_h_amount')) { + $field = " $field_tablename.$field_columnname/$field_tablename.conversion_rate "; + } + if($fieldlist[4] == 2) + { + $stdfilterlist[$fieldcolname] = "sum($field) '".$field_columnalias."'"; + } + if($fieldlist[4] == 3) + { + //Fixed average calculation issue due to NULL values ie., when we use avg() function, NULL values will be ignored.to avoid this we use (sum/count) to find average. + //$stdfilterlist[$fieldcolname] = "avg(".$fieldlist[1].".".$fieldlist[2].") '".$fieldlist[3]."'"; + $stdfilterlist[$fieldcolname] = "(sum($field)/count(*)) '".$field_columnalias."'"; + } + if($fieldlist[4] == 4) + { + $stdfilterlist[$fieldcolname] = "min($field) '".$field_columnalias."'"; + } + if($fieldlist[4] == 5) + { + $stdfilterlist[$fieldcolname] = "max($field) '".$field_columnalias."'"; + } + } + } + } + // Save the information + $this->_columnstotallist = $stdfilterlist; + + $log->info("ReportRun :: Successfully returned getColumnsTotal".$reportid); + return $stdfilterlist; + } + //<<<<<>>>>>>>> + + + /** function to get query for the columns to total for the given reportid + * @ param $reportid : Type integer + * This returns columnstoTotal query for the reportid + */ + + function getColumnsToTotalColumns($reportid) + { + global $adb; + global $modules; + global $log; + + $sreportstdfiltersql = "select vtiger_reportsummary.* from vtiger_report"; + $sreportstdfiltersql .= " inner join vtiger_reportsummary on vtiger_report.reportid = vtiger_reportsummary.reportsummaryid"; + $sreportstdfiltersql .= " where vtiger_report.reportid =?"; + + $result = $adb->pquery($sreportstdfiltersql, array($reportid)); + $noofrows = $adb->num_rows($result); + + for($i=0; $i<$noofrows; $i++) + { + $fieldcolname = $adb->query_result($result,$i,"columnname"); + + if($fieldcolname != "none") + { + $fieldlist = explode(":",$fieldcolname); + if($fieldlist[4] == 2) + { + $sSQLList[] = "sum(".$fieldlist[1].".".$fieldlist[2].") ".$fieldlist[3]; + } + if($fieldlist[4] == 3) + { + $sSQLList[] = "avg(".$fieldlist[1].".".$fieldlist[2].") ".$fieldlist[3]; + } + if($fieldlist[4] == 4) + { + $sSQLList[] = "min(".$fieldlist[1].".".$fieldlist[2].") ".$fieldlist[3]; + } + if($fieldlist[4] == 5) + { + $sSQLList[] = "max(".$fieldlist[1].".".$fieldlist[2].") ".$fieldlist[3]; + } + } + } + if(isset($sSQLList)) + { + $sSQL = implode(",",$sSQLList); + } + $log->info("ReportRun :: Successfully returned getColumnsToTotalColumns".$reportid); + return $sSQL; + } + /** Function to convert the Report Header Names into i18n + * @param $fldname: Type Varchar + * Returns Language Converted Header Strings + **/ + function getLstringforReportHeaders($fldname) + { + global $modules,$current_language,$current_user,$app_strings; + $rep_header = ltrim(str_replace($modules," ",$fldname)); + $rep_header_temp = ereg_replace(" ","_",$rep_header); + $rep_module = ereg_replace('_'.$rep_header_temp,"",$fldname); + $temp_mod_strings = return_module_language($current_language,$rep_module); + // htmlentities should be decoded in field names (eg. &). Noticed for fields like 'Terms & Conditions', 'S&H Amount' + $rep_header = decode_html($rep_header); + $curr_symb = ""; + if(in_array($fldname, $this->convert_currency)) { + $curr_symb = " (".$app_strings['LBL_IN']." ".$current_user->currency_symbol.")"; + } + if($temp_mod_strings[$rep_header] != '') + { + $rep_header = $temp_mod_strings[$rep_header]; + } + $rep_header .=$curr_symb; + + return $rep_header; + } + + /** Function to get picklist value array based on profile + * * returns permitted fields in array format + **/ + + + function getAccessPickListValues() + { + global $adb; + global $current_user; + $id = array(getTabid($this->primarymodule)); + if($this->secondarymodule != '') + array_push($id, getTabid($this->secondarymodule)); + + $query = 'select fieldname,columnname,fieldid,fieldlabel,tabid,uitype from vtiger_field where tabid in('. generateQuestionMarks($id) .') and uitype in (15,33,55)'; //and columnname in (?)'; + $result = $adb->pquery($query, $id);//,$select_column)); + $roleid=$current_user->roleid; + $subrole = getRoleSubordinates($roleid); + if(count($subrole)> 0) + { + $roleids = $subrole; + array_push($roleids, $roleid); + } + else + { + $roleids = $roleid; + } + + $temp_status = Array(); + for($i=0;$i < $adb->num_rows($result);$i++) + { + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $tabid = $adb->query_result($result,$i,"tabid"); + $uitype = $adb->query_result($result,$i,"uitype"); + + $fieldlabel1 = str_replace(" ","_",$fieldlabel); + $keyvalue = getTabModuleName($tabid)."_".$fieldlabel1; + $fieldvalues = Array(); + if (count($roleids) > 1) { + $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid in (\"". implode($roleids,"\",\"") ."\") and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; + } else { + $mulsel="select distinct $fieldname from vtiger_$fieldname inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_$fieldname.picklist_valueid where roleid ='".$roleid."' and picklistid in (select picklistid from vtiger_$fieldname) order by sortid asc"; + } + if($fieldname != 'firstname') + $mulselresult = $adb->query($mulsel); + for($j=0;$j < $adb->num_rows($mulselresult);$j++) + { + $fldvalue = $adb->query_result($mulselresult,$j,$fieldname); + if(in_array($fldvalue,$fieldvalues)) continue; + $fieldvalues[] = $fldvalue; + } + $field_count = count($fieldvalues); + if( $uitype == 15 && $field_count > 0 && ($fieldname == 'taskstatus' || $fieldname == 'eventstatus')) + { + $temp_count =count($temp_status[$keyvalue]); + if($temp_count > 0) + { + for($t=0;$t < $field_count;$t++) + { + $temp_status[$keyvalue][($temp_count+$t)] = $fieldvalues[$t]; + } + $fieldvalues = $temp_status[$keyvalue]; + } + else + $temp_status[$keyvalue] = $fieldvalues; + } + + if($uitype == 33) + $fieldlists[1][$keyvalue] = $fieldvalues; + else if($uitype == 55 && $fieldname == 'salutationtype') + $fieldlists[$keyvalue] = $fieldvalues; + else if($uitype == 15) + $fieldlists[$keyvalue] = $fieldvalues; + } + return $fieldlists; + } + + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Reports/ReportSharing.php b/oss/vtiger/trunk/modules/Reports/ReportSharing.php new file mode 100644 index 00000000..17a9a606 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportSharing.php @@ -0,0 +1,175 @@ +***************************/ + +require_once('Smarty_setup.php'); +require_once("data/Tracker.php"); +require_once('include/logging.php'); +require_once('include/utils/utils.php'); +require_once('modules/Reports/Reports.php'); + +global $app_strings; +global $app_list_strings; +global $mod_strings; +$current_module_strings = return_module_language($current_language, 'Reports'); +global $list_max_entries_per_page; +global $urlPrefix; + +$log = LoggerManager::getLogger('report_type'); +global $currentModule; +global $image_path; +global $theme; +global $current_user; + +$report_std_filter = new vtigerCRM_Smarty; +$report_std_filter->assign("MOD", $mod_strings); +$report_std_filter->assign("APP", $app_strings); +$report_std_filter->assign("IMAGE_PATH",$image_path); +$report_std_filter->assign("DATEFORMAT",$current_user->date_format); +$report_std_filter->assign("JS_DATEFORMAT",parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +$roleid = $current_user->column_fields['roleid']; +$user_array = getRoleAndSubordinateUsers($roleid); +$userIdStr = ""; +$userNameStr = ""; +$m=0; +foreach($user_array as $userid=>$username){ + + if($userid!=$current_user->id){ + if($m!=0){ + $userIdStr .= ","; + $userNameStr .= ","; + } + $userIdStr .="'".$userid."'"; + $userNameStr .="'".escape_single_quotes(decode_html($username))."'"; + $m++; + } +} + +require_once('include/utils/GetUserGroups.php'); +$userGroups = new GetUserGroups(); +$userGroups->getAllUserGroups($current_user->id); +$user_groups = $userGroups->user_groups; +$groupIdStr = ""; +$groupNameStr = ""; +$l=0; +foreach($user_groups as $i=>$grpid){ + $grp_details = getGroupDetails($grpid); + if($l!=0){ + $groupIdStr .= ","; + $groupNameStr .= ","; + } + $groupIdStr .= "'".$grp_details[0]."'"; + $groupNameStr .= "'".escape_single_quotes(decode_html($grp_details[1]))."'"; + $l++; +} +if(isset($_REQUEST["record"]) && $_REQUEST['record']!='') +{ + $reportid = vtlib_purify($_REQUEST["record"]); + $visiblecriteria=getVisibleCriteria($recordid); + $report_std_filter->assign("VISIBLECRITERIA", $visiblecriteria); + $member = getShareInfo($recordid); + $report_std_filter->assign("MEMBER", $member); +} else { + $visiblecriteria=getVisibleCriteria(); + $report_std_filter->assign("VISIBLECRITERIA", $visiblecriteria); +} +$report_std_filter->assign("GROUPNAMESTR", $groupNameStr); +$report_std_filter->assign("USERNAMESTR", $userNameStr); +$report_std_filter->assign("GROUPIDSTR", $groupIdStr); +$report_std_filter->assign("USERIDSTR", $userIdStr); + + +//include("modules/Reports/StandardFilter.php"); +//include("modules/Reports/AdvancedFilter.php"); + +$report_std_filter->display('ReportSharing.tpl'); + +/** Function to get visible criteria for a report + * This function accepts The reportid as an argument + * It returns a array of selected option of sharing along with other options + */ +function getVisibleCriteria($recordid='') +{ + global $mod_strings; + global $app_strings; + global $adb,$current_user; + //print_r("i am here");die; + $filter = array(); + $selcriteria = ""; + if($recordid!='') + { + $result = $adb->pquery("select sharingtype from vtiger_report where reportid=?",array($recordid)); + $selcriteria=$adb->query_result($result,0,"sharingtype"); + } + if($selcriteria == ""){ + $selcriteria = 'Public'; + } + $filter_result = $adb->query("select * from vtiger_reportfilters"); + $numrows = $adb->num_rows($filter_result); + for($j=0;$j<$numrows;$j++) + { + $filter_id = $adb->query_result($filter_result,$j,"filterid"); + $filtername = $adb->query_result($filter_result,$j,"name"); + $name=str_replace(' ','_',$filtername); + if($filtername == 'Private') { + $FilterKey='Private'; + $FilterValue=getTranslatedString('PRIVATE_FILTER'); + }elseif($filtername=='Shared') + { + $FilterKey='Shared'; + $FilterValue=getTranslatedString('SHARE_FILTER'); + }else{ + $FilterKey='Public'; + $FilterValue=getTranslatedString('PUBLIC_FILTER'); + } + if($FilterKey == $selcriteria) + { + $shtml['value'] = $FilterKey; + $shtml['text'] = $FilterValue; + $shtml['selected'] = "selected"; + }else + { + $shtml['value'] = $FilterKey; + $shtml['text'] = $FilterValue; + $shtml['selected'] = ""; + } + $filter[] = $shtml; + } + return $filter; +} + +function getShareInfo($recordid=''){ + global $adb; + $member_query = $adb->pquery("SELECT vtiger_reportsharing.setype,vtiger_users.id,vtiger_users.user_name FROM vtiger_reportsharing INNER JOIN vtiger_users on vtiger_users.id = vtiger_reportsharing.shareid WHERE vtiger_reportsharing.setype='users' AND vtiger_reportsharing.reportid = ?",array($recordid)); + $noofrows = $adb->num_rows($member_query); + if($noofrows > 0){ + for($i=0;$i<$noofrows;$i++){ + $userid = $adb->query_result($member_query,$i,'id'); + $username = $adb->query_result($member_query,$i,'user_name'); + $setype = $adb->query_result($member_query,$i,'setype'); + $member_data[] = Array('id'=>$setype."::".$userid,'name'=>$setype."::".$username); + } + } + + $member_query = $adb->pquery("SELECT vtiger_reportsharing.setype,vtiger_groups.groupid,vtiger_groups.groupname FROM vtiger_reportsharing INNER JOIN vtiger_groups on vtiger_groups.groupid = vtiger_reportsharing.shareid WHERE vtiger_reportsharing.setype='groups' AND vtiger_reportsharing.reportid = ?",array($recordid)); + $noofrows = $adb->num_rows($member_query); + if($noofrows > 0){ + for($i=0;$i<$noofrows;$i++){ + $grpid = $adb->query_result($member_query,$i,'groupid'); + $grpname = $adb->query_result($member_query,$i,'groupname'); + $setype = $adb->query_result($member_query,$i,'setype'); + $member_data[] = Array('id'=>$setype."::".$grpid,'name'=>$setype."::".$grpname); + } + } + return $member_data; +} + +?> diff --git a/oss/vtiger/trunk/modules/Reports/ReportType.php b/oss/vtiger/trunk/modules/Reports/ReportType.php new file mode 100644 index 00000000..940732d4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportType.php @@ -0,0 +1,47 @@ +assign("MOD", $mod_strings); +$list_report_form->assign("APP", $app_strings); +$list_report_form->assign("IMAGE_PATH",$image_path); +if(isset($_REQUEST["record"]) && $_REQUEST['record']!='') +{ + $recordid = vtlib_purify($_REQUEST["record"]); + $oReport = new Reports($recordid); + $selectedreporttype = $oReport->reporttype; +}else +{ + $selectedreporttype = "tabular"; +} +$list_report_form->assign("REPORT_TYPE",$selectedreporttype); +$list_report_form->display("ReportsType.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Reports/Reports.js b/oss/vtiger/trunk/modules/Reports/Reports.js new file mode 100644 index 00000000..2be655c7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/Reports.js @@ -0,0 +1,794 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ +var typeofdata = new Array(); +typeofdata['V'] = ['e','n','s','ew','c','k']; +typeofdata['N'] = ['e','n','l','g','m','h']; +typeofdata['T'] = ['e','n','l','g','m','h']; +typeofdata['I'] = ['e','n','l','g','m','h']; +typeofdata['C'] = ['e','n']; +typeofdata['D'] = ['e','n','l','g','m','h']; +typeofdata['NN'] = ['e','n','l','g','m','h']; +typeofdata['E'] = ['e','n','s','ew','c','k']; + +var fLabels = new Array(); +fLabels['e'] = alert_arr.EQUALS; +fLabels['n'] = alert_arr.NOT_EQUALS_TO; +fLabels['s'] = alert_arr.STARTS_WITH; +fLabels['ew'] = alert_arr.ENDS_WITH; +fLabels['c'] = alert_arr.CONTAINS; +fLabels['k'] = alert_arr.DOES_NOT_CONTAINS; +fLabels['l'] = alert_arr.LESS_THAN; +fLabels['g'] = alert_arr.GREATER_THAN; +fLabels['m'] = alert_arr.LESS_OR_EQUALS; +fLabels['h'] = alert_arr.GREATER_OR_EQUALS; +var noneLabel; +var gcurrepfolderid=0; +function trimfValues(value) +{ + var string_array; + string_array = value.split(":"); + return string_array[4]; +} + +function updatefOptions(sel, opSelName) { + var selObj = document.getElementById(opSelName); + var fieldtype = null ; + + var currOption = selObj.options[selObj.selectedIndex]; + var currField = sel.options[sel.selectedIndex]; + + if(currField.value != null && currField.value.length != 0) + { + fieldtype = trimfValues(currField.value); + ops = typeofdata[fieldtype]; + var off = 0; + if(ops != null) + { + + var nMaxVal = selObj.length; + for(nLoop = 0; nLoop < nMaxVal; nLoop++) + { + selObj.remove(0); + } + selObj.options[0] = new Option ('None', ''); + if (currField.value == '') { + selObj.options[0].selected = true; + } + off = 1; + for (var i = 0; i < ops.length; i++) + { + var label = fLabels[ops[i]]; + if (label == null) continue; + var option = new Option (fLabels[ops[i]], ops[i]); + selObj.options[i + off] = option; + if (currOption != null && currOption.value == option.value) + { + option.selected = true; + } + } + } + }else + { + var nMaxVal = selObj.length; + for(nLoop = 0; nLoop < nMaxVal; nLoop++) + { + selObj.remove(0); + } + selObj.options[0] = new Option ('None', ''); + if (currField.value == '') { + selObj.options[0].selected = true; + } + } + +} + +// Setting cookies +function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure ) +{ + var cookie_string = name + "=" + escape ( value ); + + if ( exp_y ) + { + var expires = new Date ( exp_y, exp_m, exp_d ); + cookie_string += "; expires=" + expires.toGMTString(); + } + + if ( path ) + cookie_string += "; path=" + escape ( path ); + + if ( domain ) + cookie_string += "; domain=" + escape ( domain ); + + if ( secure ) + cookie_string += "; secure"; + + document.cookie = cookie_string; +} + +// Retrieving cookies +function get_cookie ( cookie_name ) +{ + var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' ); + + if ( results ) + return ( unescape ( results[1] ) ); + else + return null; +} + + +// Delete cookies +function delete_cookie ( cookie_name ) +{ + var cookie_date = new Date ( ); // current date & time + cookie_date.setTime ( cookie_date.getTime() - 1 ); + document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); +} +function goToURL( url ) +{ + document.location.href = url; +} + +function invokeAction( actionName ) +{ + if( actionName == "newReport" ) + { + goToURL( "?module=Reports&action=NewReport0&return_module=Reports&return_action=index" ); + return; + } + goToURL( "/crm/ScheduleReport.do?step=showAllSchedules" ); +} +function verify_data(form) { + var isError = false; + var errorMessage = ""; + if (trim(form.folderName.value) == "") { + isError = true; + errorMessage += "\nFolder Name"; + } + // Here we decide whether to submit the form. + if (isError == true) { + alert(alert_arr.MISSING_FIELDS + errorMessage); + return false; + } + return true; +} + +function setObjects() +{ + availListObj=getObj("availList") + selectedColumnsObj=getObj("selectedColumns") + + moveupLinkObj=getObj("moveup_link") + moveupDisabledObj=getObj("moveup_disabled") + movedownLinkObj=getObj("movedown_link") + movedownDisabledObj=getObj("movedown_disabled") +} + +function addColumn() +{ + for (i=0;i -1) + { + for (i=0;i -1) { + for(var i = 0; i < oSel.options.length; ++i) { + if(oSel.options[i].selected == true && oSel.options[i].disabled == true) { + error_msg = error_msg + oSel.options[i].text+','; + error_str = true; + oSel.options[i].selected = false; + } + } + } + if(error_str) + { + error_msg = error_msg.substr(0,error_msg.length-1); + alert(alert_arr.NOT_ALLOWED_TO_EDIT_FIELDS+"\n"+error_msg); + return false; + } + else + return true; +} +function delColumn() +{ + if (selectedColumnsObj.options.selectedIndex > -1) + { + for (i=0;i < selectedColumnsObj.options.length;i++) + { + if(selectedColumnsObj.options[i].selected == true) + { + selectedColumnsObj.remove(i); + delColumn(); + } + } + } +} + +function formSelectColumnString() +{ + var selectedColStr = ""; + for (i=0;i0) + { + var prevpos=selectedColumnsObj.options.selectedIndex-1 + + if (browser_ie) + { + temp=selectedColumnsObj.options[prevpos].innerText + tempdisabled = selectedColumnsObj.options[prevpos].disabled; + selectedColumnsObj.options[prevpos].innerText=selectedColumnsObj.options[currpos].innerText + selectedColumnsObj.options[prevpos].disabled = false; + selectedColumnsObj.options[currpos].innerText=temp + selectedColumnsObj.options[currpos].disabled = tempdisabled; + } + else if (browser_nn4 || browser_nn6) + { + temp=selectedColumnsObj.options[prevpos].text + tempdisabled = selectedColumnsObj.options[prevpos].disabled; + selectedColumnsObj.options[prevpos].text=selectedColumnsObj.options[currpos].text + selectedColumnsObj.options[prevpos].disabled = false; + selectedColumnsObj.options[currpos].text=temp + selectedColumnsObj.options[currpos].disabled = tempdisabled; + } + temp=selectedColumnsObj.options[prevpos].value + selectedColumnsObj.options[prevpos].value=selectedColumnsObj.options[currpos].value + selectedColumnsObj.options[currpos].value=temp + selectedColumnsObj.options[prevpos].selected=true + selectedColumnsObj.options[currpos].selected=false + } + +} + +function moveDown() +{ + var currpos=selectedColumnsObj.options.selectedIndex + var tempdisabled= false; + for (i=0;i1) + { + moveupLinkObj.style.display=movedownLinkObj.style.display="none" + moveupDisabledObj.style.display=movedownDisabledObj.style.display="block" + } + else + { + moveupLinkObj.style.display=movedownLinkObj.style.display="block" + moveupDisabledObj.style.display=movedownDisabledObj.style.display="none" + } +} + + +function hideTabs() +{ + // Check the selected report type + var objreportType = document.forms.NewReport['reportType']; + if(objreportType[0].checked == true) objreportType = objreportType[0]; + else if(objreportType[1].checked == true) objreportType = objreportType[1]; + + if(objreportType.value == 'tabular') + { + divarray = new Array('step1','step2','step4','step5','step6'); + } + else + { + divarray = new Array('step1','step2','step3','step4','step5','step6'); + } +} + +function showSaveDialog() +{ + url = "index.php?module=Reports&action=SaveReport"; + window.open(url,"Save_Report","width=550,height=350,top=20,left=20;toolbar=no,status=no,menubar=no,directories=no,resizable=yes,scrollbar=no") +} + +function saveAndRunReport() +{ + if(selectedColumnsObj.options.length == 0) + { + alert(alert_arr.COLUMNS_CANNOT_BE_EMPTY); + return false; + } + formSelectedColumnString(); + formSelectColumnString(); + document.NewReport.submit(); +} + +function changeSteps1() +{ + if(getObj('step5').style.display != 'none') + { + var escapedOptions = new Array('account_id','contactid','contact_id','product_id','parent_id','campaignid','potential_id','assigned_user_id1','quote_id','accountname','salesorder_id','vendor_id','time_start','time_end','lastname'); + + for(var i=1;i < 6 ; i++) + { + var option_name="fcol"+i; + var option_value=getObj(option_name).value; + var option_object=getObj(option_name); + var comp_name="fop"+i; + var comp_value=getObj(comp_name).value; + var data_name="fval"+i; + var data_value=trim(getObj(data_name).value); + var collabel=''; + count=option_object.selectedIndex; + collabel=option_object.options[count].text + if(trim(option_value) != '') + { + if (!emptyCheck(comp_name,collabel+" Option","text")) + return false + } + else if(trim(data_value) != '') + { + if (!emptyCheck(option_name," Column ","text")) + return false + if (!emptyCheck(comp_name,collabel+" Option","text")) + return false + } + + if(trim(data_value) != '' && option_value != '' && comp_value != '') + { + var col=option_value.split(":"); + if(escapedOptions.indexOf(col[3]) == -1) + { + if(col[4] == 'T') + { + var datime = data_value.split(" "); + if(!re_dateValidate(datime[0],collabel+" (Current User Date Time Format)","OTH")) + return false + if(datime.length > 1) + if(!re_patternValidate(datime[1],collabel+" (Time)","TIMESECONDS")) + return false + } + else if(col[4] == 'D') + { + if(!dateValidate(data_name,collabel+" (Current User Date Format)","OTH")) + return false + }else if(col[4] == 'I') + { + if(!intValidate(data_name,collabel+" (Integer Criteria)"+i)) + return false + }else if(col[4] == 'N') + { + if (!numValidate(data_name,collabel+" (Number) ","any",true)) + return false + }else if(col[4] == 'E') + { + if (!patternValidate(data_name,collabel+" (Email Id)","EMAIL")) + return false + } + } + } + } + var date1=getObj("startdate") + var date2=getObj("enddate") + + //Added to handle yes or no for checkbox fields in reports advance filters. + for(var i=1;i<=5;i++) + { + value=trim(getObj("fval"+i).value); + option=getObj("fcol"+i).value; + if(option !="" && value !="") + { + arr=option.split(":"); + if(arr[4] == "C") + { + if(value == "1") + getObj("fval"+i).value='yes'; + else if(value =="0") + getObj("fval"+i).value='no'; + } + } + } + + + //# validation added for date field validation in final step of report creation + if ((date1.value != '') || (date2.value != '')) + { + + if(!dateValidate("startdate","Start Date","D")) + return false + + if(!dateValidate("enddate","End Date","D")) + return false + + if(! dateComparison("startdate",'Start Date',"enddate",'End Date','LE')) + return false; + } + + } if (getObj('step6').style.display != 'none') { + saveAndRunReport(); + } else { + for (i = 0; i < divarray.length; i++) { + if (getObj(divarray[i]).style.display != 'none') { + if (i == 1 && selectedColumnsObj.options.length == 0) { + alert(alert_arr.COLUMNS_CANNOT_BE_EMPTY); + return false; + } + if (divarray[i] == 'step5') { + document.getElementById("next").value = finish_text; + } + hide(divarray[i]); + show(divarray[i + 1]); + tableid = divarray[i] + 'label'; + newtableid = divarray[i + 1] + 'label'; + getObj(tableid).className = 'settingsTabList'; + getObj(newtableid).className = 'settingsTabSelected'; + document.getElementById('back_rep').disabled = false; + break; + } + + } + } +} +function changeStepsback1() +{ + if(getObj('step1').style.display != 'none') + { + document.NewReport.action.value='ReportsAjax'; + document.NewReport.file.value='NewReport0'; + document.NewReport.submit(); + }else + { + for(i = 0; i < divarray.length ;i++) + { + if(getObj(divarray[i]).style.display != 'none') + { + if(divarray[i] == 'step2' && !backwalk_flag) + { + document.getElementById('back_rep').disabled = true; + } + document.getElementById("next").value = next_text+'>'; + hide(divarray[i]); + show(divarray[i-1]); + tableid = divarray[i]+'label'; + newtableid = divarray[i-1]+'label'; + getObj(tableid).className = 'settingsTabList'; + getObj(newtableid).className = 'settingsTabSelected'; + break; + } + + } + } +} +function changeSteps() +{ + if(getObj('step1').style.display != 'none') + { + if (trim(document.NewRep.reportname.value) == "") + { + alert(alert_arr.MISSING_REPORT_NAME); + return false; + }else + { + new Ajax.Request( + 'index.php', + {queue: {position: 'end', scope: 'command'}, + method: 'post', + postBody: 'action=ReportsAjax&mode=ajax&file=CheckReport&module=Reports&check=reportCheck&reportName='+encodeURIComponent(document.NewRep.reportname.value), + onComplete: function(response) { + if(response.responseText!=0) + { + alert(alert_arr.REPORT_NAME_EXISTS); + return false; + } + else + { + hide('step1'); + show('step2'); + document.getElementById('back_rep').disabled = false; + getObj('step1label').className = 'settingsTabList'; + getObj('step2label').className = 'settingsTabSelected'; + } + + } + } + ); + + } + + } + else + { + document.NewRep.submit(); + } +} +function changeStepsback() +{ + hide('step2'); + show('step1'); + document.getElementById('back_rep').disabled = true; + getObj('step1label').className = 'settingsTabSelected'; + getObj('step2label').className = 'settingsTabList'; +} +function editReport(id) +{ + var arg = 'index.php?module=Reports&action=ReportsAjax&file=NewReport0&record='+id; + fnPopupWin(arg); +} +function CreateReport(module) +{ + var arg ='index.php?module=Reports&action=ReportsAjax&file=NewReport0&folder='+gcurrepfolderid+'&reportmodule='+module; + fnPopupWin(arg); +} +function fnPopupWin(winName){ + window.open(winName, "ReportWindow","width=790px,height=630px,scrollbars=yes"); +} +function re_dateValidate(fldval,fldLabel,type) { + if(re_patternValidate(fldval,fldLabel,"DATE")==false) + return false; + dateval=fldval.replace(/^\s+/g, '').replace(/\s+$/g, '') + + var dateelements=splitDateVal(dateval) + + dd=dateelements[0] + mm=dateelements[1] + yyyy=dateelements[2] + + if (dd<1 || dd>31 || mm<1 || mm>12 || yyyy<1 || yyyy<1000) { + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + + if ((mm==2) && (dd>29)) {//checking of no. of days in february month + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + + if ((mm==2) && (dd>28) && ((yyyy%4)!=0)) {//leap year checking + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + + switch (parseInt(mm)) { + case 2 : + case 4 : + case 6 : + case 9 : + case 11 : if (dd>30) { + alert(alert_arr.ENTER_VALID+fldLabel) + return false + } + } + + var currdate=new Date() + var chkdate=new Date() + + chkdate.setYear(yyyy) + chkdate.setMonth(mm-1) + chkdate.setDate(dd) + + if (type!="OTH") { + if (!compareDates(chkdate,fldLabel,currdate,"current date",type)) { + return false + } else return true; + } else return true; +} + +//Copied from general.js and altered some lines. becos we cant send vales to function present in general.js. it accept only field names. +function re_patternValidate(fldval,fldLabel,type) { + if (type.toUpperCase()=="DATE") {//DATE validation + + switch (userDateFormat) { + case "yyyy-mm-dd" : + var re = /^\d{4}(-)\d{1,2}\1\d{1,2}$/ + break; + case "mm-dd-yyyy" : + case "dd-mm-yyyy" : + var re = /^\d{1,2}(-)\d{1,2}\1\d{4}$/ + } + } + + + if (type.toUpperCase()=="TIMESECONDS") {//TIME validation + var re = new RegExp("^([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$"); + } + if (!re.test(fldval)) { + alert(alert_arr.ENTER_VALID + fldLabel) + return false + } + else return true +} + +//added to fix the ticket #5117 +function standardFilterDisplay() +{ + if(document.NewReport.stdDateFilterField.options.length <= 0 || (document.NewReport.stdDateFilterField.selectedIndex > -1 && document.NewReport.stdDateFilterField.options[document.NewReport.stdDateFilterField.selectedIndex].value == "Not Accessible")) + { + getObj('stdDateFilter').disabled = true; + getObj('startdate').disabled = true; getObj('enddate').disabled = true; + getObj('jscal_trigger_date_start').style.visibility="hidden"; + getObj('jscal_trigger_date_end').style.visibility="hidden"; + } + else + { + getObj('stdDateFilter').disabled = false; + getObj('startdate').disabled = false; + getObj('enddate').disabled = false; + getObj('jscal_trigger_date_start').style.visibility="visible"; + getObj('jscal_trigger_date_end').style.visibility="visible"; + } +} + + +function updateRelFieldOptions(sel, opSelName) { + var selObj = document.getElementById(opSelName); + var fieldtype = null ; + + var currOption = selObj.options[selObj.selectedIndex]; + var currField = sel.options[sel.selectedIndex]; + + if(currField.value != null && currField.value.length != 0) + { + fieldtype = trimfValues(currField.value); + ops = rel_fields[fieldtype]; + + var off = 0; + if(ops != null) + { + var nMaxVal = selObj.length; + for(nLoop = 0; nLoop < nMaxVal; nLoop++) + { + selObj.remove(0); + } + selObj.options[0] = new Option ('None', ''); + if (currField.value == '') { + selObj.options[0].selected = true; + } + off = 1; + for (var i = 0; i < ops.length; i++) + { + var field_array = ops[i].split("::"); + var label = field_array[1]; + var field = field_array[0]; + if (label == null) continue; + var option = new Option (label, field); + selObj.options[i + off] = option; + if (currOption != null && currOption.value == option.value) + { + option.selected = true; + } + } + } + }else + { + var nMaxVal = selObj.length; + for(nLoop = 0; nLoop < nMaxVal; nLoop++) + { + selObj.remove(0); + } + selObj.options[0] = new Option ('None', ''); + if (currField.value == '') { + selObj.options[0].selected = true; + } + } + +} + +function AddFieldToFilter(id, sel){ + if(trim(document.getElementById("fval"+id).value)==''){ + document.getElementById("fval"+id).value = document.getElementById("fval_"+id).value; + } else { + document.getElementById("fval"+id).value = document.getElementById("fval"+id).value+","+document.getElementById("fval_"+id).value; + } +} +function fnLoadRepValues(tab1,tab2,block1,block2){ + document.getElementById(block1).style.display='block'; + document.getElementById(block2).style.display='none'; + document.getElementById(tab1).className='dvtSelectedCell'; + document.getElementById(tab2).className='dvtUnSelectedCell'; +} diff --git a/oss/vtiger/trunk/modules/Reports/Reports.php b/oss/vtiger/trunk/modules/Reports/Reports.php new file mode 100644 index 00000000..02947316 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/Reports.php @@ -0,0 +1,1570 @@ +"equals", + "n"=>"not equal to", + "s"=>"starts with", + "ew"=>"ends with", + "c"=>"contains", + "k"=>"does not contain", + "l"=>"less than", + "g"=>"greater than", + "m"=>"less or equal", + "h"=>"greater or equal" + ); + +//$report_modules = Array('Faq','Rss','Portal','Recyclebin','Emails','Reports','Dashboard','Home','Activities' + // ); + +$old_related_modules = Array('Accounts'=>Array('Potentials','Contacts','Products','Quotes','Invoice'), + 'Contacts'=>Array('Accounts','Potentials','Quotes','PurchaseOrder'), + 'Potentials'=>Array('Accounts','Contacts','Quotes'), + 'Calendar'=>Array('Leads','Accounts','Contacts','Potentials'), + 'Products'=>Array('Accounts','Contacts'), + 'HelpDesk'=>Array('Products'), + 'Quotes'=>Array('Accounts','Contacts','Potentials'), + 'PurchaseOrder'=>Array('Contacts'), + 'Invoice'=>Array('Accounts'), + 'Campaigns'=>Array('Products'), + ); + +$related_modules =Array(); + +class Reports extends CRMEntity{ + + + + /** + * This class has the informations for Reports and inherits class CRMEntity and + * has the variables required to generate,save,restore vtiger_reports + * and also the required functions for the same + * Contributor(s): ______________________________________.. + */ + + + var $srptfldridjs; + + var $column_fields = Array(); + + var $sort_fields = Array(); + var $sort_values = Array(); + + var $id; + var $mode; + var $mcount; + + var $startdate; + var $enddate; + + var $ascdescorder; + + var $stdselectedfilter; + var $stdselectedcolumn; + + var $primodule; + var $secmodule; + var $columnssummary; + var $is_editable; + var $reporttype; + var $reportname; + var $reportdescription; + var $folderid; + var $module_blocks; + + var $pri_module_columnslist; + var $sec_module_columnslist; + + var $advft_column; + var $advft_option; + var $advft_value; + var $adv_rel_fields = Array(); + + var $module_list = Array(); + + /** Function to set primodule,secmodule,reporttype,reportname,reportdescription,folderid for given vtiger_reportid + * This function accepts the vtiger_reportid as argument + * It sets primodule,secmodule,reporttype,reportname,reportdescription,folderid for the given vtiger_reportid + */ + + function Reports($reportid="") + { + global $adb,$current_user,$theme,$mod_strings; + $this->initListOfModules(); + if($reportid != "") + { + // Lookup information in cache first + $cachedInfo = VTCacheUtils::lookupReport_Info($current_user->id, $reportid); + $subordinate_users = VTCacheUtils::lookupReport_SubordinateUsers($reportid); + + if($cachedInfo === false) { + $ssql = "select vtiger_reportmodules.*,vtiger_report.* from vtiger_report inner join vtiger_reportmodules on vtiger_report.reportid = vtiger_reportmodules.reportmodulesid"; + $ssql .= " where vtiger_report.reportid = ?"; + $params = array($reportid); + + require_once('include/utils/GetUserGroups.php'); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $userGroups = new GetUserGroups(); + $userGroups->getAllUserGroups($current_user->id); + $user_groups = $userGroups->user_groups; + if(!empty($user_groups) && $is_admin==false){ + $user_group_query = " (shareid IN (".generateQuestionMarks($user_groups).") AND setype='groups') OR"; + array_push($params, $user_groups); + } + + $non_admin_query = " vtiger_report.reportid IN (SELECT reportid from vtiger_reportsharing WHERE $user_group_query (shareid=? AND setype='users'))"; + if($is_admin==false){ + $ssql .= " and ( (".$non_admin_query.") or vtiger_report.sharingtype='Public' or vtiger_report.owner = ? or vtiger_report.owner 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."::%'))"; + array_push($params, $current_user->id); + array_push($params, $current_user->id); + } + + $query = $adb->pquery("select 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."::%'",array()); + $subordinate_users = Array(); + for($i=0;$i<$adb->num_rows($query);$i++){ + $subordinate_users[] = $adb->query_result($query,$i,'userid'); + } + + // Update subordinate user information for re-use + VTCacheUtils::updateReport_SubordinateUsers($reportid, $subordinate_users); + + $result = $adb->pquery($ssql, $params); + if($result && $adb->num_rows($result)) { + $reportmodulesrow = $adb->fetch_array($result); + + // Update information in cache now + VTCacheUtils::updateReport_Info( + $current_user->id, $reportid, $reportmodulesrow["primarymodule"], + $reportmodulesrow["secondarymodules"], $reportmodulesrow["reporttype"], + $reportmodulesrow["reportname"], $reportmodulesrow["description"], + $reportmodulesrow["folderid"], $reportmodulesrow["owner"] + ); + } + + // Re-look at cache to maintain code-consistency below + $cachedInfo = VTCacheUtils::lookupReport_Info($current_user->id, $reportid); + } + + if($cachedInfo) { + $this->primodule = $cachedInfo["primarymodule"]; + $this->secmodule = $cachedInfo["secondarymodules"]; + $this->reporttype = $cachedInfo["reporttype"]; + $this->reportname = decode_html($cachedInfo["reportname"]); + $this->reportdescription = decode_html($cachedInfo["description"]); + $this->folderid = $cachedInfo["folderid"]; + if($is_admin==true || in_array($cachedInfo["owner"],$subordinate_users) || $cachedInfo["owner"]==$current_user->id) + $this->is_editable = 'true'; + else + $this->is_editable = 'false'; + } else { + if($_REQUEST['mode'] != 'ajax') + { + include('themes/'.$theme.'/header.php'); + } + echo "
    "; + echo "
    + + + + + + + + + +
    You are not allowed to View this Report
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; + break; + + } + } + } + + // Update the module list for listing columns for report creation. + function updateModuleList($module) { + global $adb; + if (!isset($module)) return; + require_once('include/utils/utils.php'); + $tabid = getTabid($module); + if ($module == 'Calendar') { + $tabid = array(9, 16); + } + $sql = "SELECT blockid, blocklabel FROM vtiger_blocks WHERE tabid IN (". generateQuestionMarks($tabid) .")"; + $res = $adb->pquery($sql, array($tabid)); + $noOfRows = $adb->num_rows($res); + if ($noOfRows <= 0) return; + for($index = 0; $index < $noOfRows; ++$index) { + $blockid = $adb->query_result($res,$index,'blockid'); + if(in_array($blockid, $this->module_list[$module])) continue; + $blockid_list[] = $blockid; + $blocklabel = $adb->query_result($res,$index,'blocklabel'); + $this->module_list[$module][$blocklabel] = $blockid; + } + } + + // Initializes the module list for listing columns for report creation. + function initListOfModules() { + global $adb, $current_user, $old_related_modules; + + $restricted_modules = array('Emails','Events','Webmails'); + $restricted_blocks = array('LBL_IMAGE_INFORMATION','LBL_COMMENTS','LBL_COMMENT_INFORMATION'); + + $this->module_id = array(); + $this->module_list = array(); + + // Prefetch module info to check active or not and also get list of tabs + $modulerows = vtlib_prefetchModuleActiveInfo(false); + + $cachedInfo = VTCacheUtils::lookupReport_ListofModuleInfos(); + + if($cachedInfo !== false) { + $this->module_list = $cachedInfo['module_list']; + $this->related_modules = $cachedInfo['related_modules']; + + } else { + + if($modulerows) { + foreach($modulerows as $resultrow) { + if($resultrow['presence'] == '1') continue; // skip disabled modules + if($resultrow['isentitytype'] != '1') continue; // skip extension modules + if(in_array($resultrow['name'], $restricted_modules)) { // skip restricted modules + continue; + } + if($resultrow['name']!='Calendar'){ + $this->module_id[$resultrow['tabid']] = $resultrow['name']; + } else { + $this->module_id[9] = $resultrow['name']; + $this->module_id[16] = $resultrow['name']; + + } + $this->module_list[$resultrow['name']] = array(); + } + + $moduleids = array_keys($this->module_id); + $reportblocks = + $adb->pquery("SELECT blockid, blocklabel, tabid FROM vtiger_blocks WHERE tabid IN (" .generateQuestionMarks($moduleids) .")", + array($moduleids)); + $prev_block_label = ''; + if($adb->num_rows($reportblocks)) { + while($resultrow = $adb->fetch_array($reportblocks)) { + $blockid = $resultrow['blockid']; + $blocklabel = $resultrow['blocklabel']; + $module = $this->module_id[$resultrow['tabid']]; + + if(in_array($blocklabel, $restricted_blocks) || + in_array($blockid, $this->module_list[$module]) || + isset($this->module_list[$module][getTranslatedString($blocklabel,$module)]) + ) { + continue; + } + + if(!empty($blocklabel)){ + if($module == 'Calendar' && $blocklabel == 'LBL_CUSTOM_INFORMATION') + $this->module_list[$module][$blockid] = getTranslatedString($blocklabel,$module); + else + $this->module_list[$module][$blockid] = getTranslatedString($blocklabel,$module); + $prev_block_label = $blocklabel; + } else { + $this->module_list[$module][$blockid] = getTranslatedString($prev_block_label,$module); + } + } + } + + $relatedmodules = $adb->pquery( + "SELECT vtiger_tab.name, vtiger_relatedlists.tabid FROM vtiger_tab + INNER JOIN vtiger_relatedlists on vtiger_tab.tabid=vtiger_relatedlists.related_tabid + WHERE vtiger_tab.isentitytype=1 + AND vtiger_tab.name NOT IN(".generateQuestionMarks($restricted_modules).") + AND vtiger_tab.presence=0 AND vtiger_relatedlists.label!='Activity History'", + array($restricted_modules) + ); + if($adb->num_rows($relatedmodules)) { + while($resultrow = $adb->fetch_array($relatedmodules)) { + $module = $this->module_id[$resultrow['tabid']]; + + if(!isset($this->related_modules[$module])) { + $this->related_modules[$module] = array(); + } + + if($module != $resultrow['name']) { + $this->related_modules[$module][] = $resultrow['name']; + } + + // To achieve Backward Compatability with Report relations + if(isset($old_related_modules[$module])){ + + $rel_mod = array(); + foreach($old_related_modules[$module] as $key=>$name){ + if(vtlib_isModuleActive($name) && isPermitted($name,'index','')){ + $rel_mod[] = $name; + } + } + if(!empty($rel_mod)){ + $this->related_modules[$module] = array_merge($this->related_modules[$module],$rel_mod); + $this->related_modules[$module] = array_unique($this->related_modules[$module]); + } + } + } + } + // Put the information in cache for re-use + VTCacheUtils::updateReport_ListofModuleInfos($this->module_list, $this->related_modules); + } + } + } + // END + + + /** Function to get the Listview of Reports + * This function accepts no argument + * This generate the Reports view page and returns a string + * contains HTML + */ + + function sgetRptFldr($mode='') + { + + global $adb,$log,$mod_strings; + $returndata = Array(); + $sql = "select * from vtiger_reportfolder order by folderid"; + $result = $adb->pquery($sql, array()); + $reportfldrow = $adb->fetch_array($result); + if($mode != '') + { + // Fetch detials of all reports of folder at once + $reportsInAllFolders = $this->sgetRptsforFldr(false); + + do + { + if($reportfldrow["state"] == $mode) + { + $details = Array(); + $details['state'] = $reportfldrow["state"]; + $details['id'] = $reportfldrow["folderid"]; + $details['name'] = ($mod_strings[$reportfldrow["foldername"]] == '' ) ? $reportfldrow["foldername"]:$mod_strings[$reportfldrow["foldername"]]; + $details['description'] = $reportfldrow["description"]; + $details['fname'] = popup_decode_html($details['name']); + $details['fdescription'] = popup_decode_html($reportfldrow["description"]); + $details['details'] = $reportsInAllFolders[$reportfldrow["folderid"]]; + $returndata[] = $details; + } + }while($reportfldrow = $adb->fetch_array($result)); + }else + { + do + { + $details = Array(); + $details['state'] = $reportfldrow["state"]; + $details['id'] = $reportfldrow["folderid"]; + $details['name'] = ($mod_strings[$reportfldrow["foldername"]] == '' ) ? $reportfldrow["foldername"]:$mod_strings[$reportfldrow["foldername"]]; + $details['description'] = $reportfldrow["description"]; + $details['fname'] = popup_decode_html($details['name']); + $details['fdescription'] = popup_decode_html($reportfldrow["description"]); + $returndata[] = $details; + }while($reportfldrow = $adb->fetch_array($result)); + } + + $log->info("Reports :: ListView->Successfully returned vtiger_report folder HTML"); + return $returndata; + } + + /** Function to get the Reports inside each modules + * This function accepts the folderid + * This Generates the Reports under each Reports module + * This Returns a HTML sring + */ + + function sgetRptsforFldr($rpt_fldr_id) + { + $srptdetails=""; + global $adb; + global $log; + global $mod_strings,$current_user; + $returndata = Array(); + + require_once('include/utils/UserInfoUtil.php'); + + $sql = "select vtiger_report.*, vtiger_reportmodules.*, vtiger_reportfolder.folderid from vtiger_report inner join vtiger_reportfolder on vtiger_reportfolder.folderid = vtiger_report.folderid"; + $sql .= " inner join vtiger_reportmodules on vtiger_reportmodules.reportmodulesid = vtiger_report.reportid"; + + $params = array(); + + // If information is required only for specific report folder? + if($rpt_fldr_id !== false) { + $sql .= " where vtiger_reportfolder.folderid=?"; + $params[] = $rpt_fldr_id; + } + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + require_once('include/utils/GetUserGroups.php'); + $userGroups = new GetUserGroups(); + $userGroups->getAllUserGroups($current_user->id); + $user_groups = $userGroups->user_groups; + if(!empty($user_groups) && $is_admin==false){ + $user_group_query = " (shareid IN (".generateQuestionMarks($user_groups).") AND setype='groups') OR"; + array_push($params, $user_groups); + } + + $non_admin_query = " vtiger_report.reportid IN (SELECT reportid from vtiger_reportsharing WHERE $user_group_query (shareid=? AND setype='users'))"; + if($is_admin==false){ + $sql .= " and ( (".$non_admin_query.") or vtiger_report.sharingtype='Public' or vtiger_report.owner = ? or vtiger_report.owner 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."::%'))"; + array_push($params, $current_user->id); + array_push($params, $current_user->id); + } + $query = $adb->pquery("select 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."::%'",array()); + $subordinate_users = Array(); + for($i=0;$i<$adb->num_rows($query);$i++){ + $subordinate_users[] = $adb->query_result($query,$i,'userid'); + } + $result = $adb->pquery($sql, $params); + + $report = $adb->fetch_array($result); + if(count($report)>0) + { + do + { + $report_details = Array(); + $report_details ['customizable'] = $report["customizable"]; + $report_details ['reportid'] = $report["reportid"]; + $report_details ['primarymodule'] = $report["primarymodule"]; + $report_details ['secondarymodules'] = $report["secondarymodules"]; + $report_details ['state'] = $report["state"]; + $report_details ['description'] = $report["description"]; + $report_details ['reportname'] = $report["reportname"]; + $report_details ['sharingtype'] = $report["sharingtype"]; + if($is_admin==true || in_array($report["owner"],$subordinate_users) || $report["owner"]==$current_user->id) + $report_details ['editable'] = 'true'; + else + $report_details['editable'] = 'false'; + + if(isPermitted($report["primarymodule"],'index') == "yes") + $returndata [$report["folderid"]][] = $report_details; + }while($report = $adb->fetch_array($result)); + } + + if($rpt_fldr_id !== false) { + $returndata = $returndata[$rpt_fldr_id]; + } + + $log->info("Reports :: ListView->Successfully returned vtiger_report details HTML"); + return $returndata; + } + + /** Function to get the array of ids + * This function forms the array for the ExpandCollapse + * Javascript + * It returns the array of ids + * Array('1RptFldr','2RptFldr',........,'9RptFldr','10RptFldr') + */ + + function sgetJsRptFldr() + { + $srptfldr_js = "var ReportListArray=new Array(".$this->srptfldridjs.") + setExpandCollapse()"; + return $srptfldr_js; + } + + /** Function to set the Primary module vtiger_fields for the given Report + * This function sets the primary module columns for the given Report + * It accepts the Primary module as the argument and set the vtiger_fields of the module + * to the varialbe pri_module_columnslist and returns true if sucess + */ + + function getPriModuleColumnsList($module) + { + //$this->updateModuleList($module); + foreach($this->module_list[$module] as $key=>$value) + { + $temp = $this->getColumnsListbyBlock($module,$key); + if(!empty($ret_module_list[$module][$value])){ + if(!empty($temp)){ + $ret_module_list[$module][$value] = array_merge($ret_module_list[$module][$value],$temp); + } + } else { + $ret_module_list[$module][$value] = $this->getColumnsListbyBlock($module,$key); + } + } + $this->pri_module_columnslist = $ret_module_list; + return true; + } + + /** Function to set the Secondary module fileds for the given Report + * This function sets the secondary module columns for the given module + * It accepts the module as the argument and set the vtiger_fields of the module + * to the varialbe sec_module_columnslist and returns true if sucess + */ + + function getSecModuleColumnsList($module) + { + if($module != "") + { + $secmodule = explode(":",$module); + for($i=0;$i < count($secmodule) ;$i++) + { + //$this->updateModuleList($secmodule[$i]); + if($this->module_list[$secmodule[$i]]){ + foreach($this->module_list[$secmodule[$i]] as $key=>$value) + { + $temp = $this->getColumnsListbyBlock($secmodule[$i],$key); + if(!empty($ret_module_list[$secmodule[$i]][$value])){ + if(!empty($temp)){ + $ret_module_list[$secmodule[$i]][$value] = array_merge($ret_module_list[$secmodule[$i]][$value],$temp); + } + } else { + $ret_module_list[$secmodule[$i]][$value] = $this->getColumnsListbyBlock($secmodule[$i],$key); + } + } + $this->sec_module_columnslist[$secmodule[$i]] = $ret_module_list[$secmodule[$i]]; + } + } + } + return true; + } + + /** Function to get vtiger_fields for the given module and block + * This function gets the vtiger_fields for the given module + * It accepts the module and the block as arguments and + * returns the array column lists + * Array module_columnlist[ vtiger_fieldtablename:fieldcolname:module_fieldlabel1:fieldname:fieldtypeofdata]=fieldlabel + */ + + function getColumnsListbyBlock($module,$block) + { + global $adb; + global $log; + global $current_user; + + if(is_string($block)) $block = explode(",", $block); + + $tabid = getTabid($module); + if ($module == 'Calendar') { + $tabid = array('9','16'); + } + $params = array($tabid, $block); + + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + //Security Check + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0) + { + $sql = "select * from vtiger_field where vtiger_field.tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.block in (". generateQuestionMarks($block) .") and vtiger_field.displaytype in (1,2,3) and vtiger_field.presence in (0,2) "; + + //fix for Ticket #4016 + if($module == "Calendar") + $sql.=" group by vtiger_field.fieldlabel order by sequence"; + else + $sql.=" order by sequence"; + } + else + { + + $profileList = getCurrentUserProfileList(); + $sql = "select * from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.block in (". generateQuestionMarks($block) .") and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + if (count($profileList) > 0) { + $sql .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + + //fix for Ticket #4016 + if($module == "Calendar") + $sql.=" group by vtiger_field.fieldid,vtiger_field.fieldlabel order by sequence"; + else + $sql.=" group by vtiger_field.fieldid order by sequence"; + } + + $result = $adb->pquery($sql, $params); + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $fieldtablename = $adb->query_result($result,$i,"tablename"); + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $fieldname = $adb->query_result($result,$i,"fieldname"); + $fieldtype = $adb->query_result($result,$i,"typeofdata"); + $uitype = $adb->query_result($result,$i,"uitype"); + $fieldtype = explode("~",$fieldtype); + $fieldtypeofdata = $fieldtype[0]; + + //Here we Changing the displaytype of the field. So that its criteria will be displayed correctly in Reports Advance Filter. + $fieldtypeofdata=ChangeTypeOfData_Filter($fieldtablename,$fieldcolname,$fieldtypeofdata); + + if($uitype == 68 || $uitype == 59) + { + $fieldtypeofdata = 'V'; + } + if($fieldtablename == "vtiger_crmentity") + { + $fieldtablename = $fieldtablename.$module; + } + if($fieldname == "assigned_user_id") + { + $fieldtablename = "vtiger_users".$module; + $fieldcolname = "user_name"; + } + if($fieldname == "account_id") + { + $fieldtablename = "vtiger_account".$module; + $fieldcolname = "accountname"; + } + if($fieldname == "contact_id") + { + $fieldtablename = "vtiger_contactdetails".$module; + $fieldcolname = "lastname"; + } + if($fieldname == "parent_id") + { + $fieldtablename = "vtiger_crmentityRel".$module; + $fieldcolname = "setype"; + } + if($fieldname == "vendor_id") + { + $fieldtablename = "vtiger_vendorRel".$module; + $fieldcolname = "vendorname"; + } + if($fieldname == "potential_id") + { + $fieldtablename = "vtiger_potentialRel".$module; + $fieldcolname = "potentialname"; + } + if($fieldname == "assigned_user_id1") + { + $fieldtablename = "vtiger_usersRel1"; + $fieldcolname = "user_name"; + } + if($fieldname == 'quote_id') + { + $fieldtablename = "vtiger_quotes".$module; + $fieldcolname = "subject"; + } + + $product_id_tables = array( + "vtiger_troubletickets"=>"vtiger_productsRel", + "vtiger_campaign"=>"vtiger_productsCampaigns", + "vtiger_faq"=>"vtiger_productsFaq", + ); + if($fieldname == 'product_id' && isset($product_id_tables[$fieldtablename])) + { + $fieldtablename = $product_id_tables[$fieldtablename]; + $fieldcolname = "productname"; + } + if($fieldname == 'campaignid' && $module=='Potentials') + { + $fieldtablename = "vtiger_campaign".$module; + $fieldcolname = "campaignname"; + } + if($fieldname == 'currency_id' && $fieldtablename=='vtiger_pricebook') + { + $fieldtablename = "vtiger_currency_info".$module; + $fieldcolname = "currency_name"; + } + + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $fieldlabel1 = str_replace(" ","_",$fieldlabel); + $optionvalue = $fieldtablename.":".$fieldcolname.":".$module."_".$fieldlabel1.":".$fieldname.":".$fieldtypeofdata; + $this->adv_rel_fields[$fieldtypeofdata][] = '$'.$module.'#'.$fieldname.'$'."::".getTranslatedString($module,$module)." ".$fieldlabel; + //added to escape attachments fields in Reports as we have multiple attachments + if($module != 'HelpDesk' || $fieldname !='filename') + $module_columnlist[$optionvalue] = $fieldlabel; + } + $log->info("Reports :: FieldColumns->Successfully returned ColumnslistbyBlock".$module.$block); + return $module_columnlist; + } + + /** Function to set the standard filter vtiger_fields for the given vtiger_report + * This function gets the standard filter vtiger_fields for the given vtiger_report + * and set the values to the corresponding variables + * It accepts the repordid as argument + */ + + function getSelectedStandardCriteria($reportid) + { + global $adb; + $sSQL = "select vtiger_reportdatefilter.* from vtiger_reportdatefilter inner join vtiger_report on vtiger_report.reportid = vtiger_reportdatefilter.datefilterid where vtiger_report.reportid=?"; + $result = $adb->pquery($sSQL, array($reportid)); + $selectedstdfilter = $adb->fetch_array($result); + + $this->stdselectedcolumn = $selectedstdfilter["datecolumnname"]; + $this->stdselectedfilter = $selectedstdfilter["datefilter"]; + + if($selectedstdfilter["datefilter"] == "custom") + { + if($selectedstdfilter["startdate"] != "0000-00-00") + { + $this->startdate = $selectedstdfilter["startdate"]; + } + if($selectedstdfilter["enddate"] != "0000-00-00") + { + $this->enddate = $selectedstdfilter["enddate"]; + } + } + } + + /** Function to get the combo values for the standard filter + * This function get the combo values for the standard filter for the given vtiger_report + * and return a HTML string + */ + + function getSelectedStdFilterCriteria($selecteddatefilter = "") + { + global $mod_strings; + + $datefiltervalue = Array("custom","prevfy","thisfy","nextfy","prevfq","thisfq","nextfq", + "yesterday","today","tomorrow","lastweek","thisweek","nextweek","lastmonth","thismonth", + "nextmonth","last7days","last30days", "last60days","last90days","last120days", + "next30days","next60days","next90days","next120days" + ); + + $datefilterdisplay = Array("Custom","Previous FY", "Current FY","Next FY","Previous FQ","Current FQ","Next FQ","Yesterday", + "Today","Tomorrow","Last Week","Current Week","Next Week","Last Month","Current Month", + "Next Month","Last 7 Days","Last 30 Days","Last 60 Days","Last 90 Days","Last 120 Days", + "Next 7 Days","Next 30 Days","Next 60 Days","Next 90 Days","Next 120 Days" + ); + + for($i=0;$i".$mod_strings[$datefilterdisplay[$i]].""; + }else + { + $sshtml .= ""; + } + } + + return $sshtml; + } + + /** Function to get the selected standard filter columns + * This function returns the selected standard filter criteria + * which is selected for vtiger_reports as an array + * Array stdcriteria_list[fieldtablename:fieldcolname:module_fieldlabel1]=fieldlabel + */ + + function getStdCriteriaByModule($module) + { + global $adb; + global $log; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $tabid = getTabid($module); + foreach($this->module_list[$module] as $key=>$blockid) + { + $blockids[] = $blockid; + } + $blockids = implode(",",$blockids); + + $params = array($tabid, $blockids); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] == 0) + { + //uitype 6 and 23 added for start_date,EndDate,Expected Close Date + $sql = "select * from vtiger_field where vtiger_field.tabid=? and (vtiger_field.uitype =5 or vtiger_field.uitype = 6 or vtiger_field.uitype = 23 or vtiger_field.displaytype=2) and vtiger_field.block in (". generateQuestionMarks($block) .") and vtiger_field.presence in (0,2) order by vtiger_field.sequence"; + } + else + { + $profileList = getCurrentUserProfileList(); + $sql = "select * from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where vtiger_field.tabid=? and (vtiger_field.uitype =5 or vtiger_field.displaytype=2) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.block in (". generateQuestionMarks($block) .") and vtiger_field.presence in (0,2)"; + if (count($profileList) > 0) { + $sql .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + $sql .= " order by vtiger_field.sequence"; + } + + $result = $adb->pquery($sql, $params); + + while($criteriatyperow = $adb->fetch_array($result)) + { + $fieldtablename = $criteriatyperow["tablename"]; + $fieldcolname = $criteriatyperow["columnname"]; + $fieldlabel = $criteriatyperow["fieldlabel"]; + + if($fieldtablename == "vtiger_crmentity") + { + $fieldtablename = $fieldtablename.$module; + } + $fieldlabel1 = str_replace(" ","_",$fieldlabel); + $optionvalue = $fieldtablename.":".$fieldcolname.":".$module."_".$fieldlabel1; + $stdcriteria_list[$optionvalue] = $fieldlabel; + } + + $log->info("Reports :: StdfilterColumns->Successfully returned Stdfilter for".$module); + return $stdcriteria_list; + + } + + /** Function to form a javascript to determine the start date and end date for a standard filter + * This function is to form a javascript to determine + * the start date and End date from the value selected in the combo lists + */ + + function getCriteriaJS() + { + $today = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d"), date("Y"))); + $tomorrow = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); + $yesterday = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-1, date("Y"))); + + $currentmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m"), "01", date("Y"))); + $currentmonth1 = date("Y-m-t"); + $lastmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")-1, "01", date("Y"))); + $lastmonth1 = date("Y-m-t", strtotime("-1 Month")); + $nextmonth0 = date("Y-m-d",mktime(0, 0, 0, date("m")+1, "01", date("Y"))); + $nextmonth1 = date("Y-m-t", strtotime("+1 Month")); + + $lastweek0 = date("Y-m-d",strtotime("-2 week Sunday")); + $lastweek1 = date("Y-m-d",strtotime("-1 week Saturday")); + + $thisweek0 = date("Y-m-d",strtotime("-1 week Sunday")); + $thisweek1 = date("Y-m-d",strtotime("this Saturday")); + + $nextweek0 = date("Y-m-d",strtotime("this Sunday")); + $nextweek1 = date("Y-m-d",strtotime("+1 week Saturday")); + + $next7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+6, date("Y"))); + $next30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+29, date("Y"))); + $next60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+59, date("Y"))); + $next90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+89, date("Y"))); + $next120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")+119, date("Y"))); + + $last7days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-6, date("Y"))); + $last30days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-29, date("Y"))); + $last60days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-59, date("Y"))); + $last90days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-89, date("Y"))); + $last120days = date("Y-m-d",mktime(0, 0, 0, date("m") , date("d")-119, date("Y"))); + + $currentFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y"))); + $currentFY1 = date("Y-m-t",mktime(0, 0, 0, "12", date("d"), date("Y"))); + $lastFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")-1)); + $lastFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")-1)); + $nextFY0 = date("Y-m-d",mktime(0, 0, 0, "01", "01", date("Y")+1)); + $nextFY1 = date("Y-m-t", mktime(0, 0, 0, "12", date("d"), date("Y")+1)); + + if(date("m") <= 3) + { + $cFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y")-1)); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y")-1)); + }else if(date("m") > 3 and date("m") <= 6) + { + $pFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $nFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + + }else if(date("m") > 6 and date("m") <= 9) + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y"))); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + $pFq = date("Y-m-d",mktime(0, 0, 0, "04","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "06","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + } + else if(date("m") > 9 and date("m") <= 12) + { + $nFq = date("Y-m-d",mktime(0, 0, 0, "01","01",date("Y")+1)); + $nFq1 = date("Y-m-d",mktime(0, 0, 0, "03","31",date("Y")+1)); + $pFq = date("Y-m-d",mktime(0, 0, 0, "07","01",date("Y"))); + $pFq1 = date("Y-m-d",mktime(0, 0, 0, "09","30",date("Y"))); + $cFq = date("Y-m-d",mktime(0, 0, 0, "10","01",date("Y"))); + $cFq1 = date("Y-m-d",mktime(0, 0, 0, "12","31",date("Y"))); + + } + + $sjsStr = ''; + + return $sjsStr; + } +function getEscapedColumns($selectedfields) + { + $fieldname = $selectedfields[3]; + if($fieldname == "parent_id") + { + if($this->primarymodule == "HelpDesk" && $selectedfields[0] == "vtiger_crmentityRelHelpDesk") + { + $querycolumn = "case vtiger_crmentityRelHelpDesk.setype when 'Accounts' then vtiger_accountRelHelpDesk.accountname when 'Contacts' then vtiger_contactdetailsRelHelpDesk.lastname End"." '".$selectedfields[2]."', vtiger_crmentityRelHelpDesk.setype 'Entity_type'"; + return $querycolumn; + } + if($this->primarymodule == "Products" || $this->secondarymodule == "Products") + { + $querycolumn = "case vtiger_crmentityRelProducts.setype when 'Accounts' then vtiger_accountRelProducts.accountname when 'Leads' then vtiger_leaddetailsRelProducts.lastname when 'Potentials' then vtiger_potentialRelProducts.potentialname End"." '".$selectedfields[2]."', vtiger_crmentityRelProducts.setype 'Entity_type'"; + } + if($this->primarymodule == "Calendar" || $this->secondarymodule == "Calendar") + { + $querycolumn = "case vtiger_crmentityRelCalendar.setype when 'Accounts' then vtiger_accountRelCalendar.accountname when 'Leads' then vtiger_leaddetailsRelCalendar.lastname when 'Potentials' then vtiger_potentialRelCalendar.potentialname when 'Quotes' then vtiger_quotesRelCalendar.subject when 'PurchaseOrder' then vtiger_purchaseorderRelCalendar.subject when 'Invoice' then vtiger_invoiceRelCalendar.subject End"." '".$selectedfields[2]."', vtiger_crmentityRelCalendar.setype 'Entity_type'"; + } + } + return $querycolumn; + } + function getaccesfield($module) + { + global $current_user; + global $adb; + $access_fields = Array(); + + $profileList = getCurrentUserProfileList(); + $query = "select vtiger_field.fieldname from vtiger_field inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid where"; + $params = array(); + if($module == "Calendar") + { + $query .= " vtiger_field.tabid in (9,16) and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + if (count($profileList) > 0) { + $query .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + $query .= " group by vtiger_field.fieldid order by block,sequence"; + } + else + { + array_push($params, $this->primodule, $this->secmodule); + $query .= " vtiger_field.tabid in (select tabid from vtiger_tab where vtiger_tab.name in (?,?)) and vtiger_field.displaytype in (1,2,3) and vtiger_profile2field.visible=0 and vtiger_def_org_field.visible=0 and vtiger_field.presence in (0,2)"; + if (count($profileList) > 0) { + $query .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($params, $profileList); + } + $query .= " group by vtiger_field.fieldid order by block,sequence"; + } + $result = $adb->pquery($query, $params); + + + while($collistrow = $adb->fetch_array($result)) + { + $access_fields[] = $collistrow["fieldname"]; + } + return $access_fields; + } + + /** Function to set the order of grouping and to find the columns responsible + * to the grouping + * This function accepts the vtiger_reportid as variable,sets the variable ascdescorder[] to the sort order and + * returns the array array_list which has the column responsible for the grouping + * Array array_list[0]=columnname + */ + + + function getSelctedSortingColumns($reportid) + { + + global $adb; + global $log; + + $sreportsortsql = "select vtiger_reportsortcol.* from vtiger_report"; + $sreportsortsql .= " inner join vtiger_reportsortcol on vtiger_report.reportid = vtiger_reportsortcol.reportid"; + $sreportsortsql .= " where vtiger_report.reportid =? order by vtiger_reportsortcol.sortcolid"; + + $result = $adb->pquery($sreportsortsql, array($reportid)); + $noofrows = $adb->num_rows($result); + + for($i=0; $i<$noofrows; $i++) + { + $fieldcolname = $adb->query_result($result,$i,"columnname"); + $sort_values = $adb->query_result($result,$i,"sortorder"); + $this->ascdescorder[] = $sort_values; + $array_list[] = $fieldcolname; + } + + $log->info("Reports :: Successfully returned getSelctedSortingColumns"); + return $array_list; + } + + /** Function to get the selected columns list for a selected vtiger_report + * This function accepts the vtiger_reportid as the argument and get the selected columns + * for the given vtiger_reportid and it forms a combo lists and returns + * HTML of the combo values + */ + + function getSelectedColumnsList($reportid) + { + global $adb; + global $modules; + global $log,$current_user; + + $ssql = "select vtiger_selectcolumn.* from vtiger_report inner join vtiger_selectquery on vtiger_selectquery.queryid = vtiger_report.queryid"; + $ssql .= " left join vtiger_selectcolumn on vtiger_selectcolumn.queryid = vtiger_selectquery.queryid"; + $ssql .= " where vtiger_report.reportid = ?"; + $ssql .= " order by vtiger_selectcolumn.columnindex"; + $result = $adb->pquery($ssql, array($reportid)); + $permitted_fields = Array(); + + $selected_mod = split(":",$this->secmodule); + array_push($selected_mod,$this->primodule); + + while($columnslistrow = $adb->fetch_array($result)) + { + $fieldname =""; + $fieldcolname = $columnslistrow["columnname"]; + + $selmod_field_disabled = true; + foreach($selected_mod as $smod){ + if((stripos($fieldcolname,":".$smod."_")>-1) && vtlib_isModuleActive($smod)){ + $selmod_field_disabled = false; + break; + } + } + if($selmod_field_disabled==false){ + list($tablename,$colname,$module_field,$fieldname,$single) = split(":",$fieldcolname); + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + list($module,$field) = split("_",$module_field); + if(sizeof($permitted_fields) == 0 && $is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1) + { + $permitted_fields = $this->getaccesfield($module); + } + $querycolumns = $this->getEscapedColumns($selectedfields); + $fieldlabel = trim(str_replace($module," ",$module_field)); + $mod_arr=explode('_',$fieldlabel); + $mod = ($mod_arr[0] == '')?$module:$mod_arr[0]; + $fieldlabel = trim(str_replace("_"," ",$fieldlabel)); + //modified code to support i18n issue + $mod_lbl = getTranslatedString($mod,$module); //module + $fld_lbl = getTranslatedString($fieldlabel,$module); //fieldlabel + $fieldlabel = $mod_lbl." ".$fld_lbl; + if(CheckFieldPermission($fieldname,$mod) != 'true' && $colname!="crmid") + { + $shtml .= ""; + } + else + { + $shtml .= ""; + } + } + //end + } + $log->info("ReportRun :: Successfully returned getQueryColumnsList".$reportid); + return $shtml; + } + function getAdvancedFilterList($reportid) + { + global $adb; + global $modules; + global $log; + $ssql = 'select vtiger_relcriteria.* from vtiger_report inner join vtiger_relcriteria on vtiger_relcriteria.queryid = vtiger_report.queryid left join vtiger_selectquery on vtiger_relcriteria.queryid = vtiger_selectquery.queryid'; + $ssql.= " where vtiger_report.reportid = ? order by vtiger_relcriteria.columnindex"; + + $result = $adb->pquery($ssql, array($reportid)); + + while($relcriteriarow = $adb->fetch_array($result)) + { + $this->advft_column[] = $relcriteriarow["columnname"]; + $this->advft_option[] = $relcriteriarow["comparator"]; + $advfilterval = $relcriteriarow["value"]; + $col = explode(":",$relcriteriarow["columnname"]); + $temp_val = explode(",",$relcriteriarow["value"]); + if($col[4] == 'D' || ($col[4] == 'T' && $col[1] != 'time_start' && $col[1] != 'time_end') || ($col[4] == 'DT')) + { + $val = Array(); + for($x=0;$xadvft_value[] = $advfilterval; + } + $log->info("Reports :: Successfully returned getAdvancedFilterList"); + return true; + } + //<<<<<<<>>>>>>>>>>>>> + + /** Function to get the list of vtiger_report folders when Save and run the vtiger_report + * This function gets the vtiger_report folders from database and form + * a combo values of the folders and return + * HTML of the combo values + */ + + function sgetRptFldrSaveReport() + { + global $adb; + global $log; + + $sql = "select * from vtiger_reportfolder order by folderid"; + $result = $adb->pquery($sql, array()); + $reportfldrow = $adb->fetch_array($result); + $x = 0; + do + { + $shtml .= ""; + }while($reportfldrow = $adb->fetch_array($result)); + + $log->info("Reports :: Successfully returned sgetRptFldrSaveReport"); + return $shtml; + } + + /** Function to get the column to total vtiger_fields in Reports + * This function gets columns to total vtiger_field + * and generated the html for that vtiger_fields + * It returns the HTML of the vtiger_fields along with the check boxes + */ + + function sgetColumntoTotal($primarymodule,$secondarymodule) + { + $options = Array(); + $options []= $this->sgetColumnstoTotalHTML($primarymodule,0); + if(!empty($secondarymodule)) + { + //$secondarymodule = explode(":",$secondarymodule); + for($i=0;$i < count($secondarymodule) ;$i++) + { + $options []= $this->sgetColumnstoTotalHTML($secondarymodule[$i],($i+1)); + } + } + return $options; + } + + /** Function to get the selected columns of total vtiger_fields in Reports + * This function gets selected columns of total vtiger_field + * and generated the html for that vtiger_fields + * It returns the HTML of the vtiger_fields along with the check boxes + */ + + + function sgetColumntoTotalSelected($primarymodule,$secondarymodule,$reportid) + { + global $adb; + global $log; + $options = Array(); + if($reportid != "") + { + $ssql = "select vtiger_reportsummary.* from vtiger_reportsummary inner join vtiger_report on vtiger_report.reportid = vtiger_reportsummary.reportsummaryid where vtiger_report.reportid=?"; + $result = $adb->pquery($ssql, array($reportid)); + if($result) + { + $reportsummaryrow = $adb->fetch_array($result); + + do + { + $this->columnssummary[] = $reportsummaryrow["columnname"]; + + }while($reportsummaryrow = $adb->fetch_array($result)); + } + } + $options []= $this->sgetColumnstoTotalHTML($primarymodule,0); + if($secondarymodule != "") + { + $secondarymodule = explode(":",$secondarymodule); + for($i=0;$i < count($secondarymodule) ;$i++) + { + $options []= $this->sgetColumnstoTotalHTML($secondarymodule[$i],($i+1)); + } + } + + $log->info("Reports :: Successfully returned sgetColumntoTotalSelected"); + return $options; + + } + + /** Function to form the HTML for columns to total + * This function formulates the HTML format of the + * vtiger_fields along with four checkboxes + * It returns the HTML of the vtiger_fields along with the check boxes + */ + + + function sgetColumnstoTotalHTML($module) + { + //retreive the vtiger_tabid + global $adb; + global $log; + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + $tabid = getTabid($module); + $escapedchars = Array('_SUM','_AVG','_MIN','_MAX'); + $sparams = array($tabid); + if($is_admin == true || $profileGlobalPermission[1] == 0 || $profileGlobalPermission[2] ==0) + { + $ssql = "select * from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid where vtiger_field.uitype != 50 and vtiger_field.tabid=? and vtiger_field.displaytype in (1,2,3) and vtiger_field.presence in (0,2) "; + } + else + { + $profileList = getCurrentUserProfileList(); + $ssql = "select * from vtiger_field inner join vtiger_tab on vtiger_tab.tabid = vtiger_field.tabid inner join vtiger_def_org_field on vtiger_def_org_field.fieldid=vtiger_field.fieldid inner join vtiger_profile2field on vtiger_profile2field.fieldid=vtiger_field.fieldid where vtiger_field.uitype != 50 and vtiger_field.tabid=? and vtiger_field.displaytype in (1,2,3) and vtiger_def_org_field.visible=0 and vtiger_profile2field.visible=0 and vtiger_field.presence in (0,2)"; + if (count($profileList) > 0) { + $ssql .= " and vtiger_profile2field.profileid in (". generateQuestionMarks($profileList) .")"; + array_push($sparams, $profileList); + } + } + + //Added to avoid display the Related fields (Account name,Vandor name,product name, etc) in Report Calculations(SUM,AVG..) + switch($tabid) + { + case 2://Potentials + //ie. Campaign name will not displayed in Potential's report calcullation + $ssql.= " and vtiger_field.fieldname not in ('campaignid')"; + break; + case 4://Contacts + $ssql.= " and vtiger_field.fieldname not in ('account_id')"; + break; + case 6://Accounts + $ssql.= " and vtiger_field.fieldname not in ('account_id')"; + break; + case 9://Calandar + $ssql.= " and vtiger_field.fieldname not in ('parent_id','contact_id')"; + break; + case 13://Trouble tickets(HelpDesk) + $ssql.= " and vtiger_field.fieldname not in ('parent_id','product_id')"; + break; + case 14://Products + $ssql.= " and vtiger_field.fieldname not in ('vendor_id','product_id')"; + break; + case 20://Quotes + $ssql.= " and vtiger_field.fieldname not in ('potential_id','assigned_user_id1','account_id')"; + break; + case 21://Purchase Order + $ssql.= " and vtiger_field.fieldname not in ('contact_id','vendor_id')"; + break; + case 22://SalesOrder + $ssql.= " and vtiger_field.fieldname not in ('potential_id','account_id','contact_id','quote_id')"; + break; + case 23://Invoice + $ssql.= " and vtiger_field.fieldname not in ('salesorder_id','contact_id','account_id')"; + break; + case 26://Campaings + $ssql.= " and vtiger_field.fieldname not in ('product_id')"; + break; + + } + + $ssql.= " order by sequence"; + + $result = $adb->pquery($ssql, $sparams); + $columntototalrow = $adb->fetch_array($result); + $options_list = Array(); + do + { + $typeofdata = explode("~",$columntototalrow["typeofdata"]); + + if($typeofdata[0] == "N" || $typeofdata[0] == "I") + { + $options = Array(); + if(isset($this->columnssummary)) + { + $selectedcolumn = ""; + $selectedcolumn1 = ""; + + for($i=0;$i < count($this->columnssummary) ;$i++) + { + $selectedcolumnarray = explode(":",$this->columnssummary[$i]); + $selectedcolumn = $selectedcolumnarray[1].":".$selectedcolumnarray[2].":". + str_replace($escapedchars,"",$selectedcolumnarray[3]); + + if ($selectedcolumn != $columntototalrow['tablename'].':'.$columntototalrow['columnname'].':'.str_replace(" ","_",$columntototalrow['fieldlabel'])) + { + $selectedcolumn = ""; + }else + { + $selectedcolumn1[$selectedcolumnarray[4]] = $this->columnssummary[$i]; + } + + } + if(isset($_REQUEST["record"]) && $_REQUEST["record"] != '') + { + $options['label'][] = getTranslatedString($columntototalrow['tablabel'],$columntototalrow['tablabel']).' -'.getTranslatedString($columntototalrow['fieldlabel'],$columntototalrow['tablabel']); + } + + $columntototalrow['fieldlabel'] = str_replace(" ","_",$columntototalrow['fieldlabel']); + $options []= getTranslatedString($columntototalrow['tablabel'],$columntototalrow['tablabel']).' - '.getTranslatedString($columntototalrow['fieldlabel'],$columntototalrow['tablabel']); + if($selectedcolumn1[2] == "cb:".$columntototalrow['tablename'].':'.$columntototalrow['columnname'].':'.$columntototalrow['fieldlabel']."_SUM:2") + { + $options []= ''; + }else + { + $options []= ''; + } + if($selectedcolumn1[3] == "cb:".$columntototalrow['tablename'].':'.$columntototalrow['columnname'].':'.$columntototalrow['fieldlabel']."_AVG:3") + { + $options []= ''; + }else + { + $options []= ''; + } + + if($selectedcolumn1[4] == "cb:".$columntototalrow['tablename'].':'.$columntototalrow['columnname'].':'.$columntototalrow['fieldlabel']."_MIN:4") + { + $options []= ''; + }else + { + $options []= ''; + } + + if($selectedcolumn1[5] == "cb:".$columntototalrow['tablename'].':'.$columntototalrow['columnname'].':'.$columntototalrow['fieldlabel']."_MAX:5") + { + $options []= ''; + }else + { + $options []= ''; + } + }else + { + $options []= getTranslatedString($columntototalrow['tablabel'],$columntototalrow['tablabel']).' - '.getTranslatedString($columntototalrow['fieldlabel'],$columntototalrow['tablabel']); + $options []= ''; + $options []= ''; + $options []= ''; + $options [] =''; + } + $options_list [] = $options; + } + }while($columntototalrow = $adb->fetch_array($result)); + + $log->info("Reports :: Successfully returned sgetColumnstoTotalHTML"); + return $options_list; + } +} + +/** Function to get the primary module list in vtiger_reports + * This function generates the list of primary modules in vtiger_reports + * and returns an array of permitted modules + */ + +function getReportsModuleList($focus) +{ + global $adb; + global $app_list_strings; + //global $report_modules; + global $mod_strings; + $modules = Array(); + foreach($focus->module_list as $key=>$value) + { + if(isPermitted($key,'index') == "yes") + { + $count_flag = 1; + $modules [$key] = getTranslatedString($key,$key); + } + } + return $modules; +} +/** Function to get the Related module list in vtiger_reports + * This function generates the list of secondary modules in vtiger_reports + * and returns the related module as an Array + */ + +function getReportRelatedModules($module,$focus) +{ + global $app_list_strings; + global $related_modules; + global $mod_strings; + $optionhtml = Array(); + if(vtlib_isModuleActive($module)){ + if(!empty($focus->related_modules[$module])) { + foreach($focus->related_modules[$module] as $rel_modules) + { + if(isPermitted($rel_modules,'index') == "yes") + { + $optionhtml []= $rel_modules; + } + } + } + } + + + return $optionhtml; +} + + +?> diff --git a/oss/vtiger/trunk/modules/Reports/ReportsAjax.php b/oss/vtiger/trunk/modules/Reports/ReportsAjax.php new file mode 100644 index 00000000..47722722 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/ReportsAjax.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Reports/Save.php b/oss/vtiger/trunk/modules/Reports/Save.php new file mode 100644 index 00000000..8c2a544b --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/Save.php @@ -0,0 +1,370 @@ +>>>>>>>> +$selectedcolumnstring = $_REQUEST["selectedColumnsString"]; +//<<<<<<>>>>>>>> + +//<<<<<<>>>>>>>> +$sort_by1 = vtlib_purify($_REQUEST["Group1"]); +$sort_order1 = vtlib_purify($_REQUEST["Sort1"]); +$sort_by2 = vtlib_purify($_REQUEST["Group2"]); +$sort_order2 = vtlib_purify($_REQUEST["Sort2"]); +$sort_by3 = vtlib_purify($_REQUEST["Group3"]); +$sort_order3 = vtlib_purify($_REQUEST["Sort3"]); +//<<<<<<>>>>>>>> +$selectedcolumns = explode(";",$selectedcolumnstring); +if(!in_array($sort_by1,$selectedcolumns)){ + $selectedcolumns[] = $sort_by1; +} +if(!in_array($sort_by2,$selectedcolumns)){ + $selectedcolumns[] = $sort_by2; +} +if(!in_array($sort_by3,$selectedcolumns)){ + $selectedcolumns[] = $sort_by3; +} +//<<<<<<>>>>>>>> +$pmodule = vtlib_purify($_REQUEST["primarymodule"]); +$smodule = vtlib_purify($_REQUEST["secondarymodule"]); +//<<<<<<>>>>>>>> + +//<<<<<<>>>>>>>> +$reportname = vtlib_purify($_REQUEST["reportName"]); +$reportdescription = vtlib_purify($_REQUEST["reportDesc"]); +$reporttype = vtlib_purify($_REQUEST["reportType"]); +$folderid = vtlib_purify($_REQUEST["folder"]); +//<<<<<<>>>>>>>> + +//<<<<<<>>>>>>>> +$stdDateFilterField = vtlib_purify($_REQUEST["stdDateFilterField"]); +$stdDateFilter = vtlib_purify($_REQUEST["stdDateFilter"]); +$startdate = getDBInsertDateValue($_REQUEST["startdate"]); +$enddate = getDBInsertDateValue($_REQUEST["enddate"]); +//<<<<<<>>>>>>>> + +//<<<<<<>>>>>>>> +$sharetype = vtlib_purify($_REQUEST["stdtypeFilter"]); +$shared_entities = vtlib_purify($_REQUEST["selectedColumnsStr"]); +//<<<<<<>>>>>>>> + +//<<<<<<>>>>>>>>> +$allKeys = array_keys($_REQUEST); +for ($i=0;$i>>>>>>>> + +//<<<<<<>>>>>>> +//$adv_filter_col = "kcol"; +//$allKeys = array_keys($HTTP_POST_VARS); +$allKeys = array_keys($_REQUEST); +for ($i=0;$i>>>>>>> +if($reportid == "") +{ + $genQueryId = $adb->getUniqueID("vtiger_selectquery"); + if($genQueryId != "") + { + $iquerysql = "insert into vtiger_selectquery (QUERYID,STARTINDEX,NUMOFOBJECTS) values (?,?,?)"; + $iquerysqlresult = $adb->pquery($iquerysql, array($genQueryId,0,0)); + $log->info("Reports :: Save->Successfully saved vtiger_selectquery"); + if($iquerysqlresult!=false) + { + //<<<>>>>>>> + if(!empty($selectedcolumns)) + { + for($i=0 ;$ipquery($icolumnsql, array($genQueryId,$i,$selectedcolumns[$i])); + } + } + } + if($shared_entities != "") + { + if($sharetype == "Shared") + { + $selectedcolumn = explode(";",$shared_entities); + for($i=0 ;$i< count($selectedcolumn) -1 ;$i++) + { + $temp = split("::",$selectedcolumn[$i]); + $icolumnsql = "insert into vtiger_reportsharing (reportid,shareid,setype) values (?,?,?)"; + $icolumnsqlresult = $adb->pquery($icolumnsql, array($genQueryId,$temp[1],$temp[0])); + } + } + } + $log->info("Reports :: Save->Successfully saved vtiger_selectcolumn"); + //<<<>>>>>>> + + if($genQueryId != "") + { + $ireportsql = "insert into vtiger_report (REPORTID,FOLDERID,REPORTNAME,DESCRIPTION,REPORTTYPE,QUERYID,STATE,OWNER,SHARINGTYPE) values (?,?,?,?,?,?,?,?,?)"; + $ireportparams = array($genQueryId, $folderid, $reportname, $reportdescription, $reporttype, $genQueryId,'CUSTOM',$current_user->id,$sharetype); + $ireportresult = $adb->pquery($ireportsql, $ireportparams); + $log->info("Reports :: Save->Successfully saved vtiger_report"); + if($ireportresult!=false) + { + //<<<>>>>>> + $ireportmodulesql = "insert into vtiger_reportmodules (REPORTMODULESID,PRIMARYMODULE,SECONDARYMODULES) values (?,?,?)"; + $ireportmoduleresult = $adb->pquery($ireportmodulesql, array($genQueryId, $pmodule, $smodule)); + $log->info("Reports :: Save->Successfully saved vtiger_reportmodules"); + //<<<>>>>>> + + //<<<>>>>>> + if($sort_by1 != "") + { + $sort_by1sql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_by1result = $adb->pquery($sort_by1sql, array(1, $genQueryId, $sort_by1, $sort_order1)); + } + if($sort_by2 != "") + { + $sort_by2sql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_by2result = $adb->pquery($sort_by2sql, array(2,$genQueryId,$sort_by2,$sort_order2)); + } + if($sort_by3 != "") + { + $sort_by3sql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_by3result = $adb->pquery($sort_by3sql, array(3,$genQueryId,$sort_by3,$sort_order3)); + } + $log->info("Reports :: Save->Successfully saved vtiger_reportsortcol"); + //<<<>>>>>> + + //<<<>>>>>> + $ireportmodulesql = "insert into vtiger_reportdatefilter (DATEFILTERID,DATECOLUMNNAME,DATEFILTER,STARTDATE,ENDDATE) values (?,?,?,?,?)"; + $ireportmoduleresult = $adb->pquery($ireportmodulesql, array($genQueryId, $stdDateFilterField, $stdDateFilter, $startdate, $enddate)); + $log->info("Reports :: Save->Successfully saved vtiger_reportdatefilter"); + //<<<>>>>>> + + //<<<>>>>>> + for ($i=0;$ipquery($ireportsummarysql, array($genQueryId, $i, $columnstototal[$i])); + } + $log->info("Reports :: Save->Successfully saved vtiger_reportsummary"); + //<<<>>>>>> + + //<<<>>>>>> + for ($i=0;$ipquery($irelcriteriasql, array($genQueryId, $i, $adv_filter_col[$i], $adv_filter_option[$i], $adv_filter_value[$i])); + } + $log->info("Reports :: Save->Successfully saved vtiger_relcriteria"); + //<<<>>>>>> + + }else + { + $errormessage = "Error Message
      +
    • Error while inserting the record +

    " ; + echo $errormessage; + die; + } + } + }else + { + $errormessage = "Error Message
      +
    • Error while inserting the record +

    " ; + echo $errormessage; + die; + } + echo ''; + } +}else +{ + if($reportid != "") + { + if(!empty($selectedcolumns)) + { + $idelcolumnsql = "delete from vtiger_selectcolumn where queryid=?"; + $idelcolumnsqlresult = $adb->pquery($idelcolumnsql, array($reportid)); + if($idelcolumnsqlresult != false) + { + for($i=0 ;$ipquery($icolumnsql, array($reportid,$i,$selectedcolumns[$i])); + } + } + } + } + $delsharesqlresult = $adb->pquery("DELETE FROM vtiger_reportsharing WHERE reportid=?", array($reportid)); + if($delsharesqlresult != false && $sharetype=="Shared" && $shared_entities!='') + { + $selectedcolumn = explode(";",$shared_entities); + for($i=0 ;$i< count($selectedcolumn) -1 ;$i++) + { + $temp = split("::",$selectedcolumn[$i]); + $icolumnsql = "INSERT INTO vtiger_reportsharing (reportid,shareid,setype) VALUES (?,?,?)"; + $icolumnsqlresult = $adb->pquery($icolumnsql, array($reportid,$temp[1],$temp[0])); + } + } + + //<<<>>>>>> + $ireportmodulesql = "UPDATE vtiger_reportmodules SET primarymodule=?,secondarymodules=? WHERE reportmodulesid=?"; + $ireportmoduleresult = $adb->pquery($ireportmodulesql, array($pmodule, $smodule,$reportid)); + $log->info("Reports :: Save->Successfully saved vtiger_reportmodules"); + //<<<>>>>>> + + $ireportsql = "update vtiger_report set REPORTNAME=?, DESCRIPTION=?, REPORTTYPE=?, SHARINGTYPE=? where REPORTID=?"; + $ireportparams = array($reportname, $reportdescription, $reporttype, $sharetype, $reportid); + $ireportresult = $adb->pquery($ireportsql, $ireportparams); + $log->info("Reports :: Save->Successfully saved vtiger_report"); + + $idelreportsortcolsql = "delete from vtiger_reportsortcol where reportid=?"; + $idelreportsortcolsqlresult = $adb->pquery($idelreportsortcolsql, array($reportid)); + $log->info("Reports :: Save->Successfully deleted vtiger_reportsortcol"); + + if($idelreportsortcolsqlresult!=false) + { + //<<<>>>>>> + if($sort_by1 != "") + { + $sort_by1sql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_by1result = $adb->pquery($sort_by1sql, array(1, $reportid, $sort_by1, $sort_order1)); + } + if($sort_by2 != "") + { + $sort_by2sql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_by2result = $adb->pquery($sort_by2sql, array(2, $reportid, $sort_by2, $sort_order2)); + } + if($sort_by3 != "") + { + $sort_by3sql = "insert into vtiger_reportsortcol (SORTCOLID,REPORTID,COLUMNNAME,SORTORDER) values (?,?,?,?)"; + $sort_by3result = $adb->pquery($sort_by3sql, array(3, $reportid, $sort_by3, $sort_order3)); + } + $log->info("Reports :: Save->Successfully saved vtiger_reportsortcol"); + //<<<>>>>>> + + $idelreportdatefiltersql = "delete from vtiger_reportdatefilter where datefilterid=?"; + $idelreportdatefiltersqlresult = $adb->pquery($idelreportdatefiltersql, array($reportid)); + + //<<<>>>>>> + $ireportmodulesql = "insert into vtiger_reportdatefilter (DATEFILTERID,DATECOLUMNNAME,DATEFILTER,STARTDATE,ENDDATE) values (?,?,?,?,?)"; + $ireportmoduleresult = $adb->pquery($ireportmodulesql, array($reportid, $stdDateFilterField, $stdDateFilter, $startdate, $enddate)); + $log->info("Reports :: Save->Successfully saved vtiger_reportdatefilter"); + //<<<>>>>>> + + //<<<>>>>>> + $idelreportsummarysql = "delete from vtiger_reportsummary where reportsummaryid=?"; + $idelreportsummarysqlresult = $adb->pquery($idelreportsummarysql, array($reportid)); + + for ($i=0;$ipquery($ireportsummarysql, array($reportid, $i, $columnstototal[$i])); + } + $log->info("Reports :: Save->Successfully saved vtiger_reportsummary"); + //<<<>>>>>> + + + //<<<>>>>>> + + $idelrelcriteriasql = "delete from vtiger_relcriteria where queryid=?"; + $idelrelcriteriasqlresult = $adb->pquery($idelrelcriteriasql, array($reportid)); + + for ($i=0;$iquote($adv_filter_value[$i]); + + $irelcriteriasql = "insert into vtiger_relcriteria(QUERYID,COLUMNINDEX,COLUMNNAME,COMPARATOR,VALUE) values (?,?,?,?,?)"; + $irelcriteriaresult = $adb->pquery($irelcriteriasql, array($reportid, $i, $adv_filter_col[$i], $adv_filter_option[$i], $adv_filter_value[$i])); + } + $log->info("Reports :: Save->Successfully saved vtiger_relcriteria"); + //<<<>>>>>> + + }else + { + $errormessage = "Error Message
      +
    • Error while inserting the record +

    " ; + echo $errormessage; + die; + } + }else + { + $errormessage = "Error Message
      +
    • Error while inserting the record +

    " ; + echo $errormessage; + die; + } + echo ''; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Reports/SaveAndRun.php b/oss/vtiger/trunk/modules/Reports/SaveAndRun.php new file mode 100644 index 00000000..7bd5361a --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/SaveAndRun.php @@ -0,0 +1,303 @@ +pquery($sql, array($reportid)); +$Report_ID = $adb->query_result($res,0,'reportid'); +$numOfRows = $adb->num_rows($res); +if($numOfRows > 0) +{ + $startdate = getDBInsertDateValue($_REQUEST["startdate"]);//Convert the user date format to DB date format + $enddate = getDBInsertDateValue($_REQUEST["enddate"]);//Convert the user date format to DB date format + + global $primarymodule,$secondarymodule,$orderbylistsql,$orderbylistcolumns,$ogReport; + //added to fix the ticket #5117 + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $ogReport = new Reports($reportid); + $primarymodule = $ogReport->primodule; + $restrictedmodules = array(); + if($ogReport->secmodule!='') + $rep_modules = split(":",$ogReport->secmodule); + else + $rep_modules = array(); + + array_push($rep_modules,$primarymodule); + $modules_permitted = true; + $modules_export_permitted = true; + foreach($rep_modules as $mod){ + if(isPermitted($mod,'index')!= "yes" || vtlib_isModuleActive($mod)==false){ + $modules_permitted = false; + $restrictedmodules[] = $mod; + } + if(isPermitted("$mod",'Export','')!='yes') + $modules_export_permitted = false; + } + + if(isPermitted($primarymodule,'index') == "yes" && $modules_permitted == true) + { + $oReportRun = new ReportRun($reportid); + $filterlist = $oReportRun->RunTimeFilter($filtercolumn,$filter,$startdate,$enddate); + + // Performance Optimization: Direct output of the report result + $list_report_form = new vtigerCRM_Smarty; + + //$sshtml = $oReportRun->GenerateReport("HTML",$filterlist); + //if(is_array($sshtml))$totalhtml = $oReportRun->GenerateReport("TOTALHTML",$filterlist); + + $sshtml = array(); + $totalhtml = ''; + $list_report_form->assign("DIRECT_OUTPUT", true); + $list_report_form->assign_by_ref("__REPORT_RUN_INSTANCE", $oReportRun); + $list_report_form->assign_by_ref("__REPORT_RUN_FILTER_LIST", $filterlist); + // END + + $ogReport->getSelectedStandardCriteria($reportid); + //commented to omit dashboards for vtiger_reports + //require_once('modules/Dashboard/ReportsCharts.php'); + //$image = get_graph_by_type('Report','Report',$primarymodule,'',$sshtml[2]); + //$list_report_form->assign("GRAPH", $image); + + $BLOCK1 = getPrimaryStdFilterHTML($ogReport->primodule,$ogReport->stdselectedcolumn); + $BLOCK1 .= getSecondaryStdFilterHTML($ogReport->secmodule,$ogReport->stdselectedcolumn); + // Check if selectedcolumn is found in the filters (Fix for ticket #4866) + $selectedcolumnvalue = '"'. decode_html($ogReport->stdselectedcolumn) . '"'; + if (!$is_admin && isset($ogReport->stdselectedcolumn) && strpos($BLOCK1, $selectedcolumnvalue) === false) { + $BLOCK1 .= ""; + } + $list_report_form->assign("BLOCK1",$BLOCK1); + $BLOCKJS = $ogReport->getCriteriaJS(); + $list_report_form->assign("BLOCKJS",$BLOCKJS); + + $BLOCKCRITERIA = $ogReport->getSelectedStdFilterCriteria($ogReport->stdselectedfilter); + $list_report_form->assign("BLOCKCRITERIA",$BLOCKCRITERIA); + if(isset($ogReport->startdate) && isset($ogReport->enddate)) + { + $list_report_form->assign("STARTDATE",getDisplayDate($ogReport->startdate)); + $list_report_form->assign("ENDDATE",getDisplayDate($ogReport->enddate)); + }else + { + $list_report_form->assign("STARTDATE",$ogReport->startdate); + $list_report_form->assign("ENDDATE",$ogReport->enddate); + } + $list_report_form->assign("MOD", $mod_strings); + $list_report_form->assign("APP", $app_strings); + $list_report_form->assign("IMAGE_PATH", $image_path); + $list_report_form->assign("REPORTID", $reportid); + $list_report_form->assign("IS_EDITABLE", $ogReport->is_editable); + + $list_report_form->assign("REPORTNAME", htmlspecialchars($ogReport->reportname,ENT_QUOTES,$default_charset)); + if(is_array($sshtml))$list_report_form->assign("REPORTHTML", $sshtml); + else $list_report_form->assign("ERROR_MSG", getTranslatedString('LBL_REPORT_GENERATION_FAILED', $currentModule) . "
    " . $sshtml); + $list_report_form->assign("REPORTTOTHTML", $totalhtml); + $list_report_form->assign("FOLDERID", $folderid); + $list_report_form->assign("DATEFORMAT",$current_user->date_format); + $list_report_form->assign("JS_DATEFORMAT",parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + if($modules_export_permitted==true){ + $list_report_form->assign("EXPORT_PERMITTED","YES"); + } else { + $list_report_form->assign("EXPORT_PERMITTED","NO"); + } + $rep_in_fldr = $ogReport->sgetRptsforFldr($folderid); + for($i=0;$iassign("REPINFOLDER", $reports_array); + include('themes/'.$theme.'/header.php'); + $list_report_form->display('ReportRun.tpl'); + } + else + { + $list_report_form->display('ReportRunContents.tpl'); + } + } + else + { + if($_REQUEST['mode'] != 'ajax') + { + include('themes/'.$theme.'/header.php'); + } + echo "
    "; + echo "
    + + + + + + + + + +
    ".$mod_strings['LBL_NO_ACCESS']." : ".implode(",",$restrictedmodules)."
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; + } +} +else +{ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    ".$mod_strings['LBL_REPORT_DELETED']."
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; +} + /** Function to get the StdfilterHTML strings for the given primary module + * @ param $module : Type String + * @ param $selected : Type String(optional) + * This Generates the HTML Combo strings for the standard filter for the given reports module + * This Returns a HTML sring + */ +function getPrimaryStdFilterHTML($module,$selected="") +{ + + global $app_list_strings; + global $ogReport; + global $current_language; + $ogReport->oCustomView=new CustomView(); + $result = $ogReport->oCustomView->getStdCriteriaByModule($module); + $mod_strings = return_module_language($current_language,$module); + if(isset($result)) + { + foreach($result as $key=>$value) + { + if(isset($mod_strings[$value])) + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + }else + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + } + } + } + + return $shtml; +} + + /** Function to get the StdfilterHTML strings for the given secondary module + * @ param $module : Type String + * @ param $selected : Type String(optional) + * This Generates the HTML Combo strings for the standard filter for the given reports module + * This Returns a HTML sring + */ +function getSecondaryStdFilterHTML($module,$selected="") +{ + global $app_list_strings; + global $ogReport; + global $current_language; + $ogReport->oCustomView=new CustomView(); + + if($module != "") + { + $secmodule = explode(":",$module); + for($i=0;$i < count($secmodule) ;$i++) + { + $result = $ogReport->oCustomView->getStdCriteriaByModule($secmodule[$i]); + $mod_strings = return_module_language($current_language,$secmodule[$i]); + if(isset($result)) + { + foreach($result as $key=>$value) + { + if(isset($mod_strings[$value])) + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + }else + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + } + } + } + + } + } + return $shtml; +} + /** Function to get the reports under a report folder + * @ param $folderid : Type Integer + * This Returns $reports_array in the following format + * $reports_array = array ($reportid=>$reportname,$reportid=>$reportname1,.............,$reportidn=>$reportname) + */ +function getReportsinFolder($folderid) +{ + global $adb; + $query = 'select reportid,reportname from vtiger_report where folderid=?'; + $result = $adb->pquery($query, array($folderid)); + $reports_array = Array(); + for($i=0;$i < $adb->num_rows($result);$i++) + { + $reportid = $adb->query_result($result,$i,'reportid'); + $reportname = $adb->query_result($result,$i,'reportname'); + $reports_array[$reportid] = $reportname; + } + if(count($reports_array) > 0) + return $reports_array; + else + return false; +} +?> diff --git a/oss/vtiger/trunk/modules/Reports/SaveReport.php b/oss/vtiger/trunk/modules/Reports/SaveReport.php new file mode 100644 index 00000000..9d6a5ee7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/SaveReport.php @@ -0,0 +1,43 @@ +assign("MOD", $mod_strings); +$save_report_form->assign("APP", $app_strings); +$save_report_form->assign("THEME_PATH",$theme); +$oReport = new Reports(); +$reportfolderhtml = $oReport->sgetRptFldrSaveReport(); +$save_report_form->assign("REPORT_FOLDER", $reportfolderhtml); +$save_report_form->parse("main"); +$save_report_form->out("main"); +?> diff --git a/oss/vtiger/trunk/modules/Reports/SaveReport0.php b/oss/vtiger/trunk/modules/Reports/SaveReport0.php new file mode 100644 index 00000000..8638f2a7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/SaveReport0.php @@ -0,0 +1,30 @@ +0) { + $secondarymodule_req = implode(":",$secondarymodule_req); +} + +if($primarymodule_req!="") +{ + header("Location: index.php?action=NewReport1&module=Reports&primarymodule=$primarymodule_req&secondarymodule=$secondarymodule_req"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Reports/SaveReportFolder.php b/oss/vtiger/trunk/modules/Reports/SaveReportFolder.php new file mode 100644 index 00000000..0e37a0a7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/SaveReportFolder.php @@ -0,0 +1,69 @@ +pquery($sql, $sql_params); + if($result!=false) + { + header("Location: index.php?action=ReportsAjax&file=ListView&mode=ajax&module=Reports"); + }else + { + include('themes/'.$theme.'/header.php'); + $errormessage = "Error Message
      +
    • Error while inserting the record +

    " ; + echo $errormessage; + } + } +}elseif($mode=="Edit") +{ + if($rfid != "") + { + $sql = "update vtiger_reportfolder set "; + $sql .= "FOLDERNAME=?, DESCRIPTION=? where folderid=?"; + $params = array(trim($foldername), $folderdesc, $rfid); + $result = $adb->pquery($sql, $params); + if($result!=false) + { + header("Location: index.php?action=ReportsAjax&file=ListView&mode=ajax&module=Reports"); + }else + { + include('themes/'.$theme.'/header.php'); + $errormessage = "Error Message
      +
    • Error while updating the record +

    " ; + echo $errormessage; + } + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Reports/StandardFilter.php b/oss/vtiger/trunk/modules/Reports/StandardFilter.php new file mode 100644 index 00000000..da40b25e --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/StandardFilter.php @@ -0,0 +1,170 @@ +related_modules[$primarymodule])) { + foreach($ogReport->related_modules[$primarymodule] as $key=>$value){ + $BLOCK1 .= getSecondaryStdFilterHTML($_REQUEST["secondarymodule_".$value]); + } + } + + $report_std_filter->assign("BLOCK1_STD",$BLOCK1); + $BLOCKJS = $oReport->getCriteriaJS(); + $report_std_filter->assign("BLOCKJS_STD",$BLOCKJS); + $BLOCKCRITERIA = $oReport->getSelectedStdFilterCriteria(); + $report_std_filter->assign("BLOCKCRITERIA_STD",$BLOCKCRITERIA); + +}elseif(isset($_REQUEST["record"]) == true) +{ + //added to fix the ticket #5117 + global $current_user; + require('user_privileges/user_privileges_'.$current_user->id.'.php'); + + $reportid = vtlib_purify($_REQUEST["record"]); + $oReport = new Reports($reportid); + $oReport->getSelectedStandardCriteria($reportid); + + $oRep = new Reports(); + $secondarymodule = ''; + $secondarymodules =Array(); + + if(!empty($oRep->related_modules[$oReport->primodule])) { + foreach($oRep->related_modules[$oReport->primodule] as $key=>$value){ + if(isset($_REQUEST["secondarymodule_".$value]))$secondarymodules []= $_REQUEST["secondarymodule_".$value]; + } + } + $secondarymodule = implode(":",$secondarymodules); + + if($secondarymodule!='') + $oReport->secmodule = $secondarymodule; + + $BLOCK1 = getPrimaryStdFilterHTML($oReport->primodule,$oReport->stdselectedcolumn); + $BLOCK1 .= getSecondaryStdFilterHTML($oReport->secmodule,$oReport->stdselectedcolumn); + //added to fix the ticket #5117 + $selectedcolumnvalue = '"'. $oReport->stdselectedcolumn . '"'; + if (!$is_admin && isset($oReport->stdselectedcolumn) && strpos($BLOCK1, $selectedcolumnvalue) === false) + $BLOCK1 .= ""; + + $report_std_filter->assign("BLOCK1_STD",$BLOCK1); + + $BLOCKJS = $oReport->getCriteriaJS(); + $report_std_filter->assign("BLOCKJS_STD",$BLOCKJS); + + $BLOCKCRITERIA = $oReport->getSelectedStdFilterCriteria($oReport->stdselectedfilter); + $report_std_filter->assign("BLOCKCRITERIA_STD",$BLOCKCRITERIA); + + if(isset($oReport->startdate) && isset($oReport->enddate)) + { + $report_std_filter->assign("STARTDATE_STD",getDisplayDate($oReport->startdate)); + $report_std_filter->assign("ENDDATE_STD",getDisplayDate($oReport->enddate)); + }else{ + $report_std_filter->assign("STARTDATE_STD",$oReport->startdate); + $report_std_filter->assign("ENDDATE_STD",$oReport->enddate); + } +} + + + /** Function to get the HTML strings for the primarymodule standard filters + * @ param $module : Type String + * @ param $selected : Type String(optional) + * This Returns a HTML combo srings + */ +function getPrimaryStdFilterHTML($module,$selected="") +{ + global $app_list_strings; + global $ogReport; + global $current_language; + $ogReport->oCustomView=new CustomView(); + $result = $ogReport->oCustomView->getStdCriteriaByModule($module); + $mod_strings = return_module_language($current_language,$module); + + if(isset($result)) + { + foreach($result as $key=>$value) + { + if(isset($mod_strings[$value])) + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + }else + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + } + } + } + + return $shtml; +} + + /** Function to get the HTML strings for the secondary standard filters + * @ param $module : Type String + * @ param $selected : Type String(optional) + * This Returns a HTML combo srings for the secondary modules + */ +function getSecondaryStdFilterHTML($module,$selected="") +{ + global $app_list_strings; + global $ogReport; + global $current_language; + $ogReport->oCustomView=new CustomView(); + if($module != "") + { + $secmodule = explode(":",$module); + for($i=0;$i < count($secmodule) ;$i++) + { + $result = $ogReport->oCustomView->getStdCriteriaByModule($secmodule[$i]); + $mod_strings = return_module_language($current_language,$secmodule[$i]); + if(isset($result)) + { + foreach($result as $key=>$value) + { + if(isset($mod_strings[$value])) + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + }else + { + if($key == $selected) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + } + } + } + + } + } + return $shtml; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Reports/index.php b/oss/vtiger/trunk/modules/Reports/index.php new file mode 100644 index 00000000..f82c203c --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/index.php @@ -0,0 +1,27 @@ + diff --git a/oss/vtiger/trunk/modules/Reports/language/en_us.lang.php b/oss/vtiger/trunk/modules/Reports/language/en_us.lang.php new file mode 100644 index 00000000..e0e70cae --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/language/en_us.lang.php @@ -0,0 +1,227 @@ +'Reports', +'LBL_MODULE_TITLE'=>'Reports: Home', +'LBL_CREATE_REPORT'=>'Create Report', +'LBL_CUSTOMIZE_REPORT'=>'Customize Report', +'LBL_REP_BUTTON'=>'Create New Report', +'LBL_REP_FOLDER_BUTTON'=>'Create New Report Folder', +'LBL_REP_FOLDER'=>'Report Folder', +'LBL_REP_FOLDER_DTLS'=>'Folder Details', +'LBL_REP_FOLDER_NAME'=>'Folder Name:', +'LBL_REP_FOLDER_DESC'=>'Folder Description:', +'LBL_NEW_REP0_HDR1'=>'Select a Module for which a new Report has to be created:', +'LBL_NEW_REP0_HDR2'=>'Select Related Module:', +'LBL_NEW_REP0_HDR3'=>'Note:', +'LBL_NEW_REP0_HDR4'=>'Report Module and related module once selected cannot be modified later', +'LBL_CONTINUE_BUTTON'=>'Continue', +'LBL_NEW_REP1_HDR1'=>'Provide the following report information', +'LBL_SELECT_COLUMNS'=>'Select Columns', +'LBL_SPECIFY_GROUPING'=>'Specify Grouping', +'LBL_COLUMNS_TO_TOTAL'=>'Choose Columns To Total', +'LBL_SPECIFY_CRITERIA'=>'Specify Criteria', +'LBL_SAVERUN_BUTTON'=>'Save And Run', +'LBL_TABULAT_REPORT'=>'Tabular Report', +'LBL_REPORT_TYPE_HDR1'=>'Tabular reports are the simplest and fastest way to get a listing of your data.', +'LBL_SUMMARY_REPORT'=>'Summary Report', +'LBL_REPORT_TYPE_HDR2'=>'Summary reports allow you to view your data along with subtotals and other summary information.', +'LBL_AVAILABLE_COLUMNS'=>'Available Columns:', +'LBL_SELECTED_COLUMNS'=>'Selected Columns:', +'LBL_ADD_BUTTON'=>'Add', +'LBL_COLUMNS'=>'Columns', +'LBL_COLUMNS_SUM'=>'Sum', +'LBL_COLUMNS_AVERAGE'=>'Average', +'LBL_COLUMNS_LOW_VALUE'=>'Lowest Value', +'LBL_COLUMNS_LARGE_VALUE'=>'Largest Value', +'LBL_NONE'=>'None', +'LBL_GROUPING_SORT'=>'Sort Order:', +'LBL_GROUPING_SUMMARIZE'=>'Summarize information by:', +'LBL_GROUPING_THEN_BY'=>'and then by:', +'LBL_GROUPING_FINALLY_BY'=>'and finally by:', +'LBL_ADVANCED_FILTER'=>'Advanced Filters', +'LBL_STANDARD_FILTER'=>'Standard Filters', +'LBL_SF_COLUMNS'=>'Column', +'LBL_SF_STARTDATE'=>'Start Date', +'LBL_SF_ENDDATE'=>'End Date', +'LBL_AF_HDR1'=>'Set the search conditions to further restrict the list.', +'LBL_AF_HDR2'=>'You can use "or" filters by entering multiple items in the third column.', +'LBL_AF_HDR3'=>'You can enter up to 10 items, separated by commas. For example: CA, NY, TX, FL searches for CA or NY or TX or FL.', +'LBL_FILTER_OPTIONS'=>'Filter Options', +'LBL_CUSTOMIZE_BUTTON'=>'Customize', +'LBL_EXPORTPDF_BUTTON'=>'Export To PDF', +'LBL_APPLYFILTER_BUTTON'=>'Apply Filter', +'LBL_GENERATED_REPORT'=>'Generated Report', +'LBL_GRAND_TOTAL'=>'Grand Total', + +//Added for 4.2 Patch I +'LBL_EXPORTXL_BUTTON'=>'Export To Excel', + +//Added for 5 Beta +'LBL_NO_PERMISSION'=>'Your profile dosen\'t allow you view the reports for one of the module(s)', +'LBL_SELECT_COLUMNS_TO_GENERATE_REPORTS'=>'Select columns to generate reports', +'LBL_AVAILABLE_FIELDS'=>'Available Fields', +'LBL_SELECTED_FIELDS'=>'Selected Fields', +'LBL_CALCULATIONS'=>'Calculations', +'LBL_SELECT_COLUMNS_TO_TOTAL'=>'Select columns to Total', +'LBL_SELECT_FILTERS_TO_STREAMLINE_REPORT_DATA'=>'Select Filters to Streamline Report Data', +'LBL_SELECT_FILTERS'=>'Filters', +'LBL_SELECT_COLUMNS_TO_GROUP_REPORTS'=>'Select columns to group reports', +'LBL_BACK_TO_REPORTS'=>'Back to Reports', +'LBL_SELECT_ANOTHER_REPORT'=>'Select Another Report', +'LBL_SELECT_COLUMN'=>'Select Column', +'LBL_SELECT_TIME'=>'Select Time', +'LBL_PRINT_REPORT'=>'Print Report', +'LBL_CLICK_HERE'=>'Click Here', +'LBL_TO_ADD_NEW_GROUP'=>'to add new folder', +'LBL_CREATE_NEW'=>'Create New', +'LBL_RELATIVE_MODULE'=>'Related Module', +'LBL_REPORT_TYPE'=>'Report Type', +'LBL_REPORT_DETAILS'=>'Report Details', +'LBL_TYPE_THE_NAME'=>'Type the Name', +'LBL_DESCRIPTION_FOR_REPORT'=>'Description for the report', +'LBL_REPORT_NAME'=>'Report Name', +'LBL_DESCRIPTION'=>'Description', +'LBL_TOOLS'=>'Tools', +'LBL_AND'=>'and', +'LBL_ADD_NEW_GROUP'=>'Add New Folder', +'LBL_REPORT_MODULE'=>'Report Module', +'LBL_SELECT_RELATIVE_MODULE_FOR_REPORT'=>'Select Related Module for Report', +'LBL_SELECT_REPORT_TYPE_BELOW'=>'Select Report type Below', +'LBL_TABULAR_FORMAT'=>'Tabular Format', +'LBL_TABULAR_REPORTS_ARE_SIMPLEST'=>'Tabular Reports are the simplest and fastest way of getting your data', +'LBL_SUMMARY_REPORT_VIEW_DATA_WITH_SUBTOTALS'=>'Summary reports allow you to view your data along with subtotals and other summary information', +'LBL_FILTERS'=>'Filters', +'LBL_MOVE_TO'=>'Move to', +'LBL_RENAME_FOLDER'=>'Rename Folder', +'LBL_DELETE_FOLDER'=>'Delete Folder', + +'Account and Contact Reports'=>'Account and Contact Reports', +'Lead Reports'=>'Lead Reports', +'Potential Reports'=>'Potential Reports', +'Activity Reports'=>'Activity Reports', +'HelpDesk Reports'=>'Trouble Tickets Reports', +'Product Reports'=>'Product Reports', +'Quote Reports'=>'Quote Reports', +'PurchaseOrder Reports'=>'PurchaseOrder Reports', +'SalesOrder Reports'=>'SalesOrder Reports', //Added for SO +'Invoice Reports'=>'Invoice Reports', +'Campaign Reports'=>'Campaign Reports', //Added for Campaigns +'Contacts by Accounts'=>'Contacts by Accounts', +'Contacts without Accounts'=>'Contacts without Accounts', +'Contacts by Potentials'=>'Contacts by Potentials', +'Contacts related to Accounts'=>'Contacts related to Accounts', +'Contacts not related to Accounts'=>'Contacts not related to Accounts', +'Contacts related to Potentials'=>'Contacts related to Potentials', +'Lead by Source'=>'Lead by Source', +'Lead Status Report'=>'Lead Status Report', +'Potential Pipeline'=>'Potential Pipeline', +'Closed Potentials'=>'Closed Potentials', +'Potential that have Won'=>'Potential that have Won', +'Tickets by Products'=>'Tickets by Products', +'Tickets by Priority'=>'Tickets by Priority', +'Open Tickets'=>'Open Tickets', +'Tickets related to Products'=>'Tickets related to Products', +'Tickets that are Open'=>'Tickets that are Open', +'Product Details'=>'Product Details', +'Products by Contacts'=>'Products by Contacts', +'Product Detailed Report'=>'Product Detailed Report', +'Products related to Contacts'=>'Products related to Contacts', +'Open Quotes'=>'Open Quotes', +'Quotes Detailed Report'=>'Quotes Detailed Report', +'Quotes that are Open'=>'Quotes that are Open', +'PurchaseOrder by Contacts'=>'PurchaseOrder by Contacts', +'PurchaseOrder Detailed Report'=>'PurchaseOrder Detailed Report', +'PurchaseOrder related to Contacts'=>'PurchaseOrder related to Contacts', +'Invoice Detailed Report'=>'Invoice Detailed Report', +'Last Month Activities'=>'Last Month Activities', +'This Month Activities'=>'This Month Activities', +'Campaign Expectations and Actuals'=>'Campaign Expectations and Actuals', //Added for Campaigns +'SalesOrder Detailed Report'=>'SalesOrder Detailed Report', //Added for SO + +'LBL_DELETE'=>'Delete', +'Create_Reports'=>'Create Reports', +'Create_New_Folder'=>'Create New Folder', +'Move_Reports'=>'Move Reports', +'Delete_Report'=>'Delete Report', + +'Custom'=>'Custom', +'Previous FY'=>'Previous FY', +'Current FY'=>'Current FY', +'Next FY'=>'Next FY', +'Previous FQ'=>'Previous FQ', +'Current FQ'=>'Current FQ', +'Next FQ'=>'Next FQ', +'Yesterday'=>'Yesterday', +'Today'=>'Today', +'Tomorrow'=>'Tomorrow', +'Last Week'=>'Last Week', +'Current Week'=>'Current Week', +'Next Week'=>'Next Week', +'Last Month'=>'Last Month', +'Current Month'=>'Current Month', +'Next Month'=>'Next Month', +'Last 7 Days'=>'Last 7 Days', +'Last 30 Days'=>'Last 30 Days', +'Last 60 Days'=>'Last 60 Days', +'Last 90 Days'=>'Last 90 Days', +'Last 120 Days'=>'Last 120 Days', +'Next 7 Days'=>'Next 7 Days', +'Next 30 Days'=>'Next 30 Days', +'Next 60 Days'=>'Next 60 Days', +'Next 90 Days'=>'Next 90 Days', +'Next 120 Days'=>'Next 120 Days', +'TITLE_VTIGERCRM_CREATE_REPORT' => 'vtiger CRM - Create Report', +'TITLE_VTIGERCRM_PRINT_REPORT' => 'vtiger - Print Report', +'NO_FILTER_SELECTED' => 'No filter Selected', + +'LBL_GENERATE_NOW'=>'Generate Now', +'Totals'=>'Field Names', +'SUM'=>'SUM', +'AVG'=>'AVG', +'MAX'=>'MAX', +'MIN'=>'MIN', +'LBL_CUSTOM_REPORTS'=>'Custom Reports', + +'ticketid'=>'Ticket Id', +'NO_COLUMN'=>'No Columns available to Total', + +// Added/Updated for vtiger CRM 5.0.4 +'LBL_REPORT_DELETED' => 'The report you are trying to view has been deleted.', + +//Added for Reports +'LBL_SHARING'=>'Sharing', +'SELECT_FILTER_TYPE'=>'Select Report Type', +'LBL_USERS'=>'Users', +'LBL_GROUPS'=>'Groups', +'LBL_SELECT_FIELDS'=>'Select Fields', +'LBL_MEMBERS'=>'Members', +'LBL_RELATED_FIELDS'=>'Related Fields', +'LBL_NO_ACCESS'=>' Access Denied for module(s) ', +'LBL_NOT_ACTIVE'=>' Access Denied for module(s) ', +'LBL_PERM_DENIED'=>' Permission Denied for Report(s): ', +'LBL_FLDR_NOT_EMPTY'=>'Folder you are trying to delete is not Empty, Move or Delete the Reports in it.', +'NO_REL_MODULES'=>'No Related Modules for the Selected Module', +) + +?> diff --git a/oss/vtiger/trunk/modules/Reports/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Reports/language/zh_cn.lang.php new file mode 100644 index 00000000..3c0fae4b --- /dev/null +++ b/oss/vtiger/trunk/modules/Reports/language/zh_cn.lang.php @@ -0,0 +1,229 @@ + '报表', + 'LBL_MODULE_TITLE' => '报表:首页', +'LBL_CREATE_REPORT' => '建立报表', + 'LBL_CUSTOMIZE_REPORT' => '自订报表', + 'LBL_REP_BUTTON' => '建立新报表', +'LBL_REP_FOLDER_BUTTON' => '建立新报表数据夹', + 'LBL_REP_FOLDER' => '报表数据夹', + 'LBL_REP_FOLDER_DTLS' => '数据夹信息', + 'LBL_REP_FOLDER_NAME' => '数据夹名称:', + 'LBL_REP_FOLDER_DESC' => '资料夹说明:', + 'LBL_NEW_REP0_HDR1' => '选择新报表的数据来自哪个模块:', + 'LBL_NEW_REP0_HDR2' => '选择相关模块:', + 'LBL_NEW_REP0_HDR3' => '摘要', + 'LBL_NEW_REP0_HDR4' => '报表使用的模块与相关模块一旦决定就无法再修改', + 'LBL_CONTINUE_BUTTON' => '继续', + 'LBL_NEW_REP1_HDR1' => '提供下面报表信息', + 'LBL_SELECT_COLUMNS' => '选择字段', + 'LBL_SPECIFY_GROUPING' => '指定群组', + 'LBL_COLUMNS_TO_TOTAL' => '选择总计字段', + 'LBL_SPECIFY_CRITERIA' => '指定规则', + 'LBL_SAVERUN_BUTTON' => '储存&执行', + 'LBL_TABULAT_REPORT' => '表格式报表', + 'LBL_REPORT_TYPE_HDR1' => '表格式报表是数据呈现最简单且最快速的形式', + 'LBL_SUMMARY_REPORT' => '摘要报表', + 'LBL_REPORT_TYPE_HDR2' => '摘要报表可以让您浏览数据的小计与其它摘要信息', + 'LBL_AVAILABLE_COLUMNS' => '可以使用的字段:', + 'LBL_SELECTED_COLUMNS' => '已经选择的字段:', + 'LBL_ADD_BUTTON' => '新增', + 'LBL_COLUMNS' => '字段', + 'LBL_COLUMNS_SUM' => '总计', + 'LBL_COLUMNS_AVERAGE' => '平均', + 'LBL_COLUMNS_LOW_VALUE' => '最小值', + 'LBL_COLUMNS_LARGE_VALUE' => '最大值', + 'LBL_NONE' => '无', + 'LBL_GROUPING_SORT' => '顺序:', + 'LBL_GROUPING_SUMMARIZE' => '摘要信息来源:', + 'LBL_GROUPING_THEN_BY' => '接着来自:', + 'LBL_GROUPING_FINALLY_BY' => '最后来自:', + 'LBL_ADVANCED_FILTER' => '进阶规则', + 'LBL_STANDARD_FILTER' => '标准规则', + 'LBL_SF_COLUMNS' => '字段', + 'LBL_SF_STARTDATE' => '开始日期', + 'LBL_SF_ENDDATE' => '结束日期', +'LBL_AF_HDR1' => '设定搜寻条件来缩小范围', + 'LBL_AF_HDR2' => '您可以再第三个字段输入多个项目来使用规则 "or"', + 'LBL_AF_HDR3' => '您最多可以输入10个项目,以逗号分隔。例如CA,NY,TX,FL会尝试搜寻CA或NY或TX或FL。', + 'LBL_FILTER_OPTIONS' => '规则选项', + 'LBL_CUSTOMIZE_BUTTON' => '自订', + 'LBL_EXPORTPDF_BUTTON' => '汇出成PDF', + 'LBL_APPLYFILTER_BUTTON' => '使用规则', + 'LBL_GENERATED_REPORT' => '产生报表', + 'LBL_GRAND_TOTAL' => '总计', + +//Added for 4.2 Patch I + 'LBL_EXPORTXL_BUTTON' => '汇出到 Excel', + +//Added for 5 Beta + 'LBL_NO_PERMISSION' => '您没有检视这个报表的权限', + 'LBL_SELECT_COLUMNS_TO_GENERATE_REPORTS' => '选择要产生报表的字段', + 'LBL_AVAILABLE_FIELDS' => '可用字段', + 'LBL_SELECTED_FIELDS' => '已选择字段', + 'LBL_CALCULATIONS' => '计算', + 'LBL_SELECT_COLUMNS_TO_TOTAL' => '选择字段总数', + 'LBL_SELECT_FILTERS_TO_STREAMLINE_REPORT_DATA' => '选择报表数据的过滤规则', + 'LBL_SELECT_FILTERS' => '规则', + 'LBL_SELECT_COLUMNS_TO_GROUP_REPORTS' => '选择汇整报表的字段', + 'LBL_BACK_TO_REPORTS' => '回到报表', + 'LBL_SELECT_ANOTHER_REPORT' => '选择另一个报表', + 'LBL_SELECT_COLUMN' => '选择字段', + 'LBL_SELECT_TIME' => '选择时间', + 'LBL_PRINT_REPORT' => '打印报表', + 'LBL_CLICK_HERE' => '点选这里', + 'LBL_TO_ADD_NEW_GROUP' => '新增集合', + 'LBL_CREATE_NEW' => '建立', + 'LBL_REPORT_DETAILS' => '报表细节', + 'LBL_RELATIVE_MODULE' => '关联模块', +'LBL_REPORT_TYPE'=>'报表类型', +'LBL_REPORT_DETAILS'=>'报表细节', + 'LBL_TYPE_THE_NAME' => '输入名称', + 'LBL_DESCRIPTION_FOR_REPORT' => '报表说明', + 'LBL_REPORT_NAME' => '报表名称', + 'LBL_DESCRIPTION' => '说明', + 'LBL_TOOLS' => '工具', + 'LBL_AND' => '且', + 'LBL_ADD_NEW_GROUP' => '新增群组', + 'LBL_REPORT_MODULE' => '报表模块', + 'LBL_SELECT_RELATIVE_MODULE_FOR_REPORT' => '选择要产生报表的相关模块', + 'LBL_SELECT_REPORT_TYPE_BELOW' => '选择下面的报表类型', + 'LBL_TABULAR_FORMAT' => '表格格式', + 'LBL_TABULAR_REPORTS_ARE_SIMPLEST' => '表格格式是最快速的报表产生方式', + 'LBL_SUMMARY_REPORT_VIEW_DATA_WITH_SUBTOTALS' => '摘要报表可以让您检视数据的小计等摘要信息', + 'LBL_FILTERS' => '规则', + 'LBL_MOVE_TO' => '移动到', + 'LBL_RENAME_FOLDER' => '资料夹改名', + 'LBL_DELETE_FOLDER' => '删除数据夹', + + 'Account and Contact Reports' => '客户与联络人报表', + 'Lead Reports' => '准客户报表', + 'Potential Reports' => '潜在机会报表', + 'Activity Reports' => '最近事项报表', + 'HelpDesk Reports' => '问题传票报表', + 'Product Reports' => '产品报表', + 'Quote Reports' => '报价单报表', + 'PurchaseOrder Reports' => '采购订单报表', +'SalesOrder Reports' => '销售订单报表', //Added for SO +'Invoice Reports' => '发票报表', + 'Campaign Reports' => '活动报表', //Added for Campaigns +'Contacts by Accounts' => '按客户显示联络人', + 'Contacts without Accounts' => '没有公司资料的联络人', + 'Contacts by Potentials' => '按潜在机会显示联络人', + 'Contacts related to Accounts' => '与客户有关的联络人', + 'Contacts not related to Accounts' => '与客户无关的联络人', + 'Contacts related to Potentials' => '与潜在机会有关的联络人', + 'Lead by Source' => '按来源显示准客户', + 'Lead Status Report' => '准客户状态报表', + 'Potential Pipeline' => '潜在机会圆饼图', + 'Closed Potentials' => '已结案潜在机会', + 'Potential that have Won' => '成功结案的潜在机会', + 'Tickets by Products' => '按产品显示传票', + 'Tickets by Priority' => '按优先级显示传票', + 'Open Tickets' => '待处理传票', +'Tickets related to Products' => '与产品有关的传票', + 'Tickets that are Open' => '待处理传票', + 'Product Details' => '产品细节', + 'Products by Contacts' => '按联络人显示产品', + 'Product Detailed Report' => '产品细节报表', + 'Products related to Contacts' => '与联络人有关的产品', + 'Open Quotes' => '进行中的报价', + 'Quotes Detailed Report' => '报价细节报表', + 'Quotes that are Open' => '进行中的报价', + 'PurchaseOrder by Contacts' => '按联络人显示采购订单', + 'PurchaseOrder Detailed Report' => '采购订单细节报表', + 'PurchaseOrder related to Contacts' => '与联络人有关的采购订单', + 'Invoice Detailed Report' => '发票细节报表', + 'Last Month Activities' => '上个月的工作状况', + 'This Month Activities' => '这个月的工作状况', + 'Campaign Expectations and Actuals' => '活动的预期与实际状况', //Added for Campaigns + 'SalesOrder Detailed Report' => '销售订单细节报表',//Added for SO + +'LBL_DELETE' => '删除', + 'Create_Reports' => '建立报表', + 'Create_New_Folder' => '建立新数据夹', + 'Move_Reports' => '移动报表', + 'Delete_Report' => '删除报表', + +'Custom' => '自订', + 'Previous FY' => '上一个财务年度', + 'Current FY' => '这个财务年度', + 'Next FY' => '下一个财务年度', + 'Previous FQ' => '上一季', + 'Current FQ' => '这一季', + 'Next FQ' => '下一季', + 'Yesterday' => '昨天', + 'Today' => '今天', + 'Tomorrow' => '明天', + 'Last Week' => '上星期', + 'Current Week' => '这星期', + 'Next Week' => '下星期', + 'Last Month' => '上个月', + 'Current Month' => '这个月', + 'Next Month' => '下个月', + 'Last 7 Days' => '过去7天', + 'Last 30 Days' => '过去30天', + 'Last 60 Days' => '过去60天', + 'Last 90 Days' => '过去90天', + 'Last 120 Days' => '过去120天', + 'Next 7 Days' => '未来7天', + 'Next 30 Days' => '未来30天', + 'Next 60 Days' => '未来60天', + 'Next 90 Days' => '未来90天', + 'Next 120 Days' => '未来120天', +'TITLE_VTIGERCRM_CREATE_REPORT' => 'vtiger CRM - 创建报告', +'TITLE_VTIGERCRM_PRINT_REPORT' => 'vtiger - 打印报告', +'NO_FILTER_SELECTED' => '没有过滤选择', + +'LBL_GENERATE_NOW' => '现在制作', +'Totals'=>'字段名', +'SUM' => '小计', + 'AVG' => '平均', + 'MAX' => '最大', + 'MIN' => '最小', + 'LBL_CUSTOM_REPORTS' => '自订报表', + +'ticketid'=>'传票ID', +'NO_COLUMN'=>'没有栏目提供', +// Added/Updated for vtiger CRM 5.0.4 +'LBL_REPORT_DELETED' => '您要查看的报告已删除。', + +//Added for Reports +'LBL_SHARING'=>'共享', +'SELECT_FILTER_TYPE'=>'选择报告类型', +'LBL_USERS'=>'用户', +'LBL_GROUPS'=>'组', +'LBL_SELECT_FIELDS'=>'选择字段', +'LBL_MEMBERS'=>'成员', +'LBL_RELATED_FIELDS'=>'相关字段', +'LBL_NO_ACCESS'=>' 拒绝访问模块 ', +'LBL_NOT_ACTIVE'=>' 拒绝访问模块 ', +'LBL_PERM_DENIED'=>' 许可被拒绝的报告: ', +'LBL_FLDR_NOT_EMPTY'=>'您正在试图删除文件夹非空,请首先移动或删除其中的的报告。', +'NO_REL_MODULES'=>'您选择的模块没有关相关模块', + +'Contacts_First_Name' =>'联系人的名', +) + +?> diff --git a/oss/vtiger/trunk/modules/Rss/Delete.php b/oss/vtiger/trunk/modules/Rss/Delete.php new file mode 100644 index 00000000..0d5460f6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Delete.php @@ -0,0 +1,31 @@ +pquery($del_query, array($_REQUEST['record'])); + + //code added for returning back to the current view after delete from list view +header("Location: index.php?module=".vtlib_purify($_REQUEST['return_module'])."&action=RssAjax&file=ListView&directmode=ajax"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Rss/Forms.php b/oss/vtiger/trunk/modules/Rss/Forms.php new file mode 100644 index 00000000..13c990a2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Forms.php @@ -0,0 +1,45 @@ +getAllRssFeeds(); +function get_rssfeeds_form() { +global $mod_strings; +global $app_strings; +global $app_list_strings; +global $image_path; + +$oRss = new vtigerRSS(); +$allrsshtml = $oRss->getRSSCategoryHTML(); +//$starred_rss_html = $oRss->getStarredRssFolder(); + +$the_form .= ''; + +$the_form .= $allrsshtml; + +$the_form .= "
    "; +return $the_form; +} + +?> diff --git a/oss/vtiger/trunk/modules/Rss/ListView.html b/oss/vtiger/trunk/modules/Rss/ListView.html new file mode 100644 index 00000000..7b6cf842 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/ListView.html @@ -0,0 +1,45 @@ + + + + + + + + + + + + {RSSFEEDS_TITLE} +
    + {RSSFEEDS} +
    + {RSSDETAILS} +
    + + diff --git a/oss/vtiger/trunk/modules/Rss/ListView.php b/oss/vtiger/trunk/modules/Rss/ListView.php new file mode 100644 index 00000000..b3f23c1a --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/ListView.php @@ -0,0 +1,92 @@ +assign("MOD", $mod_strings); +$rss_form->assign("APP", $app_strings); +$rss_form->assign("THEME",$theme); +$rss_form->assign("IMAGE_PATH",$image_path); +$rss_form->assign("MODULE", $currentModule); +$rss_form->assign("CATEGORY", getParenttab()); + +//<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>// +//$url = 'http://forums/rss.php?name=forums&file=rss'; +//$url = 'http://forums/weblog_rss.php?w=202'; +if(isset($_REQUEST[record])) +{ + $recordid = vtlib_purify($_REQUEST['record']); + $url = $oRss->getRssUrlfromId($recordid); + if($oRss->setRSSUrl($url)) + { + $rss_html = $oRss->getSelectedRssHTML($recordid); + }else + { + $rss_html = "".$mod_strings['LBL_ERROR_MSG'].""; + } + $rss_form->assign("TITLE",gerRssTitle($recordid)); + $rss_form->assign("ID",$recordid); +}else +{ + $rss_form->assign("TITLE",gerRssTitle()); + $rss_html = $oRss->getStarredRssHTML(); + $query = "select rssid from vtiger_rss where starred=1"; + $result = $adb->pquery($query, array()); + $recordid = $adb->query_result($result,0,'rssid'); + $rss_form->assign("ID",$recordid); + $rss_form->assign("DEFAULT",'yes'); +} +if($currentModule == "Rss") +{ + require_once("modules/".$currentModule."/Forms.php"); + if (function_exists('get_rssfeeds_form')) + { + $rss_form->assign("RSSFEEDS", get_rssfeeds_form()); + } +} +$rss_form->assign("RSSDETAILS",$rss_html); +//<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>// +if(isset($_REQUEST['directmode']) && $_REQUEST['directmode'] == 'ajax') + $rss_form->display("RssFeeds.tpl"); +else + $rss_form->display("Rss.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Rss/Popup.html b/oss/vtiger/trunk/modules/Rss/Popup.html new file mode 100644 index 00000000..e538a25f --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Popup.html @@ -0,0 +1,57 @@ + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + +
    Add RSS Feed:
    RSS Feed URL:
    Choose Category: +
    Set as Starred
    + + + + +
    + +
    +

    + +
    + + diff --git a/oss/vtiger/trunk/modules/Rss/Popup.php b/oss/vtiger/trunk/modules/Rss/Popup.php new file mode 100644 index 00000000..c38da112 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Popup.php @@ -0,0 +1,50 @@ +pquery($query, array()); + $query = 'update vtiger_rss set starred=1 where rssid =?'; + $adb->pquery($query, array($_REQUEST["record"])); + echo vtlib_purify($_REQUEST["record"]); +} +elseif(isset($_REQUEST["rssurl"])) +{ + $newRssUrl = str_replace('##amp##','&',$_REQUEST["rssurl"]); + $setstarred = 0; + $oRss = new vtigerRSS(); + if($oRss->setRSSUrl($newRssUrl)) + { + $result = $oRss->saveRSSUrl($newRssUrl,$setstarred); + if($result == false) + { + echo $mod_strings['UNABLE_TO_SAVE'] ; + }else + { + echo $result; + } + }else + { + echo $mod_strings['NOT_A_VALID']; + + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Rss/Rss.js b/oss/vtiger/trunk/modules/Rss/Rss.js new file mode 100644 index 00000000..d9bf2ac8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Rss.js @@ -0,0 +1,60 @@ +/********************************************************************************* +** 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. +* + ********************************************************************************/ + +function star(id, starred) +{ + location.href = "index.php?module=Rss&action=Star&record="+id+"&starred="+starred; + + var elem = document.getElementById("star-"+id); + if(elem.src.indexOf("onstar.gif") != -1) { + elem.src = "themes/images/offstar.gif"; + }else { + elem.src = "themes/images/onstar.gif"; + } +} +function getRequest() { + if ( !httpRequest ) { + httpRequest = new XMLHttpRequest(); + } + return httpRequest; + } +function makeRequest(targetUrl) { + var httpRequest = getRequest(); + httpRequest.open("GET", targetUrl, false, false, false); + httpRequest.send(""); + switch ( httpRequest.status ) { + case 200: + return httpRequest.responseText; + break; + default: + alert(alert_arr.PROBLEM_ACCESSSING_URL+targetUrl+alert_arr.CODE+httpRequest.status); + return null; + break; + } + } +function verify_data(form) { + var isError = false; + var errorMessage = ""; + if (trim(form.rssurl.value) == "") { + isError = true; + errorMessage += "\nRSS Feed URL"; + } + // Here we decide whether to submit the form. + if (isError == true) { + alert(alert_arr.MISSING_REQUIRED_FIELDS + errorMessage); + return false; + } + return true; +} +function display(url,id) +{ + document.getElementById('rsstitle').innerHTML = document.getElementById(id).innerHTML; + document.getElementById('mysite').src = url; +} diff --git a/oss/vtiger/trunk/modules/Rss/Rss.php b/oss/vtiger/trunk/modules/Rss/Rss.php new file mode 100644 index 00000000..9dfc2b58 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Rss.php @@ -0,0 +1,464 @@ +rss = fetch_rss($url); + // Read in our sample feed file + //$data = @implode("",@file($url)); + // Tell feedParser to parse the data + $info = $this->rss->items; + + if(isset($info)) + { + $this->rss_object = $info; + }else + { + return false; + } + if(isset($this->rss)) + { + $this->rss_title = $this->rss->channel["title"]; + $this->rss_link = $this->rss->channel["link"]; + $this->rss_object = $info; + return true; + }else + { + return false; + } + + } + + /** Function to get the List of Rss feeds + * This Function accepts no arguments and returns the listview contents on Sucess + * returns "Sorry: It's not possible to reach RSS URL" if fails + */ + + function getListViewRSSHtml() + { + global $default_charset; + if(isset($this->rss_object)) + { + $i = 0; + foreach($this->rss_object as $key=>$item) + { + $stringConvert = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$item[title]) : $item[title]; + $rss_title= ltrim(rtrim($stringConvert)); + + $i = $i + 1; + $shtml .= "".$rss_title."".$this->rss_title.""; + if($i == 10) + { + return $shtml; + } + } + + return $shtml; + + }else + { + $shtml = "".$mod_strings['LBL_REGRET_MSG'].""; + } + } + + /** Function to get the List of Rss feeds in the Customized Home page + * This Function accepts maximum entries as arguments and returns the listview contents on Success + * returns "Sorry: It's not possible to reach RSS URL" if fails + */ + function getListViewHomeRSSHtml($maxentries) + { + $return_value=Array(); + $return_more=Array(); + if(isset($this->rss_object)) + { + $y = 0; + + foreach($this->rss_object as $key=>$item) + { + $title =$item[title]; + $link = $item[link]; + + if($y == $maxentries) + { + $return_more=Array("Details"=>$return_value,"More"=>$this->rss_link); + return $return_more; + } + $y = $y + 1; + $return_value[]=Array($title,$link); + } + $return_more=Array("Details"=>$return_value,"More"=>$this->rss_link); + return $return_more; + + }else + { + return $return_more; + } + } + + /** Function to save the Rss Feeds + * This Function accepts the RssURl,Starred Status as arguments and + * returns true on sucess + * returns false if fails + */ + function saveRSSUrl($url,$makestarred=0) + { + global $adb; + + if ($url != "") + { + $rsstitle = $this->rss_title; + if($rsstitle == "") + { + $rsstitle = $url; + } + $genRssId = $adb->getUniqueID("vtiger_rss"); + $sSQL = "insert into vtiger_rss (RSSID,RSSURL,RSSTITLE,RSSTYPE,STARRED) values (?,?,?,?,?)"; + $sparams = array($genRssId, $url, $rsstitle, 0, $makestarred); + $result = $adb->pquery($sSQL, $sparams); + if($result) + { + return $genRssId; + }else + { + return false; + } + } + } + function getCRMRssFeeds() + { + global $adb; + global $image_path,$theme; + + $sSQL = "select * from vtiger_rss where rsstype=1"; + $result = $adb->pquery($sSQL, array()); + while($allrssrow = $adb->fetch_array($result)) + { + $shtml .= ""; + if($allrssrow["starred"] == 1) + { + $shtml .= " + "; + }else + { + $shtml .= " + "; + } + $shtml .= "".$allrssrow[rsstitle].""; + $shtml .= " "; + + } + return $shtml; + + } + + function getAllRssFeeds() + { + global $adb; + global $image_path; + + $sSQL = "select * from vtiger_rss where rsstype <> 1"; + $result = $adb->pquery($sSQL, array()); + while($allrssrow = $adb->fetch_array($result)) + { + $shtml .= ""; + if($allrssrow["starred"] == 1) + { + $shtml .= " + "; + }else + { + $shtml .= " + "; + } + $shtml .= "".$allrssrow[rsstitle]." "; + $shtml .= ""; + + } + + return $shtml; + } + + /** Function to get the rssurl for the given id + * This Function accepts the rssid as argument and returns the rssurl for that id + */ + function getRssUrlfromId($rssid) + { + global $adb; + + if($rssid != "") + { + $sSQL = "select * from vtiger_rss where rssid=?"; + $result = $adb->pquery($sSQL, array($rssid)); + $rssrow = $adb->fetch_array($result); + + if(count($rssrow) > 0) + { + $rssurl = $rssrow[rssurl]; + } + } + return $rssurl; + } + + function getRSSHeadings($rssid) + { + global $image_path; + global $adb; + + if($rssid != "") + { + $sSQL = "select * from vtiger_rss where rssid=?"; + $result = $adb->pquery($sSQL, array($rssid)); + $rssrow = $adb->fetch_array($result); + + if(count($rssrow) > 0) + { + $shtml = " + + + +
    "; + if($rssrow[starred] == 1) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + $shtml .= "rss_object[link]."\"> ".$rssrow[rsstitle]." +
    "; + + } + } + return $shtml; + } + + /** Function to get the StarredRSSFeeds lists + * This Function accepts no argument and returns the rss feeds of + * the starred Feeds as HTML strings + */ + function getTopStarredRSSFeeds() + { + global $adb; + global $image_path; + + $sSQL = "select * from vtiger_rss where starred=1"; + $result = $adb->pquery($sSQL, array()); + $shtml .= "Add New Rss"; + + while($allrssrow = $adb->fetch_array($result)) + { + $shtml .= ""; + $shtml .= " ".substr($allrssrow['rsstitle'],0,10)."..."; + } + return $shtml; + } + + /** Function to get the rssfeed lists for the starred Rss feeds + * This Function accepts no argument and returns the rss feeds of + * the starred Feeds as HTML strings + */ + function getStarredRssHTML() + { + global $adb; + global $image_path,$mod_strings; + + $sSQL = "select * from vtiger_rss where starred=1"; + $result = $adb->pquery($sSQL, array()); + while($allrssrow = $adb->fetch_array($result)) + { + if($this->setRSSUrl($allrssrow["rssurl"])) + { + $rss_html = $this->getListViewRSSHtml(); + } + $shtml .= $rss_html; + if(isset($this->rss_object)) + { + if(count($this->rss_object) > 10) + { + $shtml .= " + rss_link\">".$mod_strings['LBL_MORE']." + "; + } + } + $sreturnhtml[] = $shtml; + $shtml = ""; + } + + $recordcount = round((count($sreturnhtml))/2); + $j = $recordcount; + for($i=0;$i<$recordcount;$i++) + { + $starredhtml .= $sreturnhtml[$i].$sreturnhtml[$j]; + $j = $j + 1; + } + $starredhtml = " + + + + ".$starredhtml."
    ".$mod_strings['LBL_SUBJECT']."".$mod_strings['LBL_SENDER']."
    "; + + return $starredhtml; + + } + + /** Function to get the rssfeed lists for the given rssid + * This Function accepts the rssid as argument and returns the rss feeds as HTML strings + */ + function getSelectedRssHTML($rssid) + { + global $adb; + global $image_path, $mod_strings; + + $sSQL = "select * from vtiger_rss where rssid=?"; + $result = $adb->pquery($sSQL, array($rssid)); + while($allrssrow = $adb->fetch_array($result)) + { + if($this->setRSSUrl($allrssrow["rssurl"])) + { + $rss_html = $this->getListViewRSSHtml(); + } + $shtml .= $rss_html; + if(isset($this->rss_object)) + { + if(count($this->rss_object) > 10) + { + $shtml .= " + rss_link\">".$mod_strings['LBL_MORE']." + "; + } + } + $sreturnhtml[] = $shtml; + $shtml = ""; + } + + $recordcount = round((count($sreturnhtml))/2); + $j = $recordcount; + for($i=0;$i<$recordcount;$i++) + { + $starredhtml .= $sreturnhtml[$i].$sreturnhtml[$j]; + $j = $j + 1; + } + $starredhtml = " + + + + ".$starredhtml."
    ".$mod_strings['LBL_SUBJECT']."".$mod_strings['LBL_SENDER']."
    "; + + return $starredhtml; + + } + + /** Function to get the Rss Feeds by Category + * This Function accepts the RssCategory as argument + * and returns the html string for the Rss feeds lists + */ + function getRSSCategoryHTML() + { + global $adb; + global $image_path; + $shtml .= " + + ".$this->getRssFeedsbyCategory()."
    + + "; + + return $shtml; + } + + /** Function to get the Rss Feeds for the Given Category + * This Function accepts the RssCategory as argument + * and returns the html string for the Rss feeds lists + */ + function getRssFeedsbyCategory() + { + + global $adb; + global $image_path,$theme; + + $sSQL = "select * from vtiger_rss"; + $result = $adb->pquery($sSQL, array()); + while($allrssrow = $adb->fetch_array($result)) + { + $shtml .= ""; + $shtml .= ""; + if($allrssrow["starred"] == 1) + { + $shtml .= ""; + }else + { + $shtml .= ""; + } + $shtml .= ""; + $shtml .= "".$allrssrow[rsstitle]." "; + $shtml .= ""; + } + return $shtml; + + } + + // Function to delete an entity with given Id + function trash($module, $id) { + global $log, $adb; + + $del_query = 'DELETE FROM vtiger_rss WHERE rssid=?'; + $adb->pquery($del_query, array($id)); + } + +} + +/** Function to get the rsstitle for the given rssid + * This Function accepts the rssid as an optional argument and returns the title + * if no id is passed it will return the tittle of the starred rss + */ +function gerRssTitle($id='') +{ + global $adb; + if($id == '') { + $query = 'select * from vtiger_rss where starred=1'; + $params = array(); + } else { + $query = 'select * from vtiger_rss where rssid =?'; + $params = array($id); + } + $result = $adb->pquery($query, $params); + $title = $adb->query_result($result,0,'rsstitle'); + return $title; + +} + + + +?> diff --git a/oss/vtiger/trunk/modules/Rss/RssAjax.php b/oss/vtiger/trunk/modules/Rss/RssAjax.php new file mode 100644 index 00000000..74c430d8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/RssAjax.php @@ -0,0 +1,15 @@ + diff --git a/oss/vtiger/trunk/modules/Rss/Save.php b/oss/vtiger/trunk/modules/Rss/Save.php new file mode 100644 index 00000000..34eb5920 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Save.php @@ -0,0 +1,24 @@ +setRSSUrl($newRssUrl)) { + if($oRss->saveRSSUrl($newRssUrl) == false) { + echo $mod_strings['UNABLE_TO_SAVE']; + } +} else { + echo $mod_strings['INVALID_RSS_URL']; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Rss/Star.php b/oss/vtiger/trunk/modules/Rss/Star.php new file mode 100644 index 00000000..04d05e56 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/Star.php @@ -0,0 +1,24 @@ +pquery($sSQL, array($starred, $recordid)); +} +header("Location: index.php?module=Rss&action=index"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Rss/index.php b/oss/vtiger/trunk/modules/Rss/index.php new file mode 100644 index 00000000..f26ed783 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/index.php @@ -0,0 +1,27 @@ + diff --git a/oss/vtiger/trunk/modules/Rss/language/en_us.lang.php b/oss/vtiger/trunk/modules/Rss/language/en_us.lang.php new file mode 100644 index 00000000..04f31957 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/language/en_us.lang.php @@ -0,0 +1,59 @@ +'RSS', +'LBL_MODULE_TITLE'=>'RSS: Home', + +'LBL_NEW_RSS_ENTRY'=>'New RSS News Feed URL:', +'LBL_SEARCH_RSS'=>'Search Title:', +'LBL_NEW_RSS_BUTTON'=>'Add', + +'LBL_STARRED_RSS'=>'Starred Feeds', +'LBL_POP_CRM_RSS'=>'Popular CRM Related Feeds', +'LBL_ALL_RSS_FEEDS'=>'All RSS Feeds', +'LBL_VTIGER_RSS_READER'=>'vtiger RSS Reader', + +'LBL_MORE'=>'More...', +'LBL_SUBJECT'=>'Subject', +'LBL_SENDER'=>'Sender', +'LBL_CATEGORY'=>'Category :', +'LBL_FEED'=>'Feed :', +'LBL_FEED_SOURCES'=> 'Feed Sources', +'LBL_ADD_RSS_FEED'=>'Add RSS Feed', +'LBL_DELETE_BUTTON'=>'Delete', +'LBL_SET_DEFAULT_BUTTON'=>'Set As Default', +'LBL_FEEDS_LIST'=>'Feeds list from :', +'LBL_ERROR_MSG'=>'No RSS Feeds are selected or Your Proxy Settings is not Proper', +'LBL_REGRET_MSG'=>'Sorry: It\'s not possible to reach RSS URL', + +'UNABLE_TO_SAVE'=>'Unable to save the RSS Feed URL', + +// Added/Updated for vtiger CRM 5.0.4 +'NOT_A_VALID'=>'Not a valid RSS Feed or Your Proxy Settings is not Proper', + +// Added after 5.0.4 GA +'INVALID_RSS_URL' => 'Not a valid RSS URL', +'UNABLE_TO_SAVE' => 'Unable to save the Url', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Rss/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Rss/language/zh_cn.lang.php new file mode 100644 index 00000000..1706ea67 --- /dev/null +++ b/oss/vtiger/trunk/modules/Rss/language/zh_cn.lang.php @@ -0,0 +1,52 @@ + '新闻', + 'LBL_MODULE_TITLE' => '新闻:首页', + +'LBL_NEW_RSS_ENTRY' => '新闻RSS资料来源网址:', + 'LBL_SEARCH_RSS' => '标题搜寻:', + 'LBL_NEW_RSS_BUTTON' => '新增', + + 'LBL_STARRED_RSS' => '重要新闻', + 'LBL_POP_CRM_RSS' => 'CRM相关热门新闻', + 'LBL_ALL_RSS_FEEDS' => '所有他站新闻', +'LBL_VTIGER_RSS_READER'=>'vtiger RSS 读者', + +'LBL_MORE' => '更多...', + 'LBL_SUBJECT' => '主旨', + 'LBL_SENDER' => '寄件人', + 'LBL_CATEGORY' => '类别:', + 'LBL_FEED' => '资料来源:', +'LBL_FEED_SOURCES'=> 'Feed 来源', +'LBL_ADD_RSS_FEED' => '新增 RSS 资料来源', +'LBL_DELETE_BUTTON'=>'删除', +'LBL_SET_DEFAULT_BUTTON'=>'预设', +'LBL_FEEDS_LIST' => '资料来源:', + 'LBL_ERROR_MSG' => '没有选择 RSS 来源或是您的代理服务器设定有问题', + 'LBL_REGRET_MSG' => '抱歉:无法取得 RSS 网址', + +'UNABLE_TO_SAVE'=>'无法保存 RSS 资料地址', +'NOT_A_VALID'=>'不是一个有效的rss资料或你的代理服务器设置是不正确的', +); +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/CallRelatedList.php b/oss/vtiger/trunk/modules/SalesOrder/CallRelatedList.php new file mode 100644 index 00000000..b7a1f40d --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/CallRelatedList.php @@ -0,0 +1,71 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['subject']; + $log->debug("id is ".$focus->id); + $log->debug("name is ".$focus->name); + } + + global $mod_strings; + global $app_strings,$currentModule; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + if (isset($focus->name)) $smarty->assign("NAME", $focus->name); + $related_array=getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); + $smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + $smarty->assign("CATEGORY",$category); + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("ID",$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 + + $smarty->assign("MODULE",$currentmodule); + $smarty->assign("SINGLE_MOD",$mod_strings['SalesOrder']); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/CreateSOPDF.php b/oss/vtiger/trunk/modules/SalesOrder/CreateSOPDF.php new file mode 100644 index 00000000..66a6d3e2 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/CreateSOPDF.php @@ -0,0 +1,19 @@ +Output('SalesOrder.pdf','D'); //added file name to make it work in IE, also forces the download giving the user the option to save + +exit(); +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/CustomView.php b/oss/vtiger/trunk/modules/SalesOrder/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/SalesOrder/Delete.php b/oss/vtiger/trunk/modules/SalesOrder/Delete.php new file mode 100644 index 00000000..62227735 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/Delete.php @@ -0,0 +1,39 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/DetailView.php b/oss/vtiger/trunk/modules/SalesOrder/DetailView.php new file mode 100644 index 00000000..5f41c089 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/DetailView.php @@ -0,0 +1,132 @@ +retrieve_entity_info($_REQUEST['record'],"SalesOrder"); + $focus->id = $_REQUEST['record']; + $focus->name=$focus->column_fields['subject']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("SalesOrder detail view"); + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +if (isset($focus->name)) +$smarty->assign("NAME", $focus->name); +else +$smarty->assign("NAME", ""); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +// 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 + +$smarty->assign("SINGLE_MOD", 'SalesOrder'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + + +if(isPermitted("SalesOrder","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); + +$smarty->assign("CREATEPDF","permitted"); + +if(isPermitted("Invoice","EditView",$_REQUEST['record']) == 'yes') + $smarty->assign("CONVERTINVOICE","permitted"); + +if(isPermitted("SalesOrder","Delete",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + +$smarty->assign("MODULE", $currentModule); +$smarty->assign("CONVERTMODE",'sotoinvoice'); +//Get the associated Products and then display above Terms and Conditions +$smarty->assign("ASSOCIATED_PRODUCTS",getDetailAssociatedProducts('SalesOrder',$focus)); + + $tabid = getTabid("SalesOrder"); + $validationData = getDBValidationData($focus->tab_name,$tabid); + $data = split_validationdataArray($validationData); + + $smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); + $smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); + $smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); +$smarty->assign("TODO_PERMISSION",CheckFieldPermission('parent_id','Calendar')); +$smarty->assign("EVENT_PERMISSION",CheckFieldPermission('parent_id','Events')); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("SinglePane_View", $singlepane_view); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("Inventory/InventoryDetailView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/DetailViewAjax.php b/oss/vtiger/trunk/modules/SalesOrder/DetailViewAjax.php new file mode 100644 index 00000000..92af26bf --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/DetailViewAjax.php @@ -0,0 +1,45 @@ +retrieve_entity_info($crmid,"SalesOrder"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("SalesOrder"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/EditView.php b/oss/vtiger/trunk/modules/SalesOrder/EditView.php new file mode 100644 index 00000000..486fd71a --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/EditView.php @@ -0,0 +1,363 @@ +debug("Inside Sales Order EditView"); + +$focus = CRMEntity::getInstance($currentModule); +$smarty = new vtigerCRM_Smarty(); +//added to fix the issue4600 +$searchurl = getBasic_Advance_SearchURL(); +$smarty->assign("SEARCH", $searchurl); +//4600 ends + +$currencyid = fetchCurrency($current_user->id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; +if (isset ($_REQUEST['record']) && $_REQUEST['record'] != '') { + if (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'quotetoso') { + $quoteid = $_REQUEST['record']; + $quote_focus = new Quotes(); + $quote_focus->id = $quoteid; + $quote_focus->retrieve_entity_info($quoteid, "Quotes"); + $focus = getConvertQuoteToSoObject($focus, $quote_focus, $quoteid); + $focus->id = $quoteid; + + // Reset the value w.r.t Quote Selected + $currencyid = $quote_focus->column_fields['currency_id']; + $rate = $quote_focus->column_fields['conversion_rate']; + + //Added to display the Quotes's associated vtiger_products -- when we create SO from Quotes DetailView + $associated_prod = getAssociatedProducts("Quotes", $quote_focus); + $smarty->assign("CONVERT_MODE", $_REQUEST['convertmode']); + $smarty->assign("QUOTE_ID", $quoteid); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $quote_focus->mode); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + + } + elseif (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'update_quote_val') { + //Updating the Selected Quote Value in Edit Mode + foreach ($focus->column_fields as $fieldname => $val) { + if (isset ($_REQUEST[$fieldname])) { + $value = $_REQUEST[$fieldname]; + $focus->column_fields[$fieldname] = $value; + + } + + } + //Handling for dateformat in due_date vtiger_field + if ($focus->column_fields['duedate'] != '') { + $curr_due_date = $focus->column_fields['duedate']; + $focus->column_fields['duedate'] = getDBInsertDateValue($curr_due_date); + } + + $quoteid = $focus->column_fields['quote_id']; + $smarty->assign("QUOTE_ID", $focus->column_fields['quote_id']); + $quote_focus = new Quotes(); + $quote_focus->id = $quoteid; + $quote_focus->retrieve_entity_info($quoteid, "Quotes"); + $focus = getConvertQuoteToSoObject($focus, $quote_focus, $quoteid); + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->name = $focus->column_fields['subject']; + + // Reset the value w.r.t Quote Selected + $currencyid = $quote_focus->column_fields['currency_id']; + $rate = $quote_focus->column_fields['conversion_rate']; + + } else { + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'], "SalesOrder"); + $focus->name = $focus->column_fields['subject']; + } +} else { + if (isset ($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'update_quote_val') { + //Updating the Select Quote Value in Create Mode + foreach ($focus->column_fields as $fieldname => $val) { + if (isset ($_REQUEST[$fieldname])) { + $value = $_REQUEST[$fieldname]; + $focus->column_fields[$fieldname] = $value; + } + + } + //Handling for dateformat in due_date vtiger_field + if ($focus->column_fields['duedate'] != '') { + $curr_due_date = $focus->column_fields['duedate']; + $focus->column_fields['duedate'] = getDBInsertDateValue($curr_due_date); + } + $quoteid = $focus->column_fields['quote_id']; + $quote_focus = new Quotes(); + $quote_focus->id = $quoteid; + $quote_focus->retrieve_entity_info($quoteid, "Quotes"); + $focus = getConvertQuoteToSoObject($focus, $quote_focus, $quoteid); + + // Reset the value w.r.t Quote Selected + $currencyid = $quote_focus->column_fields['currency_id']; + $rate = $quote_focus->column_fields['conversion_rate']; + + //Added to display the Quotes's associated vtiger_products -- when we select Quote in New SO page + if (isset ($_REQUEST['quote_id']) && $_REQUEST['quote_id'] != '') { + $associated_prod = getAssociatedProducts("Quotes", $quote_focus, $focus->column_fields['quote_id']); + } + + $smarty->assign("QUOTE_ID", $focus->column_fields['quote_id']); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $quote_focus->mode); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + } +} + +if (isset ($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $smarty->assign("DUPLICATE_FROM", $focus->id); + $SO_associated_prod = getAssociatedProducts("SalesOrder", $focus); + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +if (isset ($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '') { + $focus->column_fields['potential_id'] = $_REQUEST['potential_id']; + $relatedInfo = getRelatedInfo($_REQUEST['potential_id']); + if (!empty ($relatedInfo)) { + $setype = $relatedInfo["setype"]; + $relID = $relatedInfo["relID"]; + } + if ($setype == 'Accounts') { + $_REQUEST['account_id'] = $relID; + } + elseif ($setype == 'Contacts') { + $_REQUEST['contact_id'] = $relID; + } + $log->debug("Sales Order EditView: Potential Id from the request is " . $_REQUEST['potential_id']); + $associated_prod = getAssociatedProducts("Potentials", $focus, $focus->column_fields['potential_id']); +} + +if (isset ($_REQUEST['product_id']) && $_REQUEST['product_id'] != '') { + $focus->column_fields['product_id'] = $_REQUEST['product_id']; + $associated_prod = getAssociatedProducts("Products", $focus, $focus->column_fields['product_id']); + for ($i=1; $i<=count($associated_prod);$i++) { + $associated_prod_id = $associated_prod[$i]['hdnProductId'.$i]; + $associated_prod_prices = getPricesForProducts($currencyid,array($associated_prod_id),'Products'); + $associated_prod[$i]['listPrice'.$i] = $associated_prod_prices[$associated_prod_id]; + } + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); +} +if (!empty ($_REQUEST['parent_id']) && !empty ($_REQUEST['return_module'])) { + if ($_REQUEST['return_module'] == 'Services') { + $focus->column_fields['product_id'] = $_REQUEST['parent_id']; + $log->debug("Service Id from the request is " . $_REQUEST['parent_id']); + $associated_prod = getAssociatedProducts("Services", $focus, $focus->column_fields['product_id']); + for ($i=1; $i<=count($associated_prod);$i++) { + $associated_prod_id = $associated_prod[$i]['hdnProductId'.$i]; + $associated_prod_prices = getPricesForProducts($currencyid,array($associated_prod_id),'Services'); + $associated_prod[$i]['listPrice'.$i] = $associated_prod_prices[$associated_prod_id]; + } + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + } +} + +// Get Account address if vtiger_account is given +if ((isset ($_REQUEST['account_id'])) && ($_REQUEST['record'] == '') && ($_REQUEST['account_id'] != '') && ($_REQUEST['convertmode'] != 'update_quote_val')) { + require_once ('modules/Accounts/Accounts.php'); + $acct_focus = new Accounts(); + $acct_focus->retrieve_entity_info($_REQUEST['account_id'], "Accounts"); + $focus->column_fields['bill_city'] = $acct_focus->column_fields['bill_city']; + $focus->column_fields['ship_city'] = $acct_focus->column_fields['ship_city']; + //added to fix the issue 4526 + $focus->column_fields['bill_pobox'] = $acct_focus->column_fields['bill_pobox']; + $focus->column_fields['ship_pobox'] = $acct_focus->column_fields['ship_pobox']; + $focus->column_fields['bill_street'] = $acct_focus->column_fields['bill_street']; + $focus->column_fields['ship_street'] = $acct_focus->column_fields['ship_street']; + $focus->column_fields['bill_state'] = $acct_focus->column_fields['bill_state']; + $focus->column_fields['ship_state'] = $acct_focus->column_fields['ship_state']; + $focus->column_fields['bill_code'] = $acct_focus->column_fields['bill_code']; + $focus->column_fields['ship_code'] = $acct_focus->column_fields['ship_code']; + $focus->column_fields['bill_country'] = $acct_focus->column_fields['bill_country']; + $focus->column_fields['ship_country'] = $acct_focus->column_fields['ship_country']; + +} + +$theme_path = "themes/" . $theme . "/"; +$image_path = $theme_path . "images/"; + +$disp_view = getView($focus->mode); +$mode = $focus->mode; +if ($disp_view == 'edit_view') + $smarty->assign("BLOCKS", getBlocks($currentModule, $disp_view, $mode, $focus->column_fields)); +else { + $bas_block = getBlocks($currentModule, $disp_view, $mode, $focus->column_fields, 'BAS'); + $adv_block = getBlocks($currentModule, $disp_view, $mode, $focus->column_fields, 'ADV'); + + $blocks['basicTab'] = $bas_block; + if (is_array($adv_block)) + $blocks['moreTab'] = $adv_block; + + $smarty->assign("BLOCKS", $blocks); + $smarty->assign("BLOCKS_COUNT", count($blocks)); +} +$smarty->assign("OP_MODE", $disp_view); + +$smarty->assign("MODULE", $currentModule); +$smarty->assign("SINGLE_MOD", 'SalesOrder'); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$category = getParentTab(); +$smarty->assign("CATEGORY", $category); + +$log->info("Order view"); + +if (isset ($focus->name)) + $smarty->assign("NAME", $focus->name); +else + $smarty->assign("NAME", ""); + +if (isset ($_REQUEST['convertmode']) && ($_REQUEST['convertmode'] == 'quotetoso' || $_REQUEST['convertmode'] == 'update_quote_val')) { + $txtTax = (($quote_focus->column_fields['txtTax'] != '') ? $quote_focus->column_fields['txtTax'] : '0.000'); + $txtAdj = (($quote_focus->column_fields['txtAdjustment'] != '') ? $quote_focus->column_fields['txtAdjustment'] : '0.000'); + + $associated_prod = getAssociatedProducts("Quotes", $quote_focus); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $focus->mode); +} +elseif ($focus->mode == 'edit') { + $smarty->assign("UPDATEINFO", updateInfo($focus->id)); + $associated_prod = getAssociatedProducts("SalesOrder", $focus); + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $smarty->assign("MODE", $focus->mode); +} +elseif (isset ($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $smarty->assign("ASSOCIATEDPRODUCTS", $SO_associated_prod); + $smarty->assign("AVAILABLE_PRODUCTS", 'true'); + $smarty->assign("MODE", $focus->mode); +} +elseif ((isset ($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '') || (isset ($_REQUEST['product_id']) && $_REQUEST['product_id'] != '')) { + $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod); + $InvTotal = getInventoryTotal($_REQUEST['return_module'], $_REQUEST['return_id']); + $smarty->assign("MODE", $focus->mode); + + //this is to display the Product Details in first row when we create new PO from Product relatedlist + if ($_REQUEST['return_module'] == 'Products') { + $smarty->assign("PRODUCT_ID", vtlib_purify($_REQUEST['product_id'])); + $smarty->assign("PRODUCT_NAME", getProductName($_REQUEST['product_id'])); + $smarty->assign("UNIT_PRICE", vtlib_purify($_REQUEST['product_id'])); + $smarty->assign("QTY_IN_STOCK", getPrdQtyInStck($_REQUEST['product_id'])); + $smarty->assign("VAT_TAX", getProductTaxPercentage("VAT", $_REQUEST['product_id'])); + $smarty->assign("SALES_TAX", getProductTaxPercentage("Sales", $_REQUEST['product_id'])); + $smarty->assign("SERVICE_TAX", getProductTaxPercentage("Service", $_REQUEST['product_id'])); + } +} + +if (isset ($cust_fld)) { + $smarty->assign("CUSTOMFIELD", $cust_fld); +} + +if (isset ($_REQUEST['return_module'])) + $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +else + $smarty->assign("RETURN_MODULE", "SalesOrder"); +if (isset ($_REQUEST['return_action'])) + $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +else + $smarty->assign("RETURN_ACTION", "index"); +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("MODULE", "SalesOrder"); +$smarty->assign("PRINT_URL", "phprint.php?jt=" . session_id() . $GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); + +//if create SO, get all available product taxes and shipping & Handling taxes + +if ($focus->mode != 'edit') { + $tax_details = getAllTaxes('available'); + $sh_tax_details = getAllTaxes('available', 'sh'); +} else { + $tax_details = getAllTaxes('available', '', $focus->mode, $focus->id); + $sh_tax_details = getAllTaxes('available', 'sh', 'edit', $focus->id); +} +$smarty->assign("GROUP_TAXES", $tax_details); +$smarty->assign("SH_TAXES", $sh_tax_details); + +$tabid = getTabid("SalesOrder"); +$validationData = getDBValidationData($focus->tab_name, $tabid); +$data = split_validationdataArray($validationData); + +$smarty->assign("VALIDATION_DATA_FIELDNAME", $data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE", $data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL", $data['fieldlabel']); + +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 '
    ' . getTranslatedString('LBL_DUPLICATE') . ' ' . getTranslatedString($mod_seq_field['label']) . + ' - ' . getTranslatedString('LBL_CLICK') . ' ' . getTranslatedString('LBL_HERE') . ' ' . getTranslatedString('LBL_TO_CONFIGURE') . ' ' . getTranslatedString($mod_seq_field['label']) . ''; + else + $smarty->assign("MOD_SEQ_ID", $autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + +$smarty->assign("CURRENCIES_LIST", getAllCurrencies()); +if ($focus->mode == 'edit' || $_REQUEST['isDuplicate'] == 'true') { + $inventory_cur_info = getInventoryCurrencyInfo('SalesOrder', $focus->id); + $smarty->assign("INV_CURRENCY_ID", $inventory_cur_info['currency_id']); +} else { + $smarty->assign("INV_CURRENCY_ID", $currencyid); +} + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); +if ($focus->mode == 'edit') + $smarty->display("Inventory/InventoryEditView.tpl"); +else + $smarty->display('Inventory/InventoryCreateView.tpl'); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/ListTopSalesOrder.php b/oss/vtiger/trunk/modules/SalesOrder/ListTopSalesOrder.php new file mode 100644 index 00000000..4382b121 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/ListTopSalesOrder.php @@ -0,0 +1,132 @@ +$title,'Header'=>$listview_header,'Entries'=>$listview_entries) where as listview_header and listview_entries are arrays of header and entity values which are returned from function getListViewHeader and getListViewEntries + */ +function getTopSalesOrder($maxval,$calCnt) +{ + require_once("data/Tracker.php"); + require_once('modules/SalesOrder/SalesOrder.php'); + require_once('include/logging.php'); + require_once('include/ListView/ListView.php'); + require_once('include/utils/utils.php'); + require_once('modules/CustomView/CustomView.php'); + + global $current_language,$current_user,$list_max_entries_per_page,$theme,$adb; + $current_module_strings = return_module_language($current_language, 'SalesOrder'); + + $log = LoggerManager::getLogger('so_list'); + + $url_string = ''; + $sorder = ''; + $oCustomView = new CustomView("SalesOrder"); + $customviewcombo_html = $oCustomView->getCustomViewCombo(); + if(isset($_REQUEST['viewname']) == false || $_REQUEST['viewname']=='') + { + if($oCustomView->setdefaultviewid != "") + { + $viewid = $oCustomView->setdefaultviewid; + }else + { + $viewid = "0"; + } + } + + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + //Retreive the list from Database + //<<<<<<<<>>>>>>>> + $date_var = date('Y-m-d'); + + $where = ' and vtiger_crmentity.smownerid='.$current_user->id.' and vtiger_salesorder.duedate >= \''.$date_var.'\''; + $query = getListQuery("SalesOrder",$where); + $query .=" ORDER BY total DESC"; + //<<<<<<<>>>>>>>> + + $query .= " LIMIT " . $adb->sql_escape_string($maxval); + + if($calCnt == 'calculateCnt') { + $list_result_rows = $adb->query(mkCountQuery($query)); + return $adb->query_result($list_result_rows, 0, 'count'); + } + + $list_result = $adb->query($query); + + //Retreiving the no of rows + $noofrows = $adb->num_rows($list_result); + + //Retreiving the start value from request + if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); + } else { + $start = 1; + } + + //Retreive the Navigation array + $navigation_array = getNavigationValues($start, $noofrows, $list_max_entries_per_page); + + if ($navigation_array['start'] == 1) + { + if($noofrows != 0) + $start_rec = $navigation_array['start']; + else + $start_rec = 0; + if($noofrows > $list_max_entries_per_page) + { + $end_rec = $navigation_array['start'] + $list_max_entries_per_page - 1; + } + else + { + $end_rec = $noofrows; + } + + } + else + { + if($navigation_array['next'] > $list_max_entries_per_page) + { + $start_rec = $navigation_array['next'] - $list_max_entries_per_page; + $end_rec = $navigation_array['next'] - 1; + } + else + { + $start_rec = $navigation_array['prev'] + $list_max_entries_per_page; + $end_rec = $noofrows; + } + } + + $focus = new SalesOrder(); + + //Retreive the List View Table Header + $title=array('myTopSalesOrders.gif',$current_module_strings['LBL_MY_TOP_SO'],'home_mytopso'); + $listview_header = getListViewHeader($focus,"SalesOrder",$url_string,$sorder,$order_by,"HomePage",$oCustomView); + $header = Array($listview_header[1],$listview_header[2]); + + $listview_entries = getListViewEntries($focus,"SalesOrder",$list_result,$navigation_array,"HomePage","","EditView","Delete",$oCustomView); + foreach($listview_entries as $crmid=>$valuearray) + { + $entries[$crmid] = Array($valuearray[1],$valuearray[2]); + } + + $search_qry = "&query=true&Fields0=vtiger_salesorder.duedate&Condition0=grteq&Srch_value0=".$date_var."&Fields1=vtiger_crmentity.smownerid&Condition1=is&Srch_value1=".$current_user->column_fields['user_name']."&searchtype=advance&search_cnt=2&matchtype=all"; + + $values=Array('ModuleName'=>'SalesOrder','Title'=>$title,'Header'=>$header,'Entries'=>$entries,'search_qry'=>$search_qry); + if ( ($display_empty_home_blocks && $noofrows == 0 ) || ($noofrows>0) ) + return $values; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/ListView.php b/oss/vtiger/trunk/modules/SalesOrder/ListView.php new file mode 100644 index 00000000..585e46c6 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/ListView.php @@ -0,0 +1,211 @@ +assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'SalesOrder'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$focus = new SalesOrder(); +// Initialize sort by fields +$focus->initSortbyField('SalesOrder'); +// END +$other_text = Array(); +$url_string = ''; // assigning http url string + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to Change/Delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +$sorder = $focus->getSortOrder(); +$order_by = $focus->getOrderBy(); + +$_SESSION['SALESORDER_ORDER_BY'] = $order_by; +$_SESSION['SALESORDER_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + + +if(isset($_REQUEST['query']) && $_REQUEST['query'] != '' && $_REQUEST['query'] == 'true') +{ + + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); + +} + +//<<<>>>>>> +$oCustomView = new CustomView("SalesOrder"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//<<<<>>>> +$smarty->assign("CHANGE_OWNER",getUserslist()); +$smarty->assign("CHANGE_GROUP_OWNER",getGroupslist()); +// Buttons and View options +if(isPermitted('SalesOrder','Delete','') == 'yes') +{ + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +} +if(isPermitted('SalesOrder','EditView','') == 'yes') +{ + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; + $other_text['c_owner'] = $app_strings[LBL_CHANGE_OWNER]; +} +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} + +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("SalesOrder"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"SalesOrder"); +}else +{ + $list_query = getListQuery("SalesOrder"); +} +//<<<<<<<>>>>>>>> + +if(isset($where) && $where != '') +{ + $list_query .= ' and '.$where; +} + +if(isset($order_by) && $order_by != '') +{ + if($order_by == 'smownerid') + { + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY user_name'; + $list_query .= ' ORDER BY user_name '.$sorder; + } + else + { + $tablename = getTableNameForField('SalesOrder',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY '.$tablename.$order_by; + $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); + +//Retreive the List View Table Header +if($viewid !='') +$url_string .="&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"SalesOrder",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search=getSearchListHeaderValues($focus,"SalesOrder",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER", $listview_header_search); + +$listview_entries = getListViewEntries($focus,"SalesOrder",$list_result,$navigation_array,'','&return_module=SalesOrder&return_action=index','EditView','Delete',$oCustomView); +$smarty->assign("LISTENTITY", $listview_entries); +$smarty->assign("SELECT_SCRIPT", $view_script); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"SalesOrder",'index',$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','subject','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($module); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$smarty->assign("BUTTONS", $other_text); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/ListViewPagging.php b/oss/vtiger/trunk/modules/SalesOrder/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/MassEdit.php b/oss/vtiger/trunk/modules/SalesOrder/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/MassEditSave.php b/oss/vtiger/trunk/modules/SalesOrder/MassEditSave.php new file mode 100644 index 00000000..0e1f2a6f --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/Popup.php b/oss/vtiger/trunk/modules/SalesOrder/Popup.php new file mode 100644 index 00000000..033da8e3 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/Popup.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/SalesOrder/RecurringInvoiceHandler.php b/oss/vtiger/trunk/modules/SalesOrder/RecurringInvoiceHandler.php new file mode 100644 index 00000000..939e45d4 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/RecurringInvoiceHandler.php @@ -0,0 +1,50 @@ +getModuleName(); + if ($moduleName == 'SalesOrder') { + $soId = $entityData->getId(); + $data = $entityData->getData(); + if($data['enable_recurring'] == 'on' || $data['enable_recurring'] == 1) { + $frequency = $data['recurring_frequency']; + $startPeriod = getDBInsertDateValue($data['start_period']); + $endPeriod = getDBInsertDateValue($data['end_period']); + $paymentDuration = $data['payment_duration']; + $invoiceStatus = $data['invoicestatus']; + if (isset($frequency) && $frequency != '' && $frequency != '--None--') { + $check_query = "SELECT * FROM vtiger_invoice_recurring_info WHERE salesorderid=?"; + $check_res = $adb->pquery($check_query, array($soId)); + $noofrows = $adb->num_rows($check_res); + if ($noofrows > 0) { + $row = $adb->query_result_rowdata($check_res, 0); + $query = "UPDATE vtiger_invoice_recurring_info SET recurring_frequency=?, start_period=?, end_period=?, payment_duration=?, invoice_status=? WHERE salesorderid=?"; + $params = array($frequency,$startPeriod,$endPeriod,$paymentDuration,$invoiceStatus,$soId); + } else { + $query = "INSERT INTO vtiger_invoice_recurring_info VALUES (?,?,?,?,?,?,?)"; + $params = array($soId,$frequency,$startPeriod,$endPeriod,$startPeriod,$paymentDuration,$invoiceStatus); + } + $adb->pquery($query, $params); + } + } else { + $query = "DELETE FROM vtiger_invoice_recurring_info WHERE salesorderid = ?"; + $adb->pquery($query, array($soId)); + } + } + } +} + + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/SalesOrder.js b/oss/vtiger/trunk/modules/SalesOrder/SalesOrder.js new file mode 100644 index 00000000..a50f9255 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/SalesOrder.js @@ -0,0 +1,49 @@ +/********************************************************************************* +** 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. +* + ********************************************************************************/ + +document.write(""; +exit(); +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/Settings.php b/oss/vtiger/trunk/modules/SalesOrder/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/SalesOrder/TagCloud.php b/oss/vtiger/trunk/modules/SalesOrder/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/SalesOrder/UnifiedSearch.php b/oss/vtiger/trunk/modules/SalesOrder/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/SalesOrder/index.php b/oss/vtiger/trunk/modules/SalesOrder/index.php new file mode 100644 index 00000000..9816c535 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/index.php @@ -0,0 +1,54 @@ + + diff --git a/oss/vtiger/trunk/modules/SalesOrder/language/en_us.lang.php b/oss/vtiger/trunk/modules/SalesOrder/language/en_us.lang.php new file mode 100644 index 00000000..fc2f7eb8 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/language/en_us.lang.php @@ -0,0 +1,209 @@ +'SalesOrder', +'LBL_SO_MODULE_NAME'=>'Sales Order', +'LBL_RELATED_PRODUCTS'=>'Product Details', +'LBL_MODULE_TITLE'=>'SalesOrder: Home', +'LBL_SEARCH_FORM_TITLE'=>'Orders Search', +'LBL_LIST_SO_FORM_TITLE'=>'Sales Order List', +'LBL_NEW_FORM_SO_TITLE'=>'New Sales Order', +'LBL_MEMBER_ORG_FORM_TITLE'=>'Member Organizations', + +'LBL_LIST_ACCOUNT_NAME'=>'Account Name', +'LBL_LIST_CITY'=>'City', +'LBL_LIST_WEBSITE'=>'Website', +'LBL_LIST_STATE'=>'State', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_EMAIL_ADDRESS'=>'Email Address', +'LBL_LIST_CONTACT_NAME'=>'Contact Name', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT'=>'Account:', +'LBL_ACCOUNT_NAME'=>'Account Name:', +'LBL_PHONE'=>'Phone:', +'LBL_WEBSITE'=>'Website:', +'LBL_FAX'=>'Fax:', +'LBL_TICKER_SYMBOL'=>'Ticker Symbol:', +'LBL_OTHER_PHONE'=>'Other Phone:', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_MEMBER_OF'=>'Member of:', +'LBL_EMAIL'=>'Email:', +'LBL_EMPLOYEES'=>'Employees:', +'LBL_OTHER_EMAIL_ADDRESS'=>'Other Email:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_OWNERSHIP'=>'Ownership:', +'LBL_RATING'=>'Rating:', +'LBL_INDUSTRY'=>'Industry:', +'LBL_SIC_CODE'=>'SIC Code:', +'LBL_TYPE'=>'Type:', +'LBL_ANNUAL_REVENUE'=>'Annual Revenue:', +'LBL_ADDRESS_INFORMATION'=>'Address Information', +'LBL_Quote_INFORMATION'=>'Account Information', +'LBL_CUSTOM_INFORMATION'=>'Custom Information', +'LBL_BILLING_ADDRESS'=>'Billing Address:', +'LBL_SHIPPING_ADDRESS'=>'Shipping Address:', +'LBL_ANY_ADDRESS'=>'Any Address:', +'LBL_CITY'=>'City:', +'LBL_STATE'=>'State:', +'LBL_POSTAL_CODE'=>'Postal Code:', +'LBL_COUNTRY'=>'Country:', +'LBL_DESCRIPTION_INFORMATION'=>'Description Information', +'LBL_TERMS_INFORMATION'=>'Terms & Conditions', +'LBL_DESCRIPTION'=>'Description:', +'NTC_COPY_BILLING_ADDRESS'=>'Copy billing address to shipping address', +'NTC_COPY_SHIPPING_ADDRESS'=>'Copy shipping address to billing address', +'NTC_REMOVE_MEMBER_ORG_CONFIRMATION'=>'Are you sure you want to remove this record as a member organization?', +'LBL_DUPLICATE'=>'Potential Duplicate Accounts', +'MSG_DUPLICATE' => 'Creating this vtiger_account may vtiger_potentialy create a duplicate vtiger_account. You may either select an vtiger_account from the list below or you may click on Create New Account to continue creating a new vtiger_account with the previously entered data.', + +'LBL_INVITEE'=>'Contacts', +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the vtiger_account.", + +'LBL_SELECT_ACCOUNT'=>'Select Account', +'LBL_GENERAL_INFORMATION'=>'General Information', + +//for v4 release added +'LBL_NEW_POTENTIAL'=>'New Potential', +'LBL_POTENTIAL_TITLE'=>'Potentials', + +'LBL_NEW_TASK'=>'New Task', +'LBL_TASK_TITLE'=>'Tasks', +'LBL_NEW_CALL'=>'New Call', +'LBL_CALL_TITLE'=>'Calls', +'LBL_NEW_MEETING'=>'New Meeting', +'LBL_MEETING_TITLE'=>'Meetings', +'LBL_NEW_EMAIL'=>'New Email', +'LBL_EMAIL_TITLE'=>'Emails', +'LBL_NEW_CONTACT'=>'New Contact', +'LBL_CONTACT_TITLE'=>'Contacts', + +//Added vtiger_fields after RC1 - Release +'LBL_ALL'=>'All', +'LBL_PROSPECT'=>'Prospect', +'LBL_INVESTOR'=>'Investor', +'LBL_RESELLER'=>'Reseller', +'LBL_PARTNER'=>'Partner', + +// Added for 4GA +'LBL_TOOL_FORM_TITLE'=>'Account Tools', +//Added for 4GA +'Subject'=>'Subject', +'Quote Name'=>'Quote Name', +'Vendor Name'=>'Vendor Name', +'Requisition No'=>'Requisition No', +'Tracking Number'=>'Tracking Number', +'Contact Name'=>'Contact Name', +'Due Date'=>'Due Date', +'Carrier'=>'Carrier', +'Type'=>'Type', +'Sales Tax'=>'Sales Tax', +'Sales Commission'=>'Sales Commission', +'Excise Duty'=>'Excise Duty', +'Total'=>'Total', +'Product Name'=>'Product Name', +'Assigned To'=>'Assigned To', +'Billing Address'=>'Billing Address', +'Shipping Address'=>'Shipping Address', +'Billing City'=>'Billing City', +'Billing State'=>'Billing State', +'Billing Code'=>'Billing Postal Code', +'Billing Country'=>'Billing Country', +'Billing Po Box'=>'Billing PO Box', +'Shipping Po Box'=>'Shipping PO Box', +'Shipping City'=>'Shipping City', +'Shipping State'=>'Shipping State', +'Shipping Code'=>'Shipping Postal Code', +'Shipping Country'=>'Shipping Country', +'City'=>'City', +'State'=>'State', +'Code'=>'Code', +'Country'=>'Country', +'Created Time'=>'Created Time', +'Modified Time'=>'Modified Time', +'Description'=>'Description', +'Potential Name'=>'Potential Name', +'Customer No'=>'Customer No', +'Purchase Order'=>'Purchase Order', +'Vendor Terms'=>'Vendor Terms', +'Pending'=>'Pending', +'Account Name'=>'Account Name', +'Terms & Conditions'=>'Terms & Conditions', +//Quote Info +'LBL_SO_INFORMATION'=>'Sales Order Information', +'LBL_SO'=>'Sales Order:', + + //Added for 5.0 GA +'LBL_SO_FORM_TITLE'=>'Sales', +'LBL_SUBJECT_TITLE'=>'Subject', +'LBL_VENDOR_NAME_TITLE'=>'Vendor Name', +'LBL_TRACKING_NO_TITLE'=>'Tracking No:', +'LBL_SO_SEARCH_TITLE'=>'Sales Order Search', +'LBL_QUOTE_NAME_TITLE'=>'Quote Name', +'Order No'=>'Order No', +'LBL_MY_TOP_SO'=>'My Top Open Sales Orders', +'Status'=>'Status', +'SalesOrder'=>'Sales Order', + +//Added for existing Picklist Entries + +'FedEx'=>'FedEx', +'UPS'=>'UPS', +'USPS'=>'USPS', +'DHL'=>'DHL', +'BlueDart'=>'BlueDart', + +'Created'=>'Created', +'Approved'=>'Approved', +'Delivered'=>'Delivered', +'Cancelled'=>'Cancelled', +'Adjustment'=>'Adjustment', +'Sub Total'=>'Sub Total', + +//Added for Reports (5.0.4) +'Tax Type'=>'Tax Type', +'Discount Percent'=>'Discount Percent', +'Discount Amount'=>'Discount Amount', +'Terms & Conditions'=>'Terms & Conditions', +'S&H Amount'=>'S&H Amount', + +//Added after 5.0.4 GA +'SalesOrder No'=>'SalesOrder No', + +'Recurring Invoice Information' => 'Recurring Invoice Information', +'Enable Recurring' => 'Enable Recurring', +'Frequency' => 'Frequency', +'Start Period' => 'Start Period', +'End Period' => 'End Period', +'Payment Duration' => 'Payment Duration', +'Invoice Status' => 'Invoice Status', + +); + +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/SalesOrder/language/zh_cn.lang.php new file mode 100644 index 00000000..89274f6f --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/language/zh_cn.lang.php @@ -0,0 +1,208 @@ + '销售订单', + 'LBL_SO_MODULE_NAME' => '销售订单', + 'LBL_RELATED_PRODUCTS' => '产品细节', + 'LBL_MODULE_TITLE' => '销售订单:首页', + 'LBL_SEARCH_FORM_TITLE' => '查找订单', + 'LBL_LIST_SO_FORM_TITLE' => '销售订单列表', + 'LBL_NEW_FORM_SO_TITLE' => '新增销售订单', + 'LBL_MEMBER_ORG_FORM_TITLE' => '成员组织', + +'LBL_LIST_ACCOUNT_NAME' => '客户名称', + 'LBL_LIST_CITY' => '乡镇市区', + 'LBL_LIST_WEBSITE' => '网站', + 'LBL_LIST_STATE' => '市(县)', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_EMAIL_ADDRESS' => '电子邮件', + 'LBL_LIST_CONTACT_NAME' => '联络人名称', + +//DON'T CONVERT THESE THEY ARE MAPPINGS +'db_name' => 'LBL_LIST_ACCOUNT_NAME', +'db_website' => 'LBL_LIST_WEBSITE', +'db_billing_address_city' => 'LBL_LIST_CITY', + +//END DON'T CONVERT + +'LBL_ACCOUNT' => '客户:', + 'LBL_ACCOUNT_NAME' => '客户名称:', + 'LBL_PHONE' => '电话:', + 'LBL_WEBSITE' => '网站:', + 'LBL_FAX' => '传真:', + 'LBL_TICKER_SYMBOL' => '传票符号:', + 'LBL_OTHER_PHONE' => '其它电话:', + 'LBL_ANY_PHONE' => '其它电话:', + 'LBL_MEMBER_OF' => '用户组:', + 'LBL_EMAIL' => '电子邮件:', + 'LBL_EMPLOYEES' => '员工人数:', + 'LBL_OTHER_EMAIL_ADDRESS' => '其它电子信箱:', + 'LBL_ANY_EMAIL' => '其它电子信箱:', + 'LBL_OWNERSHIP' => '负责人:', + 'LBL_RATING' => '评分:', + 'LBL_INDUSTRY' => '产业类别:', + 'LBL_SIC_CODE' => '统一编号:', + 'LBL_TYPE' => '类型:', + 'LBL_ANNUAL_REVENUE' => '年收入:', + 'LBL_ADDRESS_INFORMATION' => '住址信息', + 'LBL_Quote_INFORMATION' => '客户信息', + 'LBL_CUSTOM_INFORMATION' => '自订信息', + 'LBL_BILLING_ADDRESS' => '发票住址:', + 'LBL_SHIPPING_ADDRESS' => '送货住址:', + 'LBL_ANY_ADDRESS' => '其它住址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '市(县):', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '省(市/自治区):', + 'LBL_DESCRIPTION_INFORMATION' => '说明信息', + 'LBL_TERMS_INFORMATION' => '期限与条件', + 'LBL_DESCRIPTION' => '说明:', + 'NTC_COPY_BILLING_ADDRESS' => '复制发票地址到送货地址', + 'NTC_COPY_SHIPPING_ADDRESS' => '复制送货地址到送货发票地址', + 'NTC_REMOVE_MEMBER_ORG_CONFIRMATION' => '您确定要删除这笔数据?', + 'LBL_DUPLICATE' => '客户数据重复', + 'MSG_DUPLICATE' => '建立这个客户数据可能与现有数据重复,您可以选择将数据归属于下面其中一个项目中,或是点选建立新客户来透过刚刚输入的数据建立新项目。', + + 'LBL_INVITEE' => '联络人', + 'ERR_DELETE_RECORD' => '必须指定数据编号才能删除公司。', + + 'LBL_SELECT_ACCOUNT' => '选择客户', + 'LBL_GENERAL_INFORMATION' => '一般信息', + +//for v4 release added +'LBL_NEW_POTENTIAL' => '新潜在机会', + 'LBL_POTENTIAL_TITLE' => '潜在机会', + +'LBL_NEW_TASK' => '新任务', + 'LBL_TASK_TITLE' => '任务', + 'LBL_NEW_CALL' => ' 安排电话联系', + 'LBL_CALL_TITLE' => '电话联系', +'LBL_NEW_MEETING' => '新增会议', + 'LBL_MEETING_TITLE' => '会议', + 'LBL_NEW_EMAIL' => '寄发电子邮件', + 'LBL_EMAIL_TITLE' => '电子邮件', + 'LBL_NEW_CONTACT' => '新增联络人', + 'LBL_CONTACT_TITLE' => '联络人', + +//Added vtiger_fields after RC1 - Release + 'LBL_ALL' => '全部', + 'LBL_PROSPECT' => '预期', + 'LBL_INVESTOR' => '投资者', + 'LBL_RESELLER' => '经销商', + 'LBL_PARTNER' => '合作伙伴', + +// Added for 4GA + 'LBL_TOOL_FORM_TITLE' => '客户管理工具', +//Added for 4GA +'Subject' => '主旨', + 'Quote Name' => '报价单名称', + 'Vendor Name' => '厂商名称', + 'Requisition No' => '申请书编号', + 'Tracking Number' => '追踪编号', + 'Contact Name' => '联络人名称', + 'Due Date' => '预计交付日期', + 'Carrier' => '货运商', + 'Type' => '类型', + 'Sales Tax' => '销售税额', + 'Sales Commission' => '销售佣金', + 'Excise Duty' => '货物税', + 'Total' => '总计', + 'Product Name' => '产品名称', + 'Assigned To' => '负责人', +'Billing Address' => '付款住址', + 'Shipping Address' => '送货住址', + 'Billing City' => '[付款住址]乡镇市区', + 'Billing State' => '[付款住址]市(县)', + 'Billing Code' => '[付款住址]邮政编码', + 'Billing Country' => '[付款住址]省(市/自治区)', + 'Billing Po Box' => '[付款住址]采购订单信箱', + 'Shipping Po Box' => '[送货住址]采购订单信箱', + 'Shipping City' => '[送货住址]乡镇市区', + 'Shipping State' => '[送货住址]市(县)', + 'Shipping Code' => '[送货住址]邮政编码', + 'Shipping Country' => '[送货住址]省(市/自治区)', + 'City' => '乡镇市区', + 'State' => '市(县)', + 'Code' => '邮政编码', + 'Country' => '省(市/自治区)', + 'Created Time' => '建立时间', + 'Modified Time' => '修改时间', + 'Description' => '说明', + 'Potential Name' => '潜在机会名称', + 'Customer No' => '客户编号', + 'Purchase Order' => '采购订单', + 'Vendor Terms' => '厂商条件', + 'Pending' => '等待', + 'Account Name' => '客户名称', + 'Terms & Conditions' => '期限与条件', +//Quote Info + 'LBL_SO_INFORMATION' => '销售订单信息', + 'LBL_SO' => '销售订单:', + + //Added for 5.0 GA +'LBL_SO_FORM_TITLE' => '销售', + 'LBL_SUBJECT_TITLE' => '主旨', + 'LBL_VENDOR_NAME_TITLE' => '厂商名称', + 'LBL_TRACKING_NO_TITLE' => '追踪编号:', + 'LBL_SO_SEARCH_TITLE' => '查找销售订单', + 'LBL_QUOTE_NAME_TITLE' => '报价单名称', + 'Order No' => '订单编号', + 'LBL_MY_TOP_SO' => '我的执行中订单', + 'Status' => '订单状态', + 'SalesOrder' => '销售订单', + +//Added for existing Picklist Entries + +'FedEx'=>'FedEx', +'UPS'=>'UPS', +'USPS'=>'USPS', +'DHL'=>'DHL', +'BlueDart'=>'BlueDart', + + 'Created' => '已提交', + 'Approved' => '已审核', + 'Delivered' => '已交付', + 'Cancelled' => '已取消', +'Adjustment'=>'调整', +'Sub Total'=>'小计', +//Added for Reports (5.0.4) +'Tax Type'=>'税务类型', +'Discount Percent'=>'折扣百分比', +'Discount Amount'=>'折扣数额', +'Terms & Conditions'=>'条款及条件', +'S&H Amount'=>'S&H 金额', + +//Added after 5.0.4 GA +'SalesOrder No'=>'订单编号', + +'Recurring Invoice Information' => '周期性发票信息', +'Enable Recurring' => '启用周期', +'Frequency' => '频率', +'Start Period' => '启动期', +'End Period' => '结束期', +'Payment Duration' => '付款期限', +'Invoice Status' => '发票状态', + +); + +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/footer.php b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/footer.php new file mode 100644 index 00000000..eaf16d3c --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/footer.php @@ -0,0 +1,35 @@ +addDescBlock($description, $app_strings["Description"], $descBlock); + +/* ************** End Description *********************** */ + + + +/* **************** Begin Terms ****************** */ +$termBlock=array("107",$top,"53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/header.php b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/header.php new file mode 100644 index 00000000..b7378235 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/header.php @@ -0,0 +1,106 @@ +addImage( $logo_name, $imageBlock); + +// x,y,width +if($org_phone != '') + $phone ="\n".$app_strings['Phone'].":".$org_phone; +$companyBlockPositions=array( "10","23","62" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone."\n".$org_website; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + +// ************** End company information ******************* + + + +// ************* Begin Top-Right Header *************** +// title +$titleBlock=array("140","7"); +$pdf->title( $app_strings['SalesOrder'],"", $titleBlock ); + +$soBubble=array("161","17","20"); +$pdf->addBubbleBlock($quote_name,$app_strings["Quote Name"], $soBubble); + +$poBubble=array("99","17","20"); +$pdf->addBubbleBlock($subject, $app_strings["Subject"], $poBubble); + +// page number +$pageBubble=array("140","17",0); +$pdf->addBubbleBlock($page_num, $app_strings["Page"], $pageBubble); +// ************** End Top-Right Header ***************** + + + +// ************** Begin Addresses ************** +// shipping Address +$shipLocation = array("147","40","61"); +if(trim($ship_street)!='') + $shipText = $ship_street."\n"; +if(trim($ship_city) !='') + $shipText .= $ship_city.", "; +if(trim($ship_state)!='' || trim($ship_code)!= '') + $shipText .= $ship_state." ".$ship_code."\n"; + + $shipText .=$ship_country; +$pdf->addTextBlock( $app_strings["Shipping Address"].':', $shipText, $shipLocation ); + +// billing Address +$billPositions = array("10","51","61"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].':',$billText, $billPositions); +// ********** End Addresses ****************** + + + +/* ******** Begin Invoice Data ************************ */ + +// issue date block +$issueBlock=array("80","37"); +//$pdf->addRecBlock(getDisplayDate(date("Y-m-d")), $app_strings["Issue Date"],$issueBlock); +$pdf->addRecBlock($create_time, $app_strings["Create Date"],$issueBlock); + +// due date block +$dueBlock=array("81","52"); +$pdf->addRecBlock($valid_till, $app_strings["Due Date"],$dueBlock); + +// terms block +$termBlock=array("10","67"); +$pdf->addRecBlock($account_name, $app_strings["Customer Name"], $termBlock); + +// Contact Name block +$conBlock=array("79","67"); +$pdf->addRecBlock($contact_name, $app_strings["Contact Name"],$conBlock); + + + +// vtiger_invoice number block +$invBlock=array("145","67"); +$pdf->addRecBlock($so_no, $app_strings["SO Number"],$invBlock); + +/* ************ End Invoice Data ************************ */ + + + +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/lastpage/body.php b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/lastpage/body.php new file mode 100644 index 00000000..a5883a54 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/lastpage/body.php @@ -0,0 +1,62 @@ +watermark( $app_strings["Thank You"], $waterMarkPositions, $waterMarkRotate ); +$waterMarkPositions=array("30","130"); +$pdf->watermark( $app_strings["For Your Business"], $waterMarkPositions, $waterMarkRotate ); + +// blowing bubbles +$Bubble=array("10","80","170","4"); +$pdf->addBubble("", "", $Bubble); + +$Bubble=array("168","131","12"); +//$pdf->addBubbleBlock("Neat Look", "For A", $Bubble); +$Bubble=array("10","131","12"); +//$pdf->addBubbleBlock("The Corners", "Line Up", $Bubble); + + +/* ************* Begin Totals ************************** */ +$totalBlock=array("59","135"); +$names=array($app_strings["Subtotal"],$app_strings["Tax"],$app_strings["Adjustment"],$app_strings["Total"]); +$totals=array($price_subtotal,$price_salestax,$price_adjustment,$price_total); +$pdf->addTotalsRec($names,$totals,$totalBlock); +/* ************* End Totals *************************** */ + +// lets add an image :) +$imageBlock=array("15","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); +$imageBlock=array("185","95","8","8"); +$pdf->addImage( "sale.jpeg", $imageBlock); + +// descriptions that change sizes! +$descc=count(explode("\n",$description)); +$condc=count(explode("\n",$conditions)); +if( (strlen($description) > 256) || (strlen($conditions) > 256) || $condc >6 || $descc > 6 ) + $num=255; +else + $num=150; + +/* **************** Begin Description ****************** */ +$descBlock=array("10","160","53", $num); +$pdf->addDescBlock($description, $app_strings["Description"], $descBlock); + + +$termBlock=array("107","160","53", $num); +$pdf->addDescBlock($conditions, $app_strings["Terms & Conditions"], $termBlock); + +/* ************** End Terms *********************** */ + + +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/lastpage/footer.php b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/lastpage/footer.php new file mode 100644 index 00000000..629b2abe --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/pdf_templates/lastpage/footer.php @@ -0,0 +1,60 @@ +drawLine($linePos); + $i = (($i+$width)+$pad)-1; +} + + +// company addy +if($org_phone != '') +$phone="\n".$app_strings["Phone"].": ".$org_phone; +if($org_fax != '') + $fax ="\n".$app_strings["Fax"].": ".$org_fax; +$companyBlockPositions=array( "10","220","60" ); +$companyText=$org_address."\n".$org_city.", ".$org_state." ".$org_code." ".$org_country." ".$phone." ".$fax."\n".$org_website ; +$pdf->addTextBlock( $org_name, $companyText ,$companyBlockPositions ); + + +// billing Address +$billPositions = array("85","235","60"); +if(trim($bill_street)!='') + $billText = $bill_street."\n"; +if(trim($bill_city) !='') + $billText .= $bill_city.", "; +if(trim($bill_state)!='' || trim($bill_code)!= '') + $billText .= $bill_state." ".$bill_code."\n"; + + $billText .=$bill_country; +$pdf->addTextBlock($app_strings["Billing Address"].":",$billText, $billPositions); + +// totals +$totalBlock=array("145","235","10", "110"); +$totalText=$app_strings["Subtotal"].": ".$price_subtotal."\n". + $app_strings["Tax"].": ".$price_salestax."\n". + $app_strings["Adjustment"].": ".$price_adjustment."\n". + $app_strings["Total"].": ".$price_total; +$pdf->addDescBlock($totalText, $app_strings["Total Due"], $totalBlock); + +$blurbBlock=array("10","265","150", "60"); +$blockText=$app_strings["Detach_Info"]; +$pdf->addDescBlock($blockText, $app_strings["Instructions"], $blurbBlock); + +?> diff --git a/oss/vtiger/trunk/modules/SalesOrder/updateRelations.php b/oss/vtiger/trunk/modules/SalesOrder/updateRelations.php new file mode 100644 index 00000000..85798501 --- /dev/null +++ b/oss/vtiger/trunk/modules/SalesOrder/updateRelations.php @@ -0,0 +1,48 @@ +pquery("insert into vtiger_senotesrel values (?,?)", array($forCRMRecord,$id)); + else { + $focus->save_related_module($currentModule, $forCRMRecord, $dest_mod, $id); + } + } +} + +header("Location: index.php?action=$action&module=$currentModule&record=".$forCRMRecord."&parenttab=".$parenttab); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/CallRelatedList.php b/oss/vtiger/trunk/modules/ServiceContracts/CallRelatedList.php new file mode 100644 index 00000000..067128ec --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/CallRelatedList.php @@ -0,0 +1,72 @@ +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'); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/CustomView.php b/oss/vtiger/trunk/modules/ServiceContracts/CustomView.php new file mode 100644 index 00000000..aebb8b53 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/CustomView.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/Delete.php b/oss/vtiger/trunk/modules/ServiceContracts/Delete.php new file mode 100644 index 00000000..532347ba --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/Delete.php @@ -0,0 +1,28 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/DetailView.php b/oss/vtiger/trunk/modules/ServiceContracts/DetailView.php new file mode 100644 index 00000000..bc544933 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/DetailView.php @@ -0,0 +1,104 @@ +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 + +$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); + +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($tabid, '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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/DetailViewAjax.php b/oss/vtiger/trunk/modules/ServiceContracts/DetailViewAjax.php new file mode 100644 index 00000000..43da8072 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/DetailViewAjax.php @@ -0,0 +1,39 @@ +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'; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/EditView.php b/oss/vtiger/trunk/modules/ServiceContracts/EditView.php new file mode 100644 index 00000000..053b1f90 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/EditView.php @@ -0,0 +1,134 @@ +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); +} +if(!empty($_REQUEST['service_id'])) { + $serviceObj = CRMEntity::getInstance('Services'); + if(isRecordExists($_REQUEST['service_id'])) { + $serviceObj->retrieve_entity_info($_REQUEST['service_id'], 'Services'); + $focus->column_fields['tracking_unit'] = $serviceObj->column_fields['service_usageunit']; + } +} +if(!empty($_REQUEST['return_id']) && !empty($_REQUEST['return_module'])) { + $invModule = $_REQUEST['return_module']; + $inventoryObj = CRMEntity::getInstance($invModule); + $inventoryObj->retrieve_entity_info($_REQUEST['return_id'], $invModule); + if(empty($_REQUEST['sc_related_to'])) { + if(!empty($inventoryObj->column_fields['account_id'])) { + $focus->column_fields['sc_related_to_type'] = 'Accounts'; + $focus->column_fields['sc_related_to'] = $inventoryObj->column_fields['account_id']; + } else if(!empty($inventoryObj->column_fields['contact_id'])) { + $focus->column_fields['sc_related_to_type'] = 'Contacts'; + $focus->column_fields['sc_related_to'] = $inventoryObj->column_fields['contact_id']; + } + } +} + +$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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + 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'); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ExportRecords.php b/oss/vtiger/trunk/modules/ServiceContracts/ExportRecords.php new file mode 100644 index 00000000..31029bc0 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ExportRecords.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/ServiceContracts/FindDuplicateRecords.php new file mode 100644 index 00000000..b1a36b7b --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/FindDuplicateRecords.php @@ -0,0 +1,106 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    + $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/Import.php b/oss/vtiger/trunk/modules/ServiceContracts/Import.php new file mode 100644 index 00000000..576068f5 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/Import.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ListView.php b/oss/vtiger/trunk/modules/ServiceContracts/ListView.php new file mode 100644 index 00000000..786255b5 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ListView.php @@ -0,0 +1,189 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_PERMISSION]
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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); + +$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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ListViewPagging.php b/oss/vtiger/trunk/modules/ServiceContracts/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/MassEdit.php b/oss/vtiger/trunk/modules/ServiceContracts/MassEdit.php new file mode 100644 index 00000000..b74d3e9c --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/MassEdit.php @@ -0,0 +1,44 @@ +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,'',$focus->non_mass_edit_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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/MassEditSave.php b/oss/vtiger/trunk/modules/ServiceContracts/MassEditSave.php new file mode 100644 index 00000000..61907925 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/MassEditSave.php @@ -0,0 +1,67 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/Popup.php b/oss/vtiger/trunk/modules/ServiceContracts/Popup.php new file mode 100644 index 00000000..40aae3fa --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/Popup.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ProcessDuplicates.php b/oss/vtiger/trunk/modules/ServiceContracts/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/ServiceContracts/QuickCreate.php b/oss/vtiger/trunk/modules/ServiceContracts/QuickCreate.php new file mode 100644 index 00000000..78fe10f6 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/QuickCreate.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/Save.php b/oss/vtiger/trunk/modules/ServiceContracts/Save.php new file mode 100644 index 00000000..b595d9e1 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/Save.php @@ -0,0 +1,53 @@ +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); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ServiceContracts.js b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContracts.js new file mode 100644 index 00000000..3fd0758c --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContracts.js @@ -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. + ************************************************************************************/ diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ServiceContracts.php b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContracts.php new file mode 100644 index 00000000..f22b52f4 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContracts.php @@ -0,0 +1,608 @@ + 'crmid', + 'vtiger_servicecontracts' => 'servicecontractsid', + 'vtiger_servicecontractscf'=>'servicecontractsid'); + + /** + * Mandatory for Listing (Related listview) + */ + var $list_fields = Array ( + /* Format: Field Label => Array(tablename, columnname) */ + // tablename should not have prefix 'vtiger_' + 'Subject' => Array('servicecontracts', 'subject'), + 'Assigned To' => Array('crmentity','smownerid') + ); + var $list_fields_name = Array ( + /* Format: Field Label => fieldname */ + 'Subject' => 'subject', + 'Assigned To' => 'assigned_user_id' + ); + + // Make the field link to detail view + var $list_link_field = 'subject'; + + // For Popup listview and UI type support + var $search_fields = Array( + /* Format: Field Label => Array(tablename, columnname) */ + // tablename should not have prefix 'vtiger_' + 'Subject' => Array('servicecontracts', 'subject') + ); + var $search_fields_name = Array ( + /* Format: Field Label => fieldname */ + 'Subject' => 'subject' + ); + + // For Popup window record selection + var $popup_fields = Array ('subject'); + + // 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 = 'subject'; + + // Column value to use on detail view record text display + var $def_detailview_recname = 'subject'; + + // Required Information for enabling Import feature + var $required_fields = Array ('assigned_user_id'=>1); + + // Used when enabling/disabling the mandatory fields for the module. + // Refers to vtiger_field.fieldname values. + var $mandatory_fields = Array('subject','assigned_user_id'); + + // Callback function list during Importing + var $special_functions = Array('set_import_assigned_user'); + + var $default_order_by = 'subject'; + var $default_sort_order='ASC'; + + function __construct() { + global $log; + $this->column_fields = getColumnFields('ServiceContracts'); + $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; + + $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. + */ + 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,$currentModule; + $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 = 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, 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; + } + + /** + * 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 .= " INNER 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 + */ + function vtlib_handler($moduleName, $eventType) { + + require_once('include/utils/utils.php'); + global $adb; + + if($eventType == 'module.postinstall') { + require_once('vtlib/Vtiger/Module.php'); + + $moduleInstance = Vtiger_Module::getInstance($moduleName); + + $accModuleInstance = Vtiger_Module::getInstance('Accounts'); + $accModuleInstance->setRelatedList($moduleInstance,'Service Contracts',array('add'),'get_dependents_list'); + + $conModuleInstance = Vtiger_Module::getInstance('Contacts'); + $conModuleInstance->setRelatedList($moduleInstance,'Service Contracts',array('add'),'get_dependents_list'); + + // Initialize module sequence for the module + $adb->pquery("INSERT into vtiger_modentity_num values(?,?,?,?,?,?)",array($adb->getUniqueId("vtiger_modentity_num"),$moduleName,'SERCON',1,1,1)); + + // Make the picklist value 'Complete' for status as non-editable + $adb->query("UPDATE vtiger_contract_status SET presence=0 WHERE contract_status='Complete'"); + + // Mark the module as Standard module + $adb->pquery('UPDATE vtiger_tab SET customized=0 WHERE name=?', array($moduleName)); + + } else if($eventType == 'module.disabled') { + $em = new VTEventsManager($adb); + $em->setHandlerInActive('ServiceContractsHandler'); + + } else if($eventType == 'module.enabled') { + $em = new VTEventsManager($adb); + $em->setHandlerActive('ServiceContractsHandler'); + + } else if($eventType == 'module.preuninstall') { + // TODO Handle actions when this module is about to be deleted. + } else if($eventType == 'module.preupdate') { + // TODO Handle actions before this module is updated. + } else if($eventType == '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) { + parent::save_related_module($module, $crmid, $with_module, $with_crmid); + if ($with_module == 'HelpDesk') { + $this->updateHelpDeskRelatedTo($crmid,$with_crmid); + $this->updateServiceContractState($crmid); + } + } + + // Function to Update the parent_id of HelpDesk with sc_related_to of ServiceContracts if the parent_id is not set. + function updateHelpDeskRelatedTo($focusId, $entityIds) { + global $log; + $log->debug("Entering into function updateHelpDeskRelatedTo(".$entityIds.")."); + + if(!is_array($entityIds)) $entityIds = array($entityIds); + $selectTicketsQuery = "SELECT ticketid FROM vtiger_troubletickets WHERE (parent_id IS NULL OR parent_id = 0) AND ticketid IN (" . generateQuestionMarks($entityIds) .")"; + $selectTicketsResult = $this->db->pquery($selectTicketsQuery, array($entityIds)); + $noOfTickets = $this->db->num_rows($selectTicketsResult); + for($i=0; $i < $noOfTickets; ++$i) { + $ticketId = $this->db->query_result($selectTicketsResult,$i,'ticketid'); + $updateQuery = "UPDATE vtiger_troubletickets, vtiger_servicecontracts SET parent_id=vtiger_servicecontracts.sc_related_to" . + " WHERE vtiger_servicecontracts.sc_related_to IS NOT NULL AND vtiger_servicecontracts.sc_related_to != 0" . + " AND vtiger_servicecontracts.servicecontractsid = ? AND vtiger_troubletickets.ticketid = ?"; + $updateResult = $this->db->pquery($updateQuery, array($focusId, $ticketId)); + } + + $log->debug("Exit from function updateHelpDeskRelatedTo(".$entityIds.")"); + } + + // Function to Compute and Update the Used Units and Progress of the Service Contract based on all the related Trouble tickets. + function updateServiceContractState($focusId) { + $this->id = $focusId; + $this->retrieve_entity_info($focusId,'ServiceContracts'); + + $contractTicketsResult = $this->db->pquery("SELECT relcrmid FROM vtiger_crmentityrel WHERE module = 'ServiceContracts' AND crmid = ?" . + " AND relmodule = 'HelpDesk'", array($focusId)); + $noOfTickets = $this->db->num_rows($contractTicketsResult); + $ticketFocus = CRMEntity::getInstance('HelpDesk'); + $totalUsedUnits = 0; + for($i=0; $i < $noOfTickets; ++$i) { + $ticketId = $this->db->query_result($contractTicketsResult, $i, 'relcrmid'); + $ticketFocus->id = $ticketId; + $ticketFocus->retrieve_entity_info($ticketId, 'HelpDesk'); + if (strtolower($ticketFocus->column_fields['ticketstatus']) == 'closed') { + $totalUsedUnits += $this->computeUsedUnits($ticketFocus->column_fields); + } + } + $this->updateUsedUnits($totalUsedUnits); + + $this->calculateProgress(); + } + + // Function to Upate the Used Units of the Service Contract based on the given Ticket id. + function computeUsedUnits($ticketData, $operator='+') { + $trackingUnit = strtolower($this->column_fields['tracking_unit']); + $workingHoursPerDay = 24; + + $usedUnits = 0; + if ($trackingUnit == 'incidents') { + $usedUnits = 1; + } elseif ($trackingUnit == 'days') { + if(!empty($ticketData['days'])) { + $usedUnits = $ticketData['days']; + } elseif(!empty($ticketData['hours'])) { + $usedUnits = $ticketData['hours'] / $workingHoursPerDay; + } + } elseif ($trackingUnit == 'hours') { + if(!empty($ticketData['hours'])) { + $usedUnits = $ticketData['hours']; + } elseif(!empty($ticketData['days'])) { + $usedUnits = $ticketData['days'] * $workingHoursPerDay; + } + } + return $usedUnits; + } + + // Function to Upate the Used Units of the Service Contract. + function updateUsedUnits($usedUnits) { + $this->column_fields['used_units'] = $usedUnits; + $updateQuery = "UPDATE vtiger_servicecontracts SET used_units = $usedUnits WHERE servicecontractsid = ?"; + $this->db->pquery($updateQuery, array($this->id)); + } + + // Function to Calculate the End Date, Planned Duration, Actual Duration and Progress of a Service Contract + function calculateProgress() { + $updateCols = array(); + $updateParams = array(); + + $startDate = $this->column_fields['start_date']; + $dueDate = $this->column_fields['due_date']; + $endDate = $this->column_fields['end_date']; + + $usedUnits = $this->column_fields['used_units']; + $totalUnits = $this->column_fields['total_units']; + + $contractStatus = $this->column_fields['contract_status']; + + // Update the End date if the status is Complete or if the Used Units reaches/exceeds Total Units + // We need to do this first to make sure Actual duration is computed properly + if($contractStatus == 'Complete' || (!empty($usedUnits) && !empty($totalUnits) && $usedUnits >= $totalUnits)) { + if(empty($endDate)) { + $endDate = date('Y-m-d'); + $this->db->pquery('UPDATE vtiger_servicecontracts SET end_date=? WHERE servicecontractsid = ?', array(date('Y-m-d'), $this->id)); + } + } else { + $endDate = null; + $this->db->pquery('UPDATE vtiger_servicecontracts SET end_date=? WHERE servicecontractsid = ?', array(null, $this->id)); + } + + // Calculate the Planned Duration based on Due date and Start date. (in days) + if(!empty($dueDate) && !empty($startDate)) { + $plannedDurationUpdate = " planned_duration = (TO_DAYS(due_date)-TO_DAYS(start_date)+1)"; + } else { + $plannedDurationUpdate = " planned_duration = ''"; + } + array_push($updateCols, $plannedDurationUpdate); + + // Calculate the Actual Duration based on End date and Start date. (in days) + if(!empty($endDate) && !empty($startDate)) { + $actualDurationUpdate = "actual_duration = (TO_DAYS(end_date)-TO_DAYS(start_date)+1)"; + } else { + $actualDurationUpdate = "actual_duration = ''"; + } + array_push($updateCols, $actualDurationUpdate); + + // Update the Progress based on Used Units and Total Units (in percentage) + if(!empty($usedUnits) && !empty($totalUnits)) { + $progressUpdate = 'progress = ?'; + $progressUpdateParams = floatval(($usedUnits * 100) / $totalUnits); + } else { + $progressUpdate = 'progress = ?'; + $progressUpdateParams = null; + } + array_push($updateCols, $progressUpdate); + array_push($updateParams, $progressUpdateParams); + + if(count($updateCols) > 0) { + $updateQuery = 'UPDATE vtiger_servicecontracts SET '. implode(",", $updateCols) .' WHERE servicecontractsid = ?'; + array_push($updateParams, $this->id); + $this->db->pquery($updateQuery, $updateParams); + } + } + + /** + * 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) { + parent::delete_related_module($module, $crmid, $with_module, $with_crmid); + if ($with_module == 'HelpDesk') { + $this->updateServiceContractState($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) { } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ServiceContractsAjax.php b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContractsAjax.php new file mode 100644 index 00000000..efae0a94 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContractsAjax.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/ServiceContractsHandler.php b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContractsHandler.php new file mode 100644 index 00000000..b5c8b9f2 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/ServiceContractsHandler.php @@ -0,0 +1,101 @@ +getModuleName(); + if ($moduleName == 'HelpDesk') { + $ticketId = $entityData->getId(); + $oldStatus = ''; + if(!empty($ticketId)) { + $tktResult = $adb->pquery('SELECT status FROM vtiger_troubletickets WHERE ticketid = ?', array($ticketId)); + if($adb->num_rows($tktResult) > 0) { + $oldStatus = $adb->query_result($tktResult,0,'status'); + } + } + $entityData->oldStatus = $oldStatus; + } + if ($moduleName == 'ServiceContracts') { + $contractId = $entityData->getId(); + $oldTrackingUnit = ''; + if(!empty($contractId)) { + $contractResult = $adb->pquery('SELECT tracking_unit FROM vtiger_servicecontracts WHERE servicecontractsid = ?', array($contractId)); + if($adb->num_rows($contractResult) > 0) { + $oldTrackingUnit = $adb->query_result($contractResult,0,'tracking_unit'); + } + } + $entityData->oldTrackingUnit = $oldTrackingUnit; + } + } + + if($eventName == 'vtiger.entity.aftersave') { + + $moduleName = $entityData->getModuleName(); + + // Update Used Units for the Service Contract, everytime the status of a ticket related to the Service Contract changes + if ($moduleName == 'HelpDesk' && $_REQUEST['return_module'] != 'ServiceContracts') { + $ticketId = $entityData->getId(); + $data = $entityData->getData(); + if($data['ticketstatus'] != $entityData->oldStatus) { + if(strtolower($data['ticketstatus']) == 'closed' || strtolower($entityData->oldStatus) == 'closed') { + if (strtolower($entityData->oldStatus) == 'closed') { + $op = '-'; + } else { + $op = '+'; + } + $contract_tktresult = $adb->pquery("SELECT crmid FROM vtiger_crmentityrel WHERE module = 'ServiceContracts'" . + " AND relmodule = 'HelpDesk' AND relcrmid = ?", array($ticketId)); + $noOfContracts = $adb->num_rows($contract_tktresult); + if($noOfContracts > 0) { + for($i=0;$i<$noOfContracts;$i++) { + $contract_id = $adb->query_result($contract_tktresult,$i,'crmid'); + $scFocus = CRMEntity::getInstance('ServiceContracts'); + $scFocus->id = $contract_id; + $scFocus->retrieve_entity_info($contract_id,'ServiceContracts'); + + $prevUsedUnits = $scFocus->column_fields['used_units']; + if(empty($prevUsedUnits)) $prevUsedUnits = 0; + + $usedUnits = $scFocus->computeUsedUnits($data); + if ($op == '-') { + $totalUnits = $prevUsedUnits - $usedUnits; + } else { + $totalUnits = $prevUsedUnits + $usedUnits; + } + $scFocus->updateUsedUnits($totalUnits); + $scFocus->calculateProgress(); + } + } + } + } + } + + // Update the Planned Duration, Actual Duration, End Date and Progress based on other field values. + if ($moduleName == 'ServiceContracts') { + $contractId = $entityData->getId(); + $data = $entityData->getData(); + $scFocus = CRMEntity::getInstance('ServiceContracts'); + if($data['tracking_unit'] != $entityData->oldTrackingUnit) { // Need to recompute used_units based when tracking_unit changes. + $scFocus->updateServiceContractState($contractId); + } else { + $scFocus->id = $contractId; + $scFocus->retrieve_entity_info($contractId,'ServiceContracts'); + $scFocus->calculateProgress(); + } + } + } + } +} + +?> diff --git a/oss/vtiger/trunk/modules/ServiceContracts/Settings.php b/oss/vtiger/trunk/modules/ServiceContracts/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/TagCloud.php b/oss/vtiger/trunk/modules/ServiceContracts/TagCloud.php new file mode 100644 index 00000000..8343cd5b --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/TagCloud.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/UnifiedSearch.php b/oss/vtiger/trunk/modules/ServiceContracts/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/ServiceContracts/index.php b/oss/vtiger/trunk/modules/ServiceContracts/index.php new file mode 100644 index 00000000..b7add8d8 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/index.php @@ -0,0 +1,15 @@ + diff --git a/oss/vtiger/trunk/modules/ServiceContracts/language/en_us.lang.php b/oss/vtiger/trunk/modules/ServiceContracts/language/en_us.lang.php new file mode 100644 index 00000000..823148e6 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/language/en_us.lang.php @@ -0,0 +1,59 @@ + 'Service Contracts', +'ServiceContracts' => 'Service Contracts', +'SINGLE_ServiceContracts' => 'Service Contract', +'LBL_SERVICE_CONTRACT_INFORMATION' => 'Service Contract Information', +'LBL_CUSTOM_INFORMATION' => 'Custom Information', + +'Contract No' => 'Contract No', +'Assigned To' => 'Assigned To', +'Created Time' => 'Created Time', +'Modified Time' => 'Modified Time', +'Start Date' => 'Start Date', +'Due Date' => 'Due Date', +'End Date' => 'End Date', +'Related to' => 'Related to', +'Tracking Unit' => 'Tracking Unit', +'Total Units' => 'Total Units', +'Used Units' => 'Used Units', +'Subject' => 'Subject', +'Progress'=> 'Progress (in %)', +'Type' => 'Type', +'Planned Duration' => 'Planned Duration (in Days)', +'Actual Duration' => 'Actual Duration (in Days)', +'Status' => 'Status', +'Priority' => 'Priority', + +'Undefined' => 'Undefined', +'In Planning' => 'In Planning', +'In Progress' => 'In Progress', +'On Hold' => 'On Hold', +'Complete' => 'Complete', +'Archived' => 'Archived', + +'Support' => 'Support', +'Services' => 'Services', +'Administrative' => 'Administrative', + +'Low'=>'Low', +'Normal'=>'Normal', +'High'=>'High', + +'None'=>'None', +'Hours'=>'Hours', +'Days'=>'Days', +'Incidents'=>'Incidents', + +); + +?> diff --git a/oss/vtiger/trunk/modules/ServiceContracts/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/ServiceContracts/language/zh_cn.lang.php new file mode 100644 index 00000000..cf29fac5 --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/language/zh_cn.lang.php @@ -0,0 +1,59 @@ + '服务合同', +'ServiceContracts' => '服务合同', +'SINGLE_ServiceContracts' => '服务合同', +'LBL_SERVICE_CONTRACT_INFORMATION' => '服务合同信息', +'LBL_CUSTOM_INFORMATION' => 'Custom Information', + +'Contract No' => 'Contract No', +'Assigned To' => 'Assigned To', +'Created Time' => 'Created Time', +'Modified Time' => 'Modified Time', +'Start Date' => 'Start Date', +'Due Date' => 'Due Date', +'End Date' => 'End Date', +'Related to' => 'Related to', +'Tracking Unit' => 'Tracking Unit', +'Total Units' => 'Total Units', +'Used Units' => 'Used Units', +'Subject' => 'Subject', +'Progress'=> 'Progress (in %)', +'Type' => 'Type', +'Planned Duration' => 'Planned Duration (in Days)', +'Actual Duration' => 'Actual Duration (in Days)', +'Status' => 'Status', +'Priority' => 'Priority', + +'Undefined' => 'Undefined', +'In Planning' => 'In Planning', +'In Progress' => 'In Progress', +'On Hold' => 'On Hold', +'Complete' => 'Complete', +'Archived' => 'Archived', + +'Support' => 'Support', +'Services' => 'Services', +'Administrative' => 'Administrative', + +'Low'=>'Low', +'Normal'=>'Normal', +'High'=>'High', + +'None'=>'None', +'Hours'=>'Hours', +'Days'=>'Days', +'Incidents'=>'Incidents', + +); + +?> diff --git a/oss/vtiger/trunk/modules/ServiceContracts/schema.xml b/oss/vtiger/trunk/modules/ServiceContracts/schema.xml new file mode 100644 index 00000000..0ce5433c --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/schema.xml @@ -0,0 +1,33 @@ + + + + + vtiger_servicecontracts + +
    + + vtiger_servicecontractscf + +
    +
    +
    diff --git a/oss/vtiger/trunk/modules/ServiceContracts/updateRelations.php b/oss/vtiger/trunk/modules/ServiceContracts/updateRelations.php new file mode 100644 index 00000000..9ee5399f --- /dev/null +++ b/oss/vtiger/trunk/modules/ServiceContracts/updateRelations.php @@ -0,0 +1,46 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/AddServiceToPriceBooks.php b/oss/vtiger/trunk/modules/Services/AddServiceToPriceBooks.php new file mode 100644 index 00000000..06f43edd --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/AddServiceToPriceBooks.php @@ -0,0 +1,168 @@ +id,'unit_price') != '0'){ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_UNIT_PRICE_NOT_PERMITTED]
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; + exit(); +} + +$smarty=new vtigerCRM_Smarty; + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("IMAGE_PATH",$image_path); + +$focus = new PriceBooks(); + +//Retreive the list of PriceBooks +$list_query = getListQuery("PriceBooks"); + +$list_query .= ' and vtiger_pricebook.active<>0 ORDER BY pricebookid DESC '; + +$list_result = $adb->query($list_query); +$num_rows = $adb->num_rows($list_result); + +$record_string= "Total No of PriceBooks : ".$num_rows; + +//Retreiving the array of already releated products +$sql1="select vtiger_crmentity.crmid, vtiger_pricebookproductrel.pricebookid,vtiger_service.unit_price + from vtiger_pricebookproductrel inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_pricebookproductrel.productid + inner join vtiger_service on vtiger_service.serviceid=vtiger_pricebookproductrel.productid + where vtiger_crmentity.deleted=0 and vtiger_pricebookproductrel.productid=?"; +$res1 = $adb->pquery($sql1, array($productid)); +$num_prod_rows = $adb->num_rows($res1); +$pbk_array = Array(); +for($i=0; $i<$num_prod_rows; $i++) +{ + $pbkid=$adb->query_result($res1,$i,"pricebookid"); + $pbk_array[$pbkid] = $pbkid; +} + +$pro_unit_price = getUnitPrice($productid, $currentModule); +$prod_price_details = getPriceDetailsForProduct($productid, $pro_unit_price, 'available', $currentModule); + +$prod_cur_price = array(); +for($i=0; $i + + '; + + //we should not display the Add to PriceBook button if there is no pricebooks to associate + if($num_rows != $num_prod_rows) + $other_text .=' '; + +$other_text .=''; +$other_text .=' + + '; + +$smarty->assign("PRICEBOOKLISTHEADER", get_form_header($current_module_strings['LBL_LIST_PRICEBOOK_FORM_TITLE'], $other_text, false )); + + +//List View Table Header +$list_header = ''; +$list_header .= ''; +$list_header .=''; +$list_header .= ''.$mod_strings['LBL_PRICEBOOK'].''; +$list_header .= ''.$app_strings['LBL_CURRENCY'].''; +$list_header .= ''.$mod_strings['LBL_PRODUCT_UNIT_PRICE'].''; +$list_header .= ''.$mod_strings['LBL_PB_LIST_PRICE'].''; +$list_header .= ''; + +$smarty->assign("LISTHEADER", $list_header); + +$list_body =''; +for($i=0; $i<$num_rows; $i++) +{ + $entity_id = $adb->query_result($list_result,$i,"crmid"); + if(! array_key_exists($entity_id, $pbk_array)) + { + $pk_currency_id = $adb->query_result($list_result,$i,"currency_id"); + $pk_currency_name = $adb->query_result($list_result,$i,"currency_name"); + $unit_price = $prod_cur_price[$pk_currency_id]; + $field_name = $entity_id."_listprice"; + $unit_price_array[]="'".$unit_price."'"; + $field_name_array[]="'".$field_name."'"; + + $list_body .= ''; + $list_body .= ''; + $list_body .= ''.$adb->query_result($list_result,$i,"bookname").''; + $list_body .= ''.$pk_currency_name.''; + $list_body .= ''.$unit_price.''; + + $list_body .=''; + if(isPermitted("PriceBooks","EditView","") == 'yes') + $list_body .= ''; + else + $list_body .= ''; + $list_body .= ''; + } + +} + +$smarty->assign("UNIT_PRICE_ARRAY",implode(",",$unit_price_array)); +$smarty->assign("FIELD_NAME_ARRAY",implode(",",$field_name_array)); + +if($order_by !='') + $url_string .="&order_by=".$order_by; +if($sorder !='') + $url_string .="&sorder=".$sorder; + +$smarty->assign("LISTENTITY", $list_body); +$smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); +$smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); +$smarty->assign("RETURN_ID", $productid); +$smarty->assign("CATEGORY", $parenttab); + +$smarty->display("AddProductToPriceBooks.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/AddServicesToPriceBook.php b/oss/vtiger/trunk/modules/Services/AddServicesToPriceBook.php new file mode 100644 index 00000000..4e41fce4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/AddServicesToPriceBook.php @@ -0,0 +1,185 @@ +id); +$parenttab = htmlspecialchars($_REQUEST['parenttab'],ENT_QUOTES,$default_charset); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +require_once($theme_path.'layout_utils.php'); + +if(getFieldVisibilityPermission('Services',$current_user->id,'unit_price') != '0'){ + echo ""; + echo "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_UNIT_PRICE_NOT_PERMITTED]
    + $app_strings[LBL_GO_BACK]
    +
    "; + echo "
    "; + exit(); +} + +$pricebookname = getPriceBookName($pricebook_id); + +$smarty= new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("IMAGE_PATH",$image_path); + +$focus = new Services(); + +if (isset($_REQUEST['order_by'])) + $order_by = $adb->sql_escape_string($_REQUEST['order_by']); + +$url_string = ''; // assigning http url string +$sorder = 'ASC'; // Default sort order +if(isset($_REQUEST['sorder']) && $_REQUEST['sorder'] != '') + $sorder = $adb->sql_escape_string($_REQUEST['sorder']); + + +//Retreive the list of Services +$list_query = getListQuery("Services"); + +if(isset($order_by) && $order_by != '') +{ + $list_query .= ' and vtiger_service.discontinued<>0 ORDER BY '.$order_by.' '.$sorder; +} + +$list_query .= " and vtiger_service.discontinued<>0 group by vtiger_crmentity.crmid"; +$list_result = $adb->query($list_query); +$num_rows = $adb->num_rows($list_result); + +$record_string= "Total No of Service Available : ".$num_rows; + +//Retreiving the array of already releated services +$sql1 = "select productid as serviceid from vtiger_pricebookproductrel + INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_pricebookproductrel.productid + WHERE vtiger_crmentity.setype='Services' AND vtiger_crmentity.deleted=0 AND pricebookid=?"; +$res1 = $adb->pquery($sql1, array($pricebook_id)); +$num_prod_rows = $adb->num_rows($res1); +$prod_array = Array(); +for($i=0; $i<$num_prod_rows; $i++) +{ + $prodid=$adb->query_result($res1,$i,"serviceid"); + $prod_array[$prodid] = $prodid; +} + + +//Buttons Add To PriceBook and Cancel +$other_text = ' + + + + '; + +$other_text .=' + +
      + + + + '; + + //we should not display the Add to PriceBook button if there is no services to associate + if($num_rows != $num_prod_rows && $num_rows > 0) + $other_text .=''; + +$other_text .=' 
    '; + +$smarty->assign("PRODUCTLISTHEADER", get_form_header($current_module_strings['LBL_LIST_FORM_TITLE'], $other_text, false )); + +//Retreive the List View Table Header + +$list_header = ''; +$list_header .= ''; +$list_header .=''; +$list_header .= ''.$mod_strings['LBL_LIST_SERVICE_NAME'].''; +if(getFieldVisibilityPermission('Services', $current_user->id, 'unit_price') == '0') + $list_header .= ''.$mod_strings['LBL_SERVICE_UNIT_PRICE'].''; +$list_header .= ''.$mod_strings['LBL_PB_LIST_PRICE'].''; +$list_header .= ''; + +$smarty->assign("LISTHEADER", $list_header); + + +//if the service is not associated already then we should display that services +$new_prod_array = array(); +$unit_price_array=array(); +$field_name_array=array(); +$entity_id_array =array(); +for($i=0; $i<$num_rows; $i++) +{ + $entity_id = $adb->query_result($list_result,$i,"crmid"); + if(! array_key_exists($entity_id, $prod_array)) + { + $new_prod_array[] = $entity_id; + } + $entity_id_array[$entity_id] = $i; +} +$prod_price_list = getPricesForProducts($currency_id, $new_prod_array, 'Services'); + +$list_body =''; +for($i=0; $iinfo("Services :: Showing the List of services to be added in price book"); + $entity_id = $new_prod_array[$i]; + + $list_body .= ''; + $unit_price = $prod_price_list[$entity_id]; + $field_name = $entity_id."_listprice"; + $unit_price_array[]="'".$unit_price."'"; + $field_name_array[]="'".$field_name."'"; + + $list_body .= ''; + $list_body .= ''.$adb->query_result($list_result,$entity_id_array[$entity_id],"servicename").''; + + if(getFieldVisibilityPermission('Services', $current_user->id, 'unit_price') == '0') + $list_body .= ''.$unit_price.''; + + $list_body .=''; + if(isPermitted("PriceBooks","EditView","") == 'yes') + $list_body .= ''; + else + $list_body .= ''; + $list_body .= ''; +} + +$smarty->assign("UNIT_PRICE_ARRAY",implode(",",$unit_price_array)); +$smarty->assign("FIELD_NAME_ARRAY",implode(",",$field_name_array)); + +if($order_by !='') + $url_string .="&order_by=".$order_by; +if($sorder !='') + $url_string .="&sorder=".$sorder; + +$smarty->assign("LISTENTITY", $list_body); +$smarty->assign("CATEGORY", $parenttab); + +$smarty->display("AddProductsToPriceBook.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/CallRelatedList.php b/oss/vtiger/trunk/modules/Services/CallRelatedList.php new file mode 100644 index 00000000..1cc367c4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/CallRelatedList.php @@ -0,0 +1,77 @@ +retrieve_entity_info($record, $currentModule); + $focus->id = $record; + $service_base_currency = getProductBaseCurrency($focus->id,$currentModule); + } else { + $service_base_currency = fetchCurrency($current_user->id); + } + + $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)); + + $smarty->assign("CURRENCY_ID",$service_base_currency); + + // 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'); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/CustomView.php b/oss/vtiger/trunk/modules/Services/CustomView.php new file mode 100644 index 00000000..aebb8b53 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/CustomView.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Services/Delete.php b/oss/vtiger/trunk/modules/Services/Delete.php new file mode 100644 index 00000000..83411bbd --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/Delete.php @@ -0,0 +1,31 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/DeletePriceBookServiceRel.php b/oss/vtiger/trunk/modules/Services/DeletePriceBookServiceRel.php new file mode 100644 index 00000000..e94aeb6a --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/DeletePriceBookServiceRel.php @@ -0,0 +1,29 @@ +info("Products :: Deleting Price Book - Delete from PriceBook RelatedList"); + $query = "delete from vtiger_pricebookproductrel where pricebookid=? and productid=?"; + $adb->pquery($query, array($return_id, $record)); +} else { + $log->info("Products :: Deleting Price Book"); + $query = "delete from vtiger_pricebookproductrel where pricebookid=? and productid=?"; + $adb->pquery($query, array($record, $return_id)); +} + +header("Location: index.php?module=".$return_module."&action=".$return_module."Ajax&file=$return_action&ajax=delpbprorel&record=".$return_id); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/DetailView.php b/oss/vtiger/trunk/modules/Services/DetailView.php new file mode 100644 index 00000000..5168b638 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/DetailView.php @@ -0,0 +1,116 @@ +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 + +//Added to display the Tax informations +$tax_details = getTaxDetailsForProduct($focus->id); + +for($i=0;$iid); +} +$smarty->assign("TAX_DETAILS", $tax_details); + +$price_details = getPriceDetailsForProduct($focus->id, $focus->unit_price, 'available_associated',$currentModule); +$smarty->assign("PRICE_DETAILS", $price_details); + +$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); + +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($tabid, '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("Inventory/InventoryDetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/DetailViewAjax.php b/oss/vtiger/trunk/modules/Services/DetailViewAjax.php new file mode 100644 index 00000000..43da8072 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/DetailViewAjax.php @@ -0,0 +1,39 @@ +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'; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/EditListPrice.php b/oss/vtiger/trunk/modules/Services/EditListPrice.php new file mode 100644 index 00000000..6cb9eb75 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/EditListPrice.php @@ -0,0 +1,72 @@ + + + + + + + + + + + + +
    '.$mod_strings["LBL_EDITLISTPRICE"].''.$app_strings[
    + + + + +
    + + + + + +
    '.$mod_strings["LBL_EDITLISTPRICE"].'
    +
    + + + + +
    + + +
    + +'; + +echo $output; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/EditView.php b/oss/vtiger/trunk/modules/Services/EditView.php new file mode 100644 index 00000000..fa582e25 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/EditView.php @@ -0,0 +1,182 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if($record) { + $focus->id = $record; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($record, $currentModule); + $service_base_currency = getProductBaseCurrency($focus->id,$currentModule); +} else { + $service_base_currency = fetchCurrency($current_user->id); +} + +if($isduplicate == 'true') { + $focus->id = ''; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +//needed when creating a new service with a default vtiger_vendor name to passed +if (isset($_REQUEST['name']) && is_null($focus->name)) { + $focus->name = $_REQUEST['name']; +} + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') { + $smarty->assign('BLOCKS', getBlocks($currentModule, $disp_view, $focus->mode, $focus->column_fields)); +} else { + $bas_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS'); + $adv_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'ADV'); + + $blocks['basicTab'] = $bas_block; + if(is_array($adv_block)) + $blocks['moreTab'] = $adv_block; + + $smarty->assign("BLOCKS",$blocks); + $smarty->assign("BLOCKS_COUNT",count($blocks)); +} + +$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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + 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 + +//Tax handling (get the available taxes only) - starts +if($focus->mode == 'edit') +{ + $retrieve_taxes = true; + $serviceid = $focus->id; + $tax_details = getTaxDetailsForProduct($serviceid,'available_associated'); +} +elseif($_REQUEST['isDuplicate'] == 'true') +{ + $retrieve_taxes = true; + $serviceid = $_REQUEST['record']; + $tax_details = getTaxDetailsForProduct($serviceid,'available_associated'); +} +else { + $tax_details = getAllTaxes('available'); + $smarty->assign("PROD_MODE", "create"); +} + +for($i=0;$iassign("TAX_DETAILS", $tax_details); +//Tax handling - ends + +$unit_price = $focus->column_fields['unit_price']; +$price_details = getPriceDetailsForProduct($serviceid, $unit_price, 'available',$currentModule); +$smarty->assign("PRICE_DETAILS", $price_details); + +$base_currency = 'curname' . $service_base_currency; +$smarty->assign("BASE_CURRENCY", $base_currency); + +if($focus->mode == 'edit') { + $smarty->display('Inventory/InventoryEditView.tpl'); +} else { + $smarty->display('Inventory/InventoryCreateView.tpl'); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/ExportRecords.php b/oss/vtiger/trunk/modules/Services/ExportRecords.php new file mode 100644 index 00000000..31029bc0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/ExportRecords.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Services/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/Services/FindDuplicateRecords.php new file mode 100644 index 00000000..b1a36b7b --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/FindDuplicateRecords.php @@ -0,0 +1,106 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    + $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/Import.php b/oss/vtiger/trunk/modules/Services/Import.php new file mode 100644 index 00000000..576068f5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/Import.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Services/InventoryPriceAjax.php b/oss/vtiger/trunk/modules/Services/InventoryPriceAjax.php new file mode 100644 index 00000000..0da43c2b --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/InventoryPriceAjax.php @@ -0,0 +1,36 @@ + 0) { + $product_prices = getPricesForProducts($currencyid, $product_ids); +} + +// To get the Price Values in the same order as the Products +for ($i=0;$i diff --git a/oss/vtiger/trunk/modules/Services/InventoryTaxAjax.php b/oss/vtiger/trunk/modules/Services/InventoryTaxAjax.php new file mode 100644 index 00000000..8401ad8f --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/InventoryTaxAjax.php @@ -0,0 +1,68 @@ + + + '.$app_strings['LABEL_SET_TAX_FOR'].' : '.$product_total.' +   + + + '; + +$net_tax_total = 0.00; +for($i=0,$j=$i+1;$i % + + + '.$tax_label.' + + + + + '; +} + +$tax_div .= ''; + +if($associated_tax_count == 0) +{ + $tax_div .= '
    '.$mod_strings['LBL_NO_TAXES_ASSOCIATED'].'.
    '; +} + +$tax_div .= ''; + +echo $tax_div; + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/ListView.php b/oss/vtiger/trunk/modules/Services/ListView.php new file mode 100644 index 00000000..786255b5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/ListView.php @@ -0,0 +1,189 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_PERMISSION]
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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); + +$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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/ListViewPagging.php b/oss/vtiger/trunk/modules/Services/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/MassEdit.php b/oss/vtiger/trunk/modules/Services/MassEdit.php new file mode 100644 index 00000000..7aad35e5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/MassEdit.php @@ -0,0 +1,44 @@ +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,'',$focus->non_mass_edit_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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/MassEditSave.php b/oss/vtiger/trunk/modules/Services/MassEditSave.php new file mode 100644 index 00000000..0e92858e --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/MassEditSave.php @@ -0,0 +1,58 @@ +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(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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/Popup.php b/oss/vtiger/trunk/modules/Services/Popup.php new file mode 100644 index 00000000..40aae3fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/Popup.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/Services/ProcessDuplicates.php b/oss/vtiger/trunk/modules/Services/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Services/QuickCreate.php b/oss/vtiger/trunk/modules/Services/QuickCreate.php new file mode 100644 index 00000000..78fe10f6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/QuickCreate.php @@ -0,0 +1,11 @@ + diff --git a/oss/vtiger/trunk/modules/Services/Save.php b/oss/vtiger/trunk/modules/Services/Save.php new file mode 100644 index 00000000..14e736d5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/Save.php @@ -0,0 +1,59 @@ +mode = $mode; +if($record)$focus->id = $record; + +$currencyid=fetchCurrency($current_user->id); +$rate_symbol = getCurrencySymbolandCRate($currencyid); +$rate = $rate_symbol['rate']; + +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']); +} + +if(isset($_REQUEST['activity_mode'])) $return_action .= '&activity_mode='.vtlib_purify($_REQUEST['activity_mode']); + +header("Location: index.php?action=$return_action&module=$return_module&record=$return_id&parenttab=$parenttab&start=".vtlib_purify($_REQUEST['pagenumber']).$search); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Services/Services.js b/oss/vtiger/trunk/modules/Services/Services.js new file mode 100644 index 00000000..3460f206 --- /dev/null +++ b/oss/vtiger/trunk/modules/Services/Services.js @@ -0,0 +1,341 @@ +/*+********************************************************************************** + * 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. + ************************************************************************************/ +document.write(" +
    + + + + + + + + + + + + + '; + if($mode == 'edit') + $output .= ''; + else + $output .= ''; + + $output .= ' + '; + $output .='' . + '
    Edit BlockAdd Block
    ' . + ' + + + '; + + + } +} + + +if($mode == 'create') +{ + $sharPerCombo = ''; + $sharPerCombo .= ''; +} +elseif($mode == 'edit') +{ + $selected1=''; + $selected2=''; + if($shareInfo[7] == 0) + { + $selected1='selected'; + } + elseif($shareInfo[7] == 1) + { + $selected2='selected'; + } + + $sharPerCombo = ''; + $sharPerCombo .= ''; +} + + +$output.='
    + + + + + + + +
    + + '; + + $output .= ' + '; + $output .='
    + + ' . + '' . + '
    + + '; + + + + $output .= ' + +
    + + + + + + ' . + '' . + '' . + '' . + '
    Block name
    After +
    +
    + + + + +
    +   + +
    + +
    ' . +'' . +''; +echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/AddBlockField.php b/oss/vtiger/trunk/modules/Settings/AddBlockField.php new file mode 100644 index 00000000..20090840 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/AddBlockField.php @@ -0,0 +1,139 @@ +assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("FLD_MODULE", vtlib_purify($_REQUEST['fld_module'])); + +$output = ''; + +$combo_output = ''; + + + +$output .= '
    +
    + + + + + + + + + + + + + + '; + if($mode == 'edit') + $output .= ''; + else + $output .= ''; + + $output .= ' + '; + $output .='
    Edit Field'.getTranslatedString('LBL_MOVE_BLOCK_FIELD').vtlib_purify($_REQUEST['blockname']).'
    + + + +
    + + '; + if($mode != 'edit') + { + $output .= ''; + } + $output .= ' +
    + + +
    '.getTranslatedString('LBL_SELECT_FIELD_TO_MOVE').'
    COMBO_OUTPUT_CHANGE
    +
    + + + + +
    '; + $output .= ''; + $output .= '  + +
    + +
    '; + + +function InStrCount($String,$Find,$CaseSensitive = false) { + $i=0; + $x=0; + while (strlen($String)>=$i) { + unset($substring); + if ($CaseSensitive) { + $Find=strtolower($Find); + $String=strtolower($String); + } + $substring=substr($String,$i,strlen($Find)); + if ($substring==$Find) $x++; + $i++; + } + return $x; + } + +$sql="SELECT fieldid,fieldlabel,fieldname FROM vtiger_field WHERE tabid=? AND block != ? AND block NOT IN (SELECT blockid from vtiger_blocks where blocklabel='LBL_RELATED_PRODUCTS') AND displaytype in (1,2,4) and vtiger_field.presence in (0,2) ORDER BY fieldlabel ASC"; // added by projjwal on 22-11-2007 +$res= $adb->pquery($sql,array($_REQUEST['tabid'], $_REQUEST['blockid'])); + +$combo_output=''; + + +$output=str_replace('COMBO_OUTPUT_CHANGE',$combo_output,$output); + +echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/AddBlockFieldToDB.php b/oss/vtiger/trunk/modules/Settings/AddBlockFieldToDB.php new file mode 100644 index 00000000..9f64b3c3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/AddBlockFieldToDB.php @@ -0,0 +1,36 @@ +pquery($max_fieldsequence,array($blockid)); + $max_seq = $adb->query_result($res,0,'maxsequence'); + $max_seq = $max_seq+1; + foreach($_REQUEST['field_assignid'] as $field_id) { + if($field_id!='') { + $adb->pquery("update vtiger_field set block=?,sequence = ? WHERE fieldid= ?",array($blockid,$max_seq,$field_id)); + $max_seq++; + } + } +} + +header("Location:index.php?module=Settings&action=LayoutBlockList&fld_module=".$fldmodule."&parenttab=".$parenttab."&duplicate=".$dup_error); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/AddBlockToDB.php b/oss/vtiger/trunk/modules/Settings/AddBlockToDB.php new file mode 100644 index 00000000..b516379f --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/AddBlockToDB.php @@ -0,0 +1,57 @@ +pquery("SELECT blocklabel from vtiger_blocks WHERE tabid = ?",array($tabid)); +for($i=0;$i<$adb->num_rows($dup_check_query);$i++){ + $blklbl = $adb->query_result($dup_check_query,$i,'blocklabel'); + $blklbl = getTranslatedString($blklbl); + if($blklbl == $newblocklabel){ + $flag = 1; + break; + } +} +if($flag!=1) { + $sql_seq="select sequence from vtiger_blocks where blockid=?"; + $res_seq= $adb->pquery($sql_seq, array($after_block)); + $row_seq=$adb->fetch_array($res_seq); + $block_sequence=$row_seq['sequence']; + $newblock_sequence=$block_sequence+1; + + $sql_up="update vtiger_blocks set sequence=sequence+1 where tabid=? and sequence > ?"; + $adb->pquery($sql_up, array($tabid,$block_sequence)); + + $sql='select max(blockid) as max_id from vtiger_blocks'; + $res=$adb->query($sql); + $row=$adb->fetch_array($res); + $max_blockid=$row['max_id']+1; + + $sql="INSERT INTO vtiger_blocks (tabid, blockid, sequence, blocklabel) values (?,?,?,?)"; + $params = array($tabid,$max_blockid,$newblock_sequence,$newblocklabel); + $adb->pquery($sql,$params); +} else + $duplicate='yes'; + +header("Location:index.php?module=Settings&action=LayoutBlockList&fld_module=".$fldmodule."&duplicate=".$duplicate."&parenttab=".$parenttab."&mode".$mode); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/AddCustomFieldToDB.php b/oss/vtiger/trunk/modules/Settings/AddCustomFieldToDB.php new file mode 100644 index 00000000..e080ab9b --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/AddCustomFieldToDB.php @@ -0,0 +1,309 @@ +pquery($checkquery,$params); + +if($adb->num_rows($checkresult) > 0) { + + if(isset($_REQUEST['fldLength_'.$blockid])) { + $fldlength=$_REQUEST['fldLength_'.$blockid]; + } else { + $fldlength=''; + } + if(isset($_REQUEST['fldDecimal_'.$blockid])) { + $flddecimal=$_REQUEST['fldDecimal_'.$blockid]; + } else { + $flddecimal=''; + } + if(isset($_REQUEST['fldPickList_'.$blockid])) { + $fldPickList=$_REQUEST['fldPickList_'.$blockid]; + } else { + $fldPickList=''; + } + + header("Location:index.php?module=Settings&action=CustomFieldList&fld_module=".$fldmodule."&fldType=".$fldType."&fldlabel=".$fldlabel."&parenttab=".$parenttab."&duplicate=yes"); + +} else { + if($_REQUEST['fieldid'] == '') { + $max_fieldid = $adb->getUniqueID("vtiger_field"); + $columnName = 'cf_'.$max_fieldid; + $custfld_fieldid=$max_fieldid; + } else { + $max_fieldid = $_REQUEST['column']; + $columnName = $max_fieldid; + $custfld_fieldid= $_REQUEST['fieldid']; + } + + //Assigning the vtiger_table Name + $tableName =''; + if($fldmodule == 'HelpDesk') { + $tableName='vtiger_ticketcf'; + } elseif($fldmodule == 'Products') { + $tableName='vtiger_productcf'; + } elseif($fldmodule == 'Vendors') { + $tableName='vtiger_vendorcf'; + } elseif($fldmodule == 'PriceBooks') { + $tableName='vtiger_pricebookcf'; + } elseif($fldmodule == 'Calendar') { + $tableName='vtiger_activitycf'; + } elseif($fldmodule != '') { + include_once('data/CRMEntity.php'); + $focus = CRMEntity::getInstance($fldmodule); + if (isset($focus->customFieldTable)) { + $tableName=$focus->customFieldTable[0]; + } else { + $tableName= 'vtiger_'.strtolower($fldmodule).'cf'; + } + } + //Assigning the uitype + $fldlength=$_REQUEST['fldLength_'.$blockid]; + $uitype=''; + $fldPickList=''; + if(isset($_REQUEST['fldDecimal_'.$blockid]) && $_REQUEST['fldDecimal_'.$blockid] != '') + { + $decimal=$_REQUEST['fldDecimal_'.$blockid]; + } + else + { + $decimal=0; + } + $type=''; + $uichekdata=''; + if($fldType == 'Text') + { + $uichekdata='V~O~LE~'.$fldlength; + $uitype = 1; + $type = "C(".$fldlength.") default ()"; // adodb type + } + elseif($fldType == 'Number') + { + $uitype = 7; + + //this may sound ridiculous passing decimal but that is the way adodb wants + $dbfldlength = $fldlength + $decimal + 1; + + $type="N(".$dbfldlength.".".$decimal.")"; // adodb type + $uichekdata='N~O~'.$fldlength .','.$decimal; + } + elseif($fldType == 'Percent') + { + $uitype = 9; + $type="N(5.2)"; //adodb type + $uichekdata='N~O~2~2'; + } + elseif($fldType == 'Currency') + { + $uitype = 71; + $dbfldlength = $fldlength + $decimal + 1; + $type="N(".$dbfldlength.".".$decimal.")"; //adodb type + $uichekdata='N~O~'.$fldlength .','.$decimal; + } + elseif($fldType == 'Date') + { + $uichekdata='D~O'; + $uitype = 5; + $type = "D"; // adodb type + + } + elseif($fldType == 'Email') + { + $uitype = 13; + $type = "C(50) default () "; //adodb type + $uichekdata='E~O'; + } + elseif($fldType == 'Phone') + { + $uitype = 11; + $type = "C(30) default () "; //adodb type + + $uichekdata='V~O'; + } + elseif($fldType == 'Picklist') + { + $uitype = 15; + $type = "C(255) default () "; //adodb type + $uichekdata='V~O'; + } + elseif($fldType == 'URL') + { + $uitype = 17; + $type = "C(255) default () "; //adodb type + $uichekdata='V~O'; + } + elseif($fldType == 'Checkbox') + { + $uitype = 56; + $type = "C(3) default 0"; //adodb type + $uichekdata='C~O'; + } + elseif($fldType == 'TextArea') + { + $uitype = 21; + $type = "X"; //adodb type + $uichekdata='V~O'; + } + elseif($fldType == 'MultiSelectCombo') + { + $uitype = 33; + $type = "X"; //adodb type + $uichekdata='V~O'; + } + elseif($fldType == 'Skype') + { + $uitype = 85; + $type = "C(255) default () "; //adodb type + $uichekdata='V~O'; + } + // No Decimal Pleaces Handling + + //1. add the customfield vtiger_table to the vtiger_field vtiger_table as Block4 + //2. fetch the contents of the custom vtiger_field and show in the UI + + $custfld_sequece=$adb->getUniqueID("vtiger_customfield_sequence"); + + $blockid =''; + //get the blockid for this custom block + $blockid = getBlockId($tabid,'LBL_CUSTOM_INFORMATION'); + + if(is_numeric($blockid)) + { + if($mode == "edit" && $_REQUEST['fieldid'] != '') + { + $query = "update vtiger_field set fieldlabel=?, typeofdata=? where fieldid=?"; + $adb->pquery($query, array($fldlabel, $uichekdata, $_REQUEST['fieldid'])); + } + else if($_REQUEST['fieldid'] == '') + { + $query = "insert into vtiger_field (tabid,fieldid,columnname,tablename,generatedtype,uitype,fieldname,fieldlabel, + readonly,presence,selected,maximumlength,sequence,block,displaytype,typeofdata,quickcreate,quickcreatesequence,info_type) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $qparams = array($tabid,$custfld_fieldid,$columnName,$tableName,2,$uitype,$columnName,$fldlabel,0,0,0,100,$custfld_sequece,$blockid,1,$uichekdata,1,0,'BAS'); + $adb->pquery($query, $qparams); + $adb->alterTable($tableName, $columnName." ".$type, "Add_Column"); + + //Inserting values into vtiger_profile2field vtiger_tables + $sql1 = "select * from vtiger_profile"; + $sql1_result = $adb->pquery($sql1, array()); + $sql1_num = $adb->num_rows($sql1_result); + for($i=0; $i<$sql1_num; $i++) + { + $profileid = $adb->query_result($sql1_result,$i,"profileid"); + $sql2 = "insert into vtiger_profile2field values(?,?,?,?,?)"; + $adb->pquery($sql2, array($profileid, $tabid, $custfld_fieldid, 0, 1)); + } + + //Inserting values into def_org vtiger_tables + $sql_def = "insert into vtiger_def_org_field values(?,?,?,?)"; + $adb->pquery($sql_def, array($tabid, $custfld_fieldid, 0, 1)); + + if($fldType == 'Picklist' || $fldType == 'MultiSelectCombo') + { + $columnName = $adb->sql_escape_string($columnName); + // Creating the PickList Table and Populating Values + if($_REQUEST['fieldid'] == '') + { + $qur = "CREATE TABLE vtiger_".$columnName." ( + ".$columnName."id int(19) NOT NULL auto_increment, + ".$columnName." varchar(200) NOT NULL, + presence int(1) NOT NULL default '1', + picklist_valueid int(19) NOT NULL default '0', + PRIMARY KEY (".$columnName."id) + )"; + $adb->pquery($qur, array()); + } + + //Adding a new picklist value in the picklist table + if($mode != 'edit') + { + $picklistid = $adb->getUniqueID("vtiger_picklist"); + $sql="insert into vtiger_picklist values(?,?)"; + $adb->pquery($sql, array($picklistid,$columnName)); + } + $roleid=$current_user->roleid; + $qry="select picklistid from vtiger_picklist where name=?"; + $picklistid = $adb->query_result($adb->pquery($qry, array($columnName)), 0,'picklistid'); + $pickArray = Array(); + $fldPickList = $_REQUEST['fldPickList_'.$blockid]; + $pickArray = explode("\n",$fldPickList); + $count = count($pickArray); + for($i = 0; $i < $count; $i++) + { + $pickArray[$i] = trim(from_html($pickArray[$i])); + if($pickArray[$i] != '') + { + $picklistcount=0; + $sql ="select $columnName from vtiger_$columnName"; + $numrow = $adb->num_rows($adb->pquery($sql, array())); + for($x=0;$x < $numrow ; $x++) + { + $picklistvalues = $adb->query_result($adb->pquery($sql, array()),$x,$columnName); + if($pickArray[$i] == $picklistvalues) + { + $picklistcount++; + } + } + if($picklistcount == 0) + { + $picklist_valueid = getUniquePicklistID(); + $query = "insert into vtiger_".$columnName." values(?,?,?,?)"; + $adb->pquery($query, array($adb->getUniqueID("vtiger_".$columnName),$pickArray[$i],1,$picklist_valueid)); + /*$sql="update vtiger_picklistvalues_seq set id = ?"; + $adb->pquery($sql, array(++$picklist_valueid));*/ + } + $sql = "select picklist_valueid from vtiger_$columnName where $columnName=?"; + $pick_valueid = $adb->query_result($adb->pquery($sql, array($pickArray[$i])),0,'picklist_valueid'); + $sql = "insert into vtiger_role2picklist select roleid,$pick_valueid,$picklistid,$i from vtiger_role"; + $adb->pquery($sql, array()); + } + } + } + //Inserting into LeadMapping table - Jaguar + if($fldmodule == 'Leads' && $_REQUEST['fieldid'] == '') + { + $sql_def = "insert into vtiger_convertleadmapping (leadfid) values(?)"; + $adb->pquery($sql_def, array($custfld_fieldid)); + } + } + } + header("Location:index.php?module=Settings&action=CustomFieldList&fld_module=".$fldmodule."&parenttab=".$parenttab); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/Announcements.php b/oss/vtiger/trunk/modules/Settings/Announcements.php new file mode 100644 index 00000000..59aeb2ee --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/Announcements.php @@ -0,0 +1,36 @@ +pquery($query, array($current_user->id)); +$announcement=$adb->query_result($result,0,'announcement'); +$title_prev=$adb->query_result($result,0,'title'); +$id=$adb->query_result($result,0,'creatorid'); + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("ANNOUNCE",$announcement); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +$smarty->display("Settings/Announcements.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/AuditTrail.php b/oss/vtiger/trunk/modules/Settings/AuditTrail.php new file mode 100644 index 00000000..6e149442 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/AuditTrail.php @@ -0,0 +1,126 @@ +log = LoggerManager::getLogger('audit_trial'); + $this->db = PearDatabase::getInstance(); + } + + var $sortby_fields = Array('module', 'action', 'actiondate', 'recordid'); + + // This is the list of vtiger_fields that are in the lists. + var $list_fields = Array( + 'Module'=>Array('vtiger_audit_trial'=>'module'), + 'Action'=>Array('vtiger_audit_trial'=>'action'), + 'Record'=>Array('vtiger_audit_trial'=>'recordid'), + 'Action Date'=>Array('vtiger_audit_trial'=>'actiondate'), + ); + + var $list_fields_name = Array( + 'Module'=>'module', + 'Action'=>'action', + 'Record'=>'recordid', + 'Action Date'=>'actiondate', + ); + + var $default_order_by = "actiondate"; + var $default_sort_order = 'DESC'; +/** + * Function to get the Headers of Audit Trail Information like Module, Action, RecordID, ActionDate. + * Returns Header Values like Module, Action etc in an array format. +**/ + + function getAuditTrailHeader() + { + global $log; + $log->debug("Entering getAuditTrailHeader() method ..."); + global $app_strings; + + $header_array = array($app_strings['LBL_MODULE'], $app_strings['LBL_ACTION'], $app_strings['LBL_RECORD_ID'], $app_strings['LBL_ACTION_DATE']); + + $log->debug("Exiting getAuditTrailHeader() method ..."); + return $header_array; + + } + +/** + * Function to get the Audit Trail Information values of the actions performed by a particular User. + * @param integer $userid - User's ID + * @param $navigation_array - Array values to navigate through the number of entries. + * @param $sortorder - DESC + * @param $orderby - actiondate + * Returns the audit trail entries in an array format. +**/ + function getAuditTrailEntries($userid, $navigation_array, $sorder='', $orderby='') + { + global $log; + $log->debug("Entering getAuditTrailEntries(".$userid.") method ..."); + global $adb, $current_user; + + if($sorder != '' && $order_by != '') + $list_query = "Select * from vtiger_audit_trial where userid =? order by ".$order_by." ".$sorder; + else + $list_query = "Select * from vtiger_audit_trial where userid =? order by ".$this->default_order_by." ".$this->default_sort_order; + + $result = $adb->pquery($list_query, array($userid)); + $entries_list = array(); + + if($navigation_array['end_val'] != 0) + { + for($i = $navigation_array['start']; $i <= $navigation_array['end_val']; $i++) + { + $entries = array(); + $userid = $adb->query_result($result, $i-1, 'userid'); + + $entries[] = getTranslatedString($adb->query_result($result, $i-1, 'module')); + $entries[] = $adb->query_result($result, $i-1, 'action'); + $entries[] = $adb->query_result($result, $i-1, 'recordid'); + $entries[] = getDisplayDate($adb->query_result($result, $i-1, 'actiondate')); + + $entries_list[] = $entries; + } + $log->debug("Exiting getAuditTrailEntries() method ..."); + return $entries_list; + } + } +} + + +?> diff --git a/oss/vtiger/trunk/modules/Settings/AuditTrailList.php b/oss/vtiger/trunk/modules/Settings/AuditTrailList.php new file mode 100644 index 00000000..67cf12f8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/AuditTrailList.php @@ -0,0 +1,42 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("USERLIST",getUserslist()); + +if($audit_trail == 'true') + $server = 'enabled'; +else + $server = 'disabled'; + +$smarty->assign("AuditStatus", $server); + +$smarty->display('AuditTrailList.tpl'); + + +?> diff --git a/oss/vtiger/trunk/modules/Settings/BackupServerConfig.php b/oss/vtiger/trunk/modules/Settings/BackupServerConfig.php new file mode 100644 index 00000000..900b0e0d --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/BackupServerConfig.php @@ -0,0 +1,150 @@ +pquery($sql_del, array('ftp_backup')); +} + +$smarty = new vtigerCRM_Smarty; +if($_REQUEST['error'] != '') +{ + $smarty->assign("ERROR_MSG",''.vtlib_purify($_REQUEST["error"]).''); +} +if($_REQUEST['error1'] != '') +{ + $smarty->assign("ERROR_STR",''.vtlib_purify($_REQUEST["error1"]).''); +} +$sql="select * from vtiger_systems where server_type = ?"; +$result = $adb->pquery($sql, array('ftp_backup')); +$server = $adb->query_result($result,0,'server'); +$server_username = $adb->query_result($result,0,'server_username'); +$server_password = $adb->query_result($result,0,'server_password'); + +$result = $adb->pquery($sql, array('local_backup')); +$local_server = $adb->query_result($result,0,'server'); +$server_path = $adb->query_result($result,0,'server_path'); + +if(isset($_REQUEST['bkp_server_mode']) && $_REQUEST['bkp_server_mode'] != '') + $smarty->assign("BKP_SERVER_MODE",vtlib_purify($_REQUEST['bkp_server_mode'])); +else + $smarty->assign("BKP_SERVER_MODE",'view'); + +if(isset($_REQUEST['local_server_mode']) && $_REQUEST['local_server_mode'] != '') + $smarty->assign("LOCAL_SERVER_MODE",vtlib_purify($_REQUEST['local_server_mode'])); +else + $smarty->assign("LOCAL_SERVER_MODE",'view'); + +if(isset($_REQUEST['server'])) + $smarty->assign("FTPSERVER",vtlib_purify($_REQUEST['server'])); +else if (isset($server)) + $smarty->assign("FTPSERVER",$server); +if (isset($_REQUEST['server_user'])) + $smarty->assign("FTPUSER",vtlib_purify($_REQUEST['server_user'])); +else if (isset($server_username)) + $smarty->assign("FTPUSER",$server_username); +if (isset($_REQUEST['password'])) + $smarty->assign("FTPPASSWORD",vtlib_purify($_REQUEST['password'])); +else if (isset($server_password)) + $smarty->assign("FTPPASSWORD",$server_password); +if (isset($_REQUEST['path'])) + $smarty->assign("SERVER_BACKUP_PATH",vtlib_purify($_REQUEST['server_path'])); +else if (isset($server_path)) + $smarty->assign("SERVER_BACKUP_PATH",$server_path); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("CMOD", $mod_strings); + +require_once('user_privileges/enable_backup.php'); + +if($enable_local_backup == 'true') + $local_backup_status = 'enabled'; +else + $local_backup_status = 'disabled'; + +if($enable_ftp_backup == 'true') + $ftp_backup_status = 'enabled'; +else + $ftp_backup_status = 'disabled'; + +$smarty->assign("FTP_BACKUP_STATUS", $ftp_backup_status); +$smarty->assign("LOCAL_BACKUP_STATUS", $local_backup_status); + +require_once('include/logging.php'); +require_once('database/DatabaseConnection.php'); +require_once('modules/Users/LoginHistory.php'); +require_once('modules/Users/Users.php'); +require_once('config.php'); +require_once('include/db_backup/backup.php'); +require_once('include/db_backup/ftp.php'); +require_once('include/database/PearDatabase.php'); +require_once('user_privileges/enable_backup.php'); + +global $adb, $enable_backup; + +if((isset($_REQUEST['backupnow']))) +{ + define("dbserver", $dbconfig['db_hostname']); + define("dbuser", $dbconfig['db_username']); + define("dbpass", $dbconfig['db_password']); + define("dbname", $dbconfig['db_name']); + + $path_query = $adb->pquery("SELECT * FROM vtiger_systems WHERE server_type = ?",array('local_backup')); + $path = $adb->query_result($path_query,0,'server_path'); + $currenttime=date("Ymd_His"); + + if(is_dir($path) && is_writable($path)) + { + $fileName = $path.'/backup_'.$currenttime.'.zip'; + $createZip = new createDirZip; + + $createZip->addDirectory('user_privileges/'); + $createZip->get_files_from_folder('user_privileges/', 'user_privileges/'); + + $createZip->addDirectory('storage/'); + $createZip->get_files_from_folder('storage/', 'storage/'); + + $backup_DBFileName = "sqlbackup_".$currenttime.".sql"; + $dbdump = new DatabaseDump(dbserver, dbuser, dbpass); + $dumpfile = 'backup/'.$backup_DBFileName; + $dbdump->save(dbname, $dumpfile) ; + + $filedata = implode("", file('backup/'.$backup_DBFileName)); + $createZip->addFile($filedata,$backup_DBFileName); + + $fd = fopen ($fileName, 'wb'); + $out = fwrite ($fd, $createZip->getZippedfile()); + fclose ($fd); + + $smarty->assign("BACKUP_RESULT", ''. $fileName.''); + } + else + $smarty->assign("BACKUP_RESULT", 'Failed to backup'); +} + +if($_REQUEST['ajax'] == 'true' && $_REQUEST['server_type'] == 'ftp_backup') + $smarty->display("Settings/BackupServerContents.tpl"); +else + $smarty->display("Settings/BackupServer.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/CreateCustomField.php b/oss/vtiger/trunk/modules/Settings/CreateCustomField.php new file mode 100644 index 00000000..00612ace --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CreateCustomField.php @@ -0,0 +1,218 @@ +'Text', + '1'=>'Number', + '2'=>'Percent', + '3'=>'Currency', + '4'=>'Date', + '5'=>'Email', + '6'=>'Phone', + '7'=>'Picklist', + '8'=>'URL', + '9'=>'Checkbox', + '11'=>'MultiSelectCombo', + '12'=>'Skype'); +if(isset($fieldid) && $fieldid!='') +{ + $mode='edit'; + $customfield_columnname=getCustomFieldData($tabid,$fieldid,'columnname'); + $customfield_typeofdata=getCustomFieldData($tabid,$fieldid,'typeofdata'); + $customfield_fieldlabel=getCustomFieldData($tabid,$fieldid,'fieldlabel'); + $customfield_typename=getCustomFieldTypeName($uitype); + $fieldtype_lengthvalue=getFldTypeandLengthValue($customfield_typename,$customfield_typeofdata); + list($fieldtype,$fieldlength,$decimalvalue)= explode(";",$fieldtype_lengthvalue); + $readonly = "readonly"; + if($fieldtype == '7' || $fieldtype == '11') + { + $query = "select * from vtiger_". $adb->sql_escape_string($customfield_columnname); + $result = $adb->pquery($query, array()); + $fldVal=''; + while($row = $adb->fetch_array($result)) + { + $fldVal .= $row[$customfield_columnname]; + $fldVal .= "\n"; + } + $smarty->assign("PICKLISTVALUE",$fldVal); + } + $selectedvalue = $typeVal[$fieldtype]; +} +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("FLD_MODULE", vtlib_purify($_REQUEST['fld_module'])); +if(isset($_REQUEST["duplicate"]) && $_REQUEST["duplicate"] == "yes") +{ + $error=$mod_strings['ERR_CUSTOM_FIELD_WITH_NAME']. $_REQUEST["fldlabel"] .$mod_strings['ERR_ALREADY_EXISTS'] . ' ' .$mod_strings['ERR_SPECIFY_DIFFERENT_LABEL']; + $smarty->assign("DUPLICATE_ERROR", $error); + $customfield_fieldlabel=vtlib_purify($_REQUEST["fldlabel"]); + $fieldlength=vtlib_purify($_REQUEST["fldlength"]); + $decimalvalue=vtlib_purify($_REQUEST["flddecimal"]); + $fldVal = vtlib_purify($_REQUEST["fldPickList"]); + $selectedvalue = $typeVal[$_REQUEST["fldType"]]; +} +elseif($fieldid == '') +{ + $selectedvalue = "0"; +} + +if($mode == 'edit') + $disable_str = 'disabled' ; +else + $disable_str = '' ; + +$output = ''; + +$combo_output = ''; +for($i=0;$i'.$cftextcombo[$i].''; + +} +$output .= '
    +
    + + + + + + + + + + + + + + '; + if($mode == 'edit') + $output .= ''; + else + $output .= ''; + + $output .= ' + '; + $output .='
    '.$mod_strings['LBL_EDIT_FIELD_TYPE'].' - '.$customfield_typename.''.$mod_strings['LBL_ADD_FIELD'].'
    + + + +
    + + '; + if($mode != 'edit') + { + $output .= ''; + } + $output .=' + +
    + + +
    '.$mod_strings['LBL_SELECT_FIELD_TYPE'].'
    +
    '.$combo_output.'
    +
    + + + + + '; + if($mode != 'edit') { + $output .= ' + + + + + + + + + + + '; + } + $output .= ' +
    '.$mod_strings['LBL_LABEL'].'
    '.$mod_strings['LBL_LENGTH'].'
    +
    +
    + + + + +
    +   + +
    + + +
    '; +echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/CreateSharingRule.php b/oss/vtiger/trunk/modules/Settings/CreateSharingRule.php new file mode 100644 index 00000000..efd75f27 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CreateSharingRule.php @@ -0,0 +1,350 @@ +$rolename) + { + $combovalues .=''; + } + + foreach($roleDetails as $roleid=>$rolename) + { + $combovalues .=''; + } + + foreach($grpDetails as $groupid=>$groupname) + { + $combovalues .=''; + } + + $fromComboValues=$combovalues; + $toComboValues=$combovalues; + +} +elseif($mode == 'edit') +{ + + + //constructing the from combo values + $fromtype=$shareInfo[3]; + $fromid=$shareInfo[5]; + + + foreach($roleDetails as $roleid=>$rolename) + { + $selected=''; + + if($fromtype == 'roles') + { + if($roleid == $fromid) + { + $selected='selected'; + } + } + $fromComboValues .=''; + } + + foreach($roleDetails as $roleid=>$rolename) + { + + $selected=''; + if($fromtype == 'rs') + { + if($roleid == $fromid) + { + $selected='selected'; + } + } + + $fromComboValues .=''; + } + + foreach($grpDetails as $groupid=>$groupname) + { + $selected=''; + if($fromtype == 'groups') + { + if($groupid == $fromid) + { + $selected='selected'; + } + } + + + $fromComboValues .=''; + } + + //constructing the to combo values + $totype=$shareInfo[4]; + $toid=$shareInfo[6]; + + + foreach($roleDetails as $roleid=>$rolename) + { + $selected=''; + + if($totype == 'roles') + { + if($roleid == $toid) + { + $selected='selected'; + } + } + $toComboValues .=''; + } + + foreach($roleDetails as $roleid=>$rolename) + { + + $selected=''; + if($totype == 'rs') + { + if($roleid == $toid) + { + $selected='selected'; + } + } + + $toComboValues .=''; + } + + foreach($grpDetails as $groupid=>$groupname) + { + $selected=''; + if($totype == 'groups') + { + if($groupid == $toid) + { + $selected='selected'; + } + } + + + $toComboValues .=''; + } + +} + + + +$relatedmodule=''; +$relatedlistscombo=''; +$relatedModuleSharingArr=getRelatedSharingModules($tabid); +$size=sizeof($relatedModuleSharingArr); +if($size > 0) +{ + if($mode=='edit') + { + $relatedModuleSharingPerrArr=getRelatedModuleSharingPermission($shareid); + } + foreach($relatedModuleSharingArr as $reltabid=>$relmode_shareid) + { + $rel_module=getTabModuleName($reltabid); + $relatedmodule .=$rel_module.'###'; + } + foreach($relatedModuleSharingArr as $reltabid=>$relmode_shareid) + { + $ro_selected=''; + $rw_selected=''; + $rel_module=getTabModuleName($reltabid); + if($mode=='create') + { + $ro_selected='selected'; + } + elseif($mode=='edit') + { + $perr=$relatedModuleSharingPerrArr[$reltabid]; + if($perr == 0) + { + $ro_selected='selected'; + } + elseif($perr == 1) + { + $rw_selected='selected'; + } + } + + $relatedlistscombo.='
    '.$app_strings[$rel_module].' :'; + $relatedlistscombo.='
    +'; + +if($sharing_module == 'Accounts') +{ + $display_module = $app_strings['Accounts'].' & '.$app_strings['Contacts']; +} +else +{ + $display_module = $app_strings[$sharing_module]; +} +$output .= ''; +else + $output .=$mod_strings[LBL_ADD_CUSTOM_RULE].''; +$output .= ' + + +
    '.$display_module.' - '; +if($mode == 'edit') + $output .=$mod_strings[LBL_EDIT_CUSTOM_RULE].''.$app_strings[
    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    '.$mod_strings[LBL_STEP].' 1 : '.$display_module.' '.$app_strings[LBL_LIST_OF].' ('.$mod_strings[LBL_SELECT_ENTITY].') 
    '; +//combovalues + + $output.=''; + $output.=' 
     
    '.$mod_strings[LBL_STEP].' 2 : '.$mod_strings[LBL_CAN_BE_ACCESSED_BY].' ('.$mod_strings[LBL_SELECT_ENTITY].')'.$mod_strings[LBL_PERMISSIONS].'
    + + + + + + + +
     
    '.$mod_strings[LBL_STEP].' 3 : '.$mod_strings[LBL_ACCESS_RIGHTS_FOR_MODULES].'  
    + '; + + $output .=$relatedlistscombo.'
    +
     
     
    '.$mod_strings[LBL_RULE_CONSTRUCTION].'
      +
      +
    +
    + + + + +
    +    +
    '; + +$output.=''; +echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/CurrencyDelete.php b/oss/vtiger/trunk/modules/Settings/CurrencyDelete.php new file mode 100644 index 00000000..1e57c5d4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CurrencyDelete.php @@ -0,0 +1,25 @@ +pquery($sql, array($del_id)); + +header("Location: index.php?action=SettingsAjax&module=Settings&file=CurrencyListView&ajax=true"); + +?> + diff --git a/oss/vtiger/trunk/modules/Settings/CurrencyDeleteStep1.php b/oss/vtiger/trunk/modules/Settings/CurrencyDeleteStep1.php new file mode 100644 index 00000000..5bd8160a --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CurrencyDeleteStep1.php @@ -0,0 +1,81 @@ +pquery($sql, array($delete_currency_id)); +$delete_currencyname = $adb->query_result($result,0,"currency_name"); + + +$output=''; +$output ='
    +
    + + + + + + + + +
    '.$mod_strings["LBL_DELETE_CURRENCY"].''.$app_strings[
    +
    + + + +
    + + + + + + + + + +
    '.$mod_strings['LBL_CURRDEL'].''.getTranslatedCurrencyString($delete_currencyname).'
    '.$mod_strings['LBL_TRANSCURR'].''; + + $output.='
    +
    + + + + +
    +
    +
    '; + +echo $output; +?> diff --git a/oss/vtiger/trunk/modules/Settings/CurrencyEditView.php b/oss/vtiger/trunk/modules/Settings/CurrencyEditView.php new file mode 100644 index 00000000..271318cd --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CurrencyEditView.php @@ -0,0 +1,95 @@ +pquery($sql, array()); + // Check if the current currency status has to be disabled for the + $sql1 = "select * from vtiger_users where currency_id=?"; + $result1 = $adb->pquery($sql1, array($tempid)); + $noofrows = $adb->num_rows($result1); + if($noofrows != 0) + { + $disable_currency = "disabled"; + } else { + $disable_currency = ""; + } + + $other_currencies_list = array(); + while($currencyResult = $adb->fetch_array($result)) { + if ($currencyResult['id'] == $tempid) { + $smarty->assign("STATUS_DISABLE",$disable_currency); + $smarty->assign("CURRENCY_NAME",$currencyResult['currency_name']); + $smarty->assign("CURRENCY_CODE",$currencyResult['currency_code']); + $smarty->assign("CURRENCY_SYMBOL",decode_html($currencyResult['currency_symbol'])); + $smarty->assign("CONVERSION_RATE",$currencyResult['conversion_rate']); + $smarty->assign("CURRENCY_STATUS",$currencyResult['currency_status']); + $currency = $currencyResult['currency_name']; + if($currencyResult['currency_status'] == 'Active') + $smarty->assign("ACTSELECT","selected"); + else + $smarty->assign("INACTSELECT","selected"); + } elseif($currencyResult['currency_status'] == 'Active') { + $cur_id = $currencyResult['id']; + $other_currencies_list[$cur_id] = $currencyResult['currency_name']; + } + } + $smarty->assign("OTHER_CURRENCIES", $other_currencies_list); + $smarty->assign("ID",$tempid); +} + +$currencies_query = $adb->pquery("SELECT currency_name from vtiger_currency_info WHERE deleted=0",array()); +for($index = 0;$index<$adb->num_rows($currencies_query);$index++){ + $currencies_listed[] = decode_html($adb->query_result($currencies_query,$index,'currency_name')); +} + +$currencies_query = $adb->pquery("SELECT currency_name,currency_code,currency_symbol from vtiger_currencies",array()); +for($index = 0;$index<$adb->num_rows($currencies_query);$index++){ + $currencyname = decode_html($adb->query_result($currencies_query,$index,'currency_name')); + $currencycode = decode_html($adb->query_result($currencies_query,$index,'currency_code')); + $currencysymbol = decode_html($adb->query_result($currencies_query,$index,'currency_symbol')); + $currencies[$currencyname] = array($currencycode,$currencysymbol); +} + +$currencies_not_listed = array(); +foreach($currencies as $key=>$value){ + if(!in_array($key,$currencies_listed) || $key==$currency) + $currencies_not_listed[$key] = $value; +} + +require_once('include/Zend/Json.php'); +$smarty->assign("CURRENCIES_ARRAY", Zend_Json::encode($currencies_not_listed)); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("CURRENCIES", $currencies_not_listed); +$smarty->assign("PARENTTAB",getParentTab()); +$smarty->assign("MASTER_CURRENCY",$currency_name); +$smarty->assign("IMAGE_PATH",$image_path); + +if(isset($_REQUEST['detailview']) && $_REQUEST['detailview'] != '') + $smarty->display('CurrencyDetailView.tpl'); +else + $smarty->display("CurrencyEditView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/CurrencyListView.php b/oss/vtiger/trunk/modules/Settings/CurrencyListView.php new file mode 100644 index 00000000..004c2f84 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CurrencyListView.php @@ -0,0 +1,53 @@ +pquery($sql, array()); + $temprow = $adb->fetch_array($result); + $cnt=1; + $currency = Array(); +do +{ + $currency_element = Array(); + $currency_element['name'] = $temprow["currency_name"]; + $currency_element['code'] = $temprow["currency_code"]; + $currency_element['symbol'] = $temprow["currency_symbol"]; + $currency_element['crate'] = $temprow["conversion_rate"]; + $currency_element['status'] = $temprow["currency_status"]; + if($temprow["defaultid"] != '-11') + { + $currency_element['name'] = ''.getTranslatedCurrencyString($temprow["currency_name"]).''; + $currency_element['tool']= ''.$app_strings['LBL_EDIT_BUTTON_LABEL'].' | '.$app_strings['LBL_DELETE_BUTTON_LABEL'].''; + } + else + $currency_element['tool']= ''; + $currency[] = $currency_element; + $cnt++; +}while($temprow = $adb->fetch_array($result)); +$smarty->assign("PARENTTAB",$parenttab); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MOD",$mod_strings); +$smarty->assign("CURRENCY_LIST",$currency); +if($_REQUEST['ajax'] !='') + $smarty->display("CurrencyListViewEntries.tpl"); +else + $smarty->display("CurrencyListView.tpl"); +?> + diff --git a/oss/vtiger/trunk/modules/Settings/CustomFieldList.php b/oss/vtiger/trunk/modules/Settings/CustomFieldList.php new file mode 100644 index 00000000..4fc2430a --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CustomFieldList.php @@ -0,0 +1,187 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$theme_path="themes/".$theme."/"; +$image_path="themes/images/"; +$smarty->assign("IMAGE_PATH", $image_path); +$module_array=getCustomFieldSupportedModules(); + +$cfimagecombo = Array($image_path."text.gif", +$image_path."number.gif", +$image_path."percent.gif", +$image_path."currency.gif", +$image_path."date.gif", +$image_path."email.gif", +$image_path."phone.gif", +$image_path."picklist.gif", +$image_path."url.gif", +$image_path."checkbox.gif", +$image_path."text.gif", +$image_path."picklist.gif"); + +$cftextcombo = Array($mod_strings['Text'], +$mod_strings['Number'], +$mod_strings['Percent'], +$mod_strings['Currency'], +$mod_strings['Date'], +$mod_strings['Email'], +$mod_strings['Phone'], +$mod_strings['PickList'], +$mod_strings['LBL_URL'], +$mod_strings['LBL_CHECK_BOX'], +$mod_strings['LBL_TEXT_AREA'], +$mod_strings['LBL_MULTISELECT_COMBO'] +); + + +$smarty->assign("MODULES",$module_array); +$smarty->assign("CFTEXTCOMBO",$cftextcombo); +$smarty->assign("CFIMAGECOMBO",$cfimagecombo); +if($_REQUEST['fld_module'] !='') + $fld_module = vtlib_purify($_REQUEST['fld_module']); +elseif($_REQUEST['formodule'] != ''){ + $fld_module = vtlib_purify($_REQUEST['formodule']); +} +else + $fld_module = 'Leads'; +$smarty->assign("MODULE",$fld_module); +$smarty->assign("CFENTRIES",getCFListEntries($fld_module)); +if(isset($_REQUEST["duplicate"]) && $_REQUEST["duplicate"] == "yes") +{ + $error=getTranslatedString('ERR_CUSTOM_FIELD_WITH_NAME','Settings'). vtlib_purify($_REQUEST["fldlabel"]) .getTranslatedString('ERR_ALREADY_EXISTS','Settings') . ' ' .getTranslatedString('ERR_SPECIFY_DIFFERENT_LABEL','Settings'); + $smarty->assign("DUPLICATE_ERROR", $error); +} + +if($_REQUEST['mode'] !='') + $mode = vtlib_purify($_REQUEST['mode']); +$smarty->assign("MODE", $mode); + +if($_REQUEST['ajax'] != 'true') + $smarty->display(vtlib_getModuleTemplate('Calendar','CustomFieldList.tpl')); +else + $smarty->display(vtlib_getModuleTemplate('Calendar','CustomFieldEntries.tpl')); + + /** + * Function to get customfield entries + * @param string $module - Module name + * return array $cflist - customfield entries + */ +function getCFListEntries($module) +{ + global $adb,$app_strings,$theme,$smarty,$log; + $tabid = getTabid($module); + if ($module == 'Calendar') { + $tabid = array(9, 16); + } + $theme_path="themes/".$theme."/"; + $image_path="themes/images/"; + $dbQuery = "select fieldid,columnname,fieldlabel,uitype,displaytype,block,vtiger_convertleadmapping.cfmid,tabid from vtiger_field left join vtiger_convertleadmapping on vtiger_convertleadmapping.leadfid = vtiger_field.fieldid where tabid in (". generateQuestionMarks($tabid) .") and vtiger_field.presence in (0,2) and generatedtype = 2 order by sequence"; + $result = $adb->pquery($dbQuery, array($tabid)); + $row = $adb->fetch_array($result); + $count=1; + $cflist=Array(); + if($row!='') + { + do + { + $cf_element=Array(); + $cf_element['no']=$count; + $cf_element['label']=getTranslatedString($row["fieldlabel"],$module); + $fld_type_name = getCustomFieldTypeName($row["uitype"]); + $cf_element['type']=$fld_type_name; + $cf_tab_id = $row["tabid"]; + if($module == 'Leads') + { + $mapping_details = getListLeadMapping($row["cfmid"]); + $cf_element[]= $mapping_details['accountlabel']; + $cf_element[]= $mapping_details['contactlabel']; + $cf_element[]= $mapping_details['potentiallabel']; + } + if($module == 'Calendar') + { + if ($cf_tab_id == '9') + $cf_element['activitytype'] = getTranslatedString('Task',$module); + else + $cf_element['activitytype'] = getTranslatedString('Event',$module); + } + if ($module == 'Calendar') { + $cf_element['tool']=' '.$app_strings['LBL_DELETE_BUTTON_LABEL'].''; + } + $cflist[] = $cf_element; + $count++; + }while($row = $adb->fetch_array($result)); + } + return $cflist; +} + +/** +* Function to Lead customfield Mapping entries +* @param integer $cfid - Lead customfield id +* return array $label - customfield mapping +*/ +function getListLeadMapping($cfid) +{ + global $adb; + $sql="select * from vtiger_convertleadmapping where cfmid =?"; + $result = $adb->pquery($sql, array($cfid)); + $noofrows = $adb->num_rows($result); + for($i =0;$i <$noofrows;$i++) + { + $leadid = $adb->query_result($result,$i,'leadfid'); + $accountid = $adb->query_result($result,$i,'accountfid'); + $contactid = $adb->query_result($result,$i,'contactfid'); + $potentialid = $adb->query_result($result,$i,'potentialfid'); + $cfmid = $adb->query_result($result,$i,'cfmid'); + + $sql2="select fieldlabel from vtiger_field where fieldid =?"; + $result2 = $adb->pquery($sql2, array($accountid)); + $accountfield = $adb->query_result($result2,0,'fieldlabel'); + $label['accountlabel'] = getTranslatedString($accountfield,'Accounts'); + + $sql3="select fieldlabel from vtiger_field where fieldid =?"; + $result3 = $adb->pquery($sql3, array($contactid)); + $contactfield = $adb->query_result($result3,0,'fieldlabel'); + $label['contactlabel'] = getTranslatedString($contactfield,'Contacts'); + $sql4="select fieldlabel from vtiger_field where fieldid =?"; + $result4 = $adb->pquery($sql4, array($potentialid)); + $potentialfield = $adb->query_result($result4,0,'fieldlabel'); + $label['potentiallabel'] = getTranslatedString($potentialfield,'Potentials'); + } + return $label; +} + +/* function to get the modules supports Custom Fields +*/ + +function getCustomFieldSupportedModules() +{ + global $adb; + // vtlib customization: Do not list disabled modules. + //$sql="select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_field.tabid=vtiger_tab.tabid where vtiger_field.tabid not in(9,10,16,15,8,29)"; + $sql="select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_field.tabid=vtiger_tab.tabid where vtiger_field.tabid not in(10,16,15,8,29) and vtiger_tab.presence != 1"; // 16 is still here as we do not want duplicates for Calendar - Both 9 and 16 point to Calendar itself + // END + $result = $adb->pquery($sql, array()); + while($moduleinfo=$adb->fetch_array($result)) + { + $modulelist[$moduleinfo['name']] = $moduleinfo['name']; + } + return $modulelist; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/CustomModEntityNo.php b/oss/vtiger/trunk/modules/Settings/CustomModEntityNo.php new file mode 100644 index 00000000..86e9c0c4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/CustomModEntityNo.php @@ -0,0 +1,115 @@ +"; + echo "
    + + + + + + +
    + $app_strings[LBL_NO_MODULES_TO_SELECT]
    +
    "; + echo ""; + exit; +} + +$modulesList = array_keys($module_array); + +$selectedModule = vtlib_purify($_REQUEST['selmodule']); +if($selectedModule == '') $selectedModule = $modulesList[0]; + +$mode = $_REQUEST['mode']; +if(in_array($selectedModule, $module_array)) { + $focus = CRMEntity::getInstance($selectedModule); +} +if($mode == 'UPDATESETTINGS') { + if(isset($focus)) { + + $status = $focus->setModuleSeqNumber('configure', $selectedModule, $recprefix, $recnumber); + if($status === false) { + $STATUSMSG = "".$mod_strings['LBL_UPDATE']." ".$mod_strings['LBL_FAILED']." $recprefix$recnum ".$mod_strings['LBL_IN_USE']; + } else { + $STATUSMSG = "".$mod_strings['LBL_UPDATE']." ".$mod_strings['LBL_DONE'].""; + } + } +} else if($mode == 'UPDATEBULKEXISTING') { + if(isset($focus)) { + $resultinfo = $focus->updateMissingSeqNumber($selectedModule); + + if(!empty($resultinfo)) { + $usefontcolor = 'green'; + if($resultinfo['totalrecords'] != $resultinfo['updatedrecords']) $usefontcolor = 'red'; + + $STATUSMSG = "" . + $mod_strings['LBL_TOTAL'] . $resultinfo['totalrecords'] . ", " . + $mod_strings['LBL_UPDATE'] . ' ' . $mod_strings['LBL_DONE'] . ':' . $resultinfo['updatedrecords'] . + ""; + } + $seqinfo = $focus->getModuleSeqInfo($selectedModule); + $recprefix = $seqinfo[0]; + $recnumber = $seqinfo[1]; + } +} else { + if(isset($focus)) { + $seqinfo = $focus->getModuleSeqInfo($selectedModule); + $recprefix = $seqinfo[0]; + $recnumber = $seqinfo[1]; + } +} + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); + +$smarty->assign("MODULES",$module_array); +$smarty->assign("SELMODULE",$selectedModule); +$smarty->assign("MODNUM_PREFIX",$recprefix); +$smarty->assign("MODNUM", $recnumber); +$smarty->assign("STATUSMSG", $STATUSMSG); + +if($_REQUEST['ajax'] == 'true') $smarty->display('Settings/CustomModEntityNoInfo.tpl'); +else $smarty->display('Settings/CustomModEntityNo.tpl'); + +function getCRMSupportedModules() +{ + global $adb; + $sql="select tabid,name from vtiger_tab where isentitytype = 1 and presence = 0 and tabid in(select distinct tabid from vtiger_field where uitype='4')"; + $result = $adb->query($sql); + while($moduleinfo=$adb->fetch_array($result)) + { + $modulelist[$moduleinfo['name']] = $moduleinfo['name']; + } + return $modulelist; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/DefModuleView.php b/oss/vtiger/trunk/modules/Settings/DefModuleView.php new file mode 100644 index 00000000..935cf576 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/DefModuleView.php @@ -0,0 +1,42 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); + +if($singlepane_view == 'true') + $viewstatus = 'enabled'; +else + $viewstatus = 'disabled'; + +$smarty->assign("ViewStatus", $viewstatus); + +$smarty->display('DefModuleView.tpl'); + + +?> + diff --git a/oss/vtiger/trunk/modules/Settings/DefaultFieldPermissions.php b/oss/vtiger/trunk/modules/Settings/DefaultFieldPermissions.php new file mode 100644 index 00000000..b675976b --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/DefaultFieldPermissions.php @@ -0,0 +1,93 @@ +$mod_name) +{ + $fieldListResult = getDefOrgFieldList($fld_module); + $noofrows = $adb->num_rows($fieldListResult); + $language_strings = return_module_language($current_language,$fld_module); + $allfields[$fld_module] = getStdOutput($fieldListResult, $noofrows, $language_strings,$profileid); +} + +if($_REQUEST['fld_module'] != '') + $smarty->assign("DEF_MODULE",vtlib_purify($_REQUEST['fld_module'])); +else + $smarty->assign("DEF_MODULE",'Leads'); + +/** Function to get the field label/permission array to construct the default orgnization field UI for the specified profile + * @param $fieldListResult -- mysql query result that contains the field label and uitype:: Type array + * @param $lang_strings -- i18n language mod strings array:: Type array + * @param $profileid -- profile id:: Type integer + * @returns $standCustFld -- field label/permission array :: Type varchar + * + */ +function getStdOutput($fieldListResult, $noofrows, $lang_strings,$profileid) +{ + global $adb; + global $image_path,$theme; + $standCustFld = Array(); + for($i=0; $i<$noofrows; $i++) + { + $uitype = $adb->query_result($fieldListResult,$i,"uitype"); + $fieldlabel = $adb->query_result($fieldListResult,$i,"fieldlabel"); + $typeofdata = $adb->query_result($fieldListResult,$i,"typeofdata"); + $fieldtype = explode("~",$typeofdata); + if($lang_strings[$fieldlabel] !='') + $standCustFld []= $lang_strings[$fieldlabel]; + else + $standCustFld []= $fieldlabel; + + + if($adb->query_result($fieldListResult,$i,"visible") == 0 || ($uitype == 117 && $fieldtype[1] == "M")) + { + $visible =""; + } + else + { + $visible = ""; + } + $standCustFld []= $visible; + } + $standCustFld=array_chunk($standCustFld,2); + $standCustFld=array_chunk($standCustFld,4); + return $standCustFld; +} + +$smarty->assign("FIELD_INFO",$field_module); +$smarty->assign("FIELD_LISTS",$allfields); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("MODE",'view'); + +$smarty->display("FieldAccess.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/DeleteCustomField.php b/oss/vtiger/trunk/modules/Settings/DeleteCustomField.php new file mode 100644 index 00000000..f6df0079 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/DeleteCustomField.php @@ -0,0 +1,93 @@ +pquery($query, array($id)); + +//Deleting from vtiger_profile2field table +$query='delete from vtiger_profile2field where fieldid=?'; +$adb->pquery($query, array($id)); + +//Deleting from vtiger_def_org_field table +$query='delete from vtiger_def_org_field where fieldid=?'; +$adb->pquery($query, array($id)); + +//Drop the column in the corresponding module table +$delete_module_tables = Array( + "Leads"=>"vtiger_leadscf", + "Accounts"=>"vtiger_accountscf", + "Contacts"=>"vtiger_contactscf", + "Potentials"=>"vtiger_potentialscf", + "HelpDesk"=>"vtiger_ticketcf", + "Products"=>"vtiger_productcf", + "Vendors"=>"vtiger_vendorcf", + "PriceBooks"=>"vtiger_pricebookcf", + "PurchaseOrder"=>"vtiger_purchaseordercf", + "SalesOrder"=>"vtiger_salesordercf", + "Quotes"=>"vtiger_quotescf", + "Invoice"=>"vtiger_invoicecf", + "Campaigns"=>"vtiger_campaignscf", + "Calendar"=>"vtiger_activitycf", + ); + +// vtlib customization: Hook added to allow action for custom modules too +$cftablename = $delete_module_tables[$fld_module]; +if(empty($cftablename)) { + include_once('data/CRMEntity.php'); + $focus = CRMEntity::getInstance($fld_module); + $cftablename = $focus->customFieldTable[0]; +} + +$dbquery = 'alter table '. $cftablename .' drop column '. $adb->sql_escape_string($colName); +$adb->pquery($dbquery, array()); + +//To remove customfield entry from vtiger_field table +$dbquery = 'delete from vtiger_field where tablename= ? and fieldname=?'; +$adb->pquery($dbquery, array($cftablename, $colName)); +//we have to remove the entries in customview and report related tables which have this field ($colName) +$adb->pquery("delete from vtiger_cvcolumnlist where columnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_cvstdfilter where columnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_cvadvfilter where columnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_selectcolumn where columnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_relcriteria where columnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_reportsortcol where columnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_reportdatefilter where datecolumnname like ?", array('%'.$colName.'%')); +$adb->pquery("delete from vtiger_reportsummary where columnname like ?", array('%'.$colName.'%')); + + +//Deleting from convert lead mapping vtiger_table- Jaguar +if($fld_module=="Leads") +{ + $deletequery = 'delete from vtiger_convertleadmapping where leadfid=?'; + $adb->pquery($deletequery, array($id)); +}elseif($fld_module=="Accounts" || $fld_module=="Contacts" || $fld_module=="Potentials") +{ + $map_del_id = array("Accounts"=>"accountfid","Contacts"=>"contactfid","Potentials"=>"potentialfid"); + $map_del_q = "update vtiger_convertleadmapping set ".$map_del_id[$fld_module]."=0 where ".$map_del_id[$fld_module]."=?"; + $adb->pquery($map_del_q, array($id)); +} + +//HANDLE HERE - we have to remove the table for other picklist type values which are text area and multiselect combo box +if($uitype == 15) +{ + $deltablequery = 'drop table vtiger_'.$adb->sql_escape_string($colName); + $adb->pquery($deltablequery, array()); +} + +header("Location:index.php?module=Settings&action=CustomFieldList&fld_module=".$fld_module."&parenttab=Settings"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/DeleteLeadCustomFieldMapping.php b/oss/vtiger/trunk/modules/Settings/DeleteLeadCustomFieldMapping.php new file mode 100644 index 00000000..9e784fb2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/DeleteLeadCustomFieldMapping.php @@ -0,0 +1,21 @@ +pquery($sql, array($id)); +} + +header("Location: index.php?module=Settings&action=ListLeadCustomFieldMapping&parenttab=Settings"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/DeleteMailAccount.php b/oss/vtiger/trunk/modules/Settings/DeleteMailAccount.php new file mode 100644 index 00000000..a79eebd0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/DeleteMailAccount.php @@ -0,0 +1,28 @@ +pquery($query, array($account_id)); + } +} + +header("Location:index.php?module=Settings&action=ListMailAccount"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/EditComboField.php b/oss/vtiger/trunk/modules/Settings/EditComboField.php new file mode 100644 index 00000000..63832b55 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/EditComboField.php @@ -0,0 +1,107 @@ +sql_escape_string($tableName); +$moduleName=vtlib_purify($_REQUEST["fld_module"]); +$uitype=vtlib_purify($_REQUEST["uitype"]); + +if(isset($_REQUEST['parentroleid']) && $_REQUEST['parentroleid'] != '') { + $roleid = vtlib_purify($_REQUEST['parentroleid']); +} else { + $roleid = vtlib_purify($_REQUEST["roleid"]); +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; + +//Added to get the strings from language files if present +if($moduleName == 'Events') + $temp_module_strings = return_module_language($current_language, 'Calendar'); +else + $temp_module_strings = return_module_language($current_language, $moduleName); + +//To get the Editable Picklist Values +$query = "select * from vtiger_".$tableName." inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid=vtiger_$tableName.picklist_valueid where roleid=? and presence=1 order by sortid"; +$result = $adb->pquery($query, array($roleid)); +$fldVal=''; + +while($row = $adb->fetch_array($result)) +{ + if($temp_module_strings[$row[$tableName]] != '') + $fldVal .= $temp_module_strings[$row[$tableName]]; + else + $fldVal .= $row[$tableName]; + $fldVal .= "\n"; +} + +if(isset($_REQUEST['parentroleid']) && $_REQUEST['parentroleid']!= '') +{ + echo ''; + echo ''; + + echo ''; + $roleid = vtlib_purify($_REQUEST['parentroleid']); + die; +} + +//To get the Non Editable Picklist Entries +$qry = "select * from vtiger_".$tableName." inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid=vtiger_$tableName.picklist_valueid where roleid=? and presence=0 order by sortid"; +$res = $adb->pquery($qry, array($roleid)); +if($adb->num_rows($res) > 0) +{ + $nonedit_fldVal='
    '; + $c = 0; + while($row = $adb->fetch_array($res)) + { + if($c != 0) + $nonedit_fldVal .= "
    "; + if($temp_module_strings[$row[$tableName]] != '') + $nonedit_fldVal .= $temp_module_strings[$row[$tableName]]; + else + $nonedit_fldVal .= $row[$tableName]; + $c++; + } + $nonedit_fldVal .= "
    "; +} + +$query = 'select fieldlabel from vtiger_tab inner join vtiger_field on vtiger_tab.tabid=vtiger_field.tabid where vtiger_tab.name=? and fieldname=? and vtiger_field.presence in (0,2)'; +$fieldlabel = $adb->query_result($adb->pquery($query, array($moduleName, $tableName)),0,'fieldlabel'); + +if($nonedit_fldVal == '') + $smarty->assign("EDITABLE_MODE","edit"); +else + $smarty->assign("EDITABLE_MODE","nonedit"); +$smarty->assign("NON_EDITABLE_ENTRIES", $nonedit_fldVal); +$smarty->assign("ENTRIES",$fldVal); +$smarty->assign("MODULE",$moduleName); +$smarty->assign("FIELDNAME",$tableName); +//First look into app_strings and then mod_strings and if not available then original label will be displayed +$temp_label = getTranslatedString($fieldlabel); +$smarty->assign("FIELDLABEL",$temp_label); +$smarty->assign("UITYPE", $uitype); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("TEMP_MOD", $temp_module_strings); + +$smarty->display("Settings/EditPickList.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/EditCompanyDetails.php b/oss/vtiger/trunk/modules/Settings/EditCompanyDetails.php new file mode 100644 index 00000000..6d7ff632 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/EditCompanyDetails.php @@ -0,0 +1,88 @@ +assign("ERRORFLAG","".$mod_strings['LOGO_ERROR']."");; + break; + case 2: + $smarty->assign("ERRORFLAG","".$mod_strings['Error_Message']."
    • ".$mod_strings['Invalid_file']."
    • ".$mod_strings['File_has_no_data']."
    "); + break; + case 3: + $smarty->assign("ERRORFLAG","".$mod_strings['Sorry'].",".$mod_strings['uploaded_file_exceeds_maximum_limit'].".".$mod_strings['try_file_smaller'].""); + break; + case 4: + $smarty->assign("ERRORFLAG","".$mod_strings['Problems_in_upload'].". ".$mod_strings['Please_try_again']."
    "); + break; + default: + $smarty->assign("ERRORFLAG",""); + + } +} +global $adb; +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$sql="select * from vtiger_organizationdetails"; +$result = $adb->pquery($sql, array()); +$organization_name = str_replace('"','"',$adb->query_result($result,0,'organizationname')); +$organization_address= $adb->query_result($result,0,'address'); +$organization_city = $adb->query_result($result,0,'city'); +$organization_state = $adb->query_result($result,0,'state'); +$organization_code = $adb->query_result($result,0,'code'); +$organization_country = $adb->query_result($result,0,'country'); +$organization_phone = $adb->query_result($result,0,'phone'); +$organization_fax = $adb->query_result($result,0,'fax'); +$organization_website = $adb->query_result($result,0,'website'); +$organization_logoname = $adb->query_result($result,0,'logoname'); + + +if (isset($organization_name)) + $smarty->assign("ORGANIZATIONNAME",$organization_name); +if (isset($organization_address)) + $smarty->assign("ORGANIZATIONADDRESS",$organization_address); +if (isset($organization_city)) + $smarty->assign("ORGANIZATIONCITY",$organization_city); +if (isset($organization_state)) + $smarty->assign("ORGANIZATIONSTATE",$organization_state); +if (isset($organization_code)) + $smarty->assign("ORGANIZATIONCODE",$organization_code); +if (isset($organization_country)) + $smarty->assign("ORGANIZATIONCOUNTRY",$organization_country); +if (isset($organization_phone)) + $smarty->assign("ORGANIZATIONPHONE",$organization_phone); +if (isset($organization_fax)) + $smarty->assign("ORGANIZATIONFAX",$organization_fax); +if (isset($organization_website)) + $smarty->assign("ORGANIZATIONWEBSITE",$organization_website); +if ($organization_logoname == '') + $organization_logoname = vtlib_purify($_REQUEST['prev_name']); +if (isset($organization_logoname)) + $smarty->assign("ORGANIZATIONLOGONAME",$organization_logoname); + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->display('Settings/EditCompanyInfo.tpl'); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/EditDefOrgFieldLevelAccess.php b/oss/vtiger/trunk/modules/Settings/EditDefOrgFieldLevelAccess.php new file mode 100644 index 00000000..ef4ee6cb --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/EditDefOrgFieldLevelAccess.php @@ -0,0 +1,107 @@ +num_rows($fieldListResult); + $language_strings = return_module_language($current_language,$fld_module); + $allfields[$fld_module] = getStdOutput($fieldListResult, $noofrows, $language_strings,$profileid); +} +if($_REQUEST['fld_module'] != '') + $smarty->assign("DEF_MODULE",vtlib_purify($_REQUEST['fld_module'])); +else + $smarty->assign("DEF_MODULE",'Leads'); + +/** Function to get the field label/permission array to construct the default orgnization field UI for the specified profile + * @param $fieldListResult -- mysql query result that contains the field label and uitype:: Type array + * @param $mod_strings -- i18n language mod strings array:: Type array + * @param $profileid -- profile id:: Type integer + * @returns $standCustFld -- field label/permission array :: Type varchar + * + */ +function getStdOutput($fieldListResult, $noofrows, $lang_strings,$profileid) +{ + global $adb; + $standCustFld = Array(); + if(!isset($focus->mandatory_fields)) $focus->mandatory_fields = Array(); + for($i=0; $i<$noofrows; $i++) + { + $fieldname = $adb->query_result($fieldListResult,$i,"fieldname"); + $uitype = $adb->query_result($fieldListResult,$i,"uitype"); + $displaytype = $adb->query_result($fieldListResult,$i,"displaytype"); + $fieldlabel = $adb->query_result($fieldListResult,$i,"fieldlabel"); + $typeofdata = $adb->query_result($fieldListResult,$i,"typeofdata"); + $fieldtype = explode("~",$typeofdata); + $mandatory = ''; + $readonly = ''; + if($fieldtype[1] == 'M') + { + $mandatory = '*'; + $readonly = 'disabled'; + } + + if($lang_strings[$fieldlabel] !='') + $standCustFld []= $mandatory.' '.$lang_strings[$fieldlabel]; + else + $standCustFld []= $mandatory.' '.$fieldlabel; + if($adb->query_result($fieldListResult,$i,"visible") == 0 && $displaytype!=3) + { + if($fieldlabel == 'Activity Type') + { + $visible = "checked"; + $readonly = 'disabled'; + } + else + $visible = "checked"; + } + elseif($displaytype == 3) + { + $visible = "checked"; + $readonly = 'disabled'; + } + else + { + $visible = ""; + } + $standCustFld []= ''; + + } + $standCustFld=array_chunk($standCustFld,2); + $standCustFld=array_chunk($standCustFld,4); + return $standCustFld; +} + +$smarty->assign("FIELD_INFO",$field_module); +$smarty->assign("FIELD_LISTS",$allfields); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("MODE",'edit'); +$smarty->display("FieldAccess.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/EditInventoryNotification.php b/oss/vtiger/trunk/modules/Settings/EditInventoryNotification.php new file mode 100644 index 00000000..c8758d0f --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/EditInventoryNotification.php @@ -0,0 +1,55 @@ +pquery($sql, array($id)); + if($adb->num_rows($result) ==1); + { + $label = $mod_strings[$adb->query_result($result,0,'notificationname')]; + $notification_subject = $adb->query_result($result,0,'notificationsubject'); + $notification_body = function_exists(iconv) ? iconv("UTF-8",$default_charset,$adb->query_result($result,0,'notificationbody')) : $adb->query_result($result,0,'notificationbody'); + $notification_id = $adb->query_result($result,0,'notificationid'); + + $notification = Array(); + $notification['label'] = $label; + $notification['subject'] = $notification_subject; + $notification['body'] = $notification_body; + $notification['id'] = $notification_id; + } + + $smarty->assign("NOTIFY_DETAILS",$notification); + $smarty->assign("MOD", return_module_language($current_language,'Settings')); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("APP", $app_strings); + $smarty->assign("CMOD", $mod_strings); + $smarty->display("Settings/EditInventoryNotify.tpl"); +} +else +{ + header("Location:index.php?module=Settings&action=listnotificationschedulers&directmode=ajax"); +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/EditNotification.php b/oss/vtiger/trunk/modules/Settings/EditNotification.php new file mode 100644 index 00000000..e4afabcc --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/EditNotification.php @@ -0,0 +1,71 @@ +pquery($query, array($id)); + $selected_item=$adb->query_result($result,0,'templateid'); + + $sql="select * from vtiger_notificationscheduler where schedulednotificationid = ?"; + $result = $adb->pquery($sql, array($id)); + if($adb->num_rows($result) ==1); + { + $notification = Array(); + $notification['active'] = $adb->query_result($result,0,'active'); + $notification['subject'] = $adb->query_result($result,0,'notificationsubject'); + $notification['body'] = $adb->query_result($result,0,'notificationbody'); + $notification['name'] = $mod_strings[$adb->query_result($result,0,'label')]; + $notification['id'] = $adb->query_result($result,0,'schedulednotificationid'); + $notification['type'] = $adb->query_result($result,0,'type'); + } + + $smarty->assign("NOTIFY_DETAILS",$notification); + //Added to show the previous selected value when editing. assigning previously selected id + $smarty->assign("SEL_ID",$selected_item); +} + +//Get all the email template name and id and send it to tpl to generate the combo box + $query="select templateid,templatename from vtiger_emailtemplates"; + $result = $adb->pquery($query, array()); + + $values = Array(); + for($i=0;$i < $adb->num_rows($result);$i++) + { + $temp_id = $adb->query_result($result,$i,'templateid'); + $temp_name = $adb->query_result($result,$i,'templatename'); + $values[$temp_id]=$temp_name; + } + +$smarty->assign("VALUES",$values); + + + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("CMOD", $mod_strings); +$smarty->display("Settings/EditEmailNotification.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/EmailConfig.php b/oss/vtiger/trunk/modules/Settings/EmailConfig.php new file mode 100644 index 00000000..9f0357a5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/EmailConfig.php @@ -0,0 +1,72 @@ +assign("ERROR_MSG",$mod_strings['LBL_TESTMAILSTATUS'].' '.$error_msg.''); +} + +global $adb; +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$sql="select * from vtiger_systems where server_type = ?"; +$result = $adb->pquery($sql, array('email')); +$mail_server = $adb->query_result($result,0,'server'); +$mail_server_username = $adb->query_result($result,0,'server_username'); +$mail_server_password = $adb->query_result($result,0,'server_password'); +$smtp_auth = $adb->query_result($result,0,'smtp_auth'); +if(isset($_REQUEST['server_name'])) + $smarty->assign("MAILSERVER",vtlib_purify($_REQUEST['server_name'])); +elseif(isset($mail_server)) + $smarty->assign("MAILSERVER",$mail_server); +if(isset($_REQUEST['server_user'])) + $smarty->assign("USERNAME",vtlib_purify($_REQUEST['server_user'])); +elseif(isset($mail_server_username)) + $smarty->assign("USERNAME",$mail_server_username); +if (isset($mail_server_password)) + $smarty->assign("PASSWORD",$mail_server_password); +if(isset($_REQUEST['auth_check'])) +{ + if($_REQUEST['auth_check'] == 'on') + $smarty->assign("SMTP_AUTH",'checked'); + else + $smarty->assign("SMTP_AUTH",''); +} +elseif (isset($smtp_auth)) +{ + if($smtp_auth == 'true') + $smarty->assign("SMTP_AUTH",'checked'); + else + $smarty->assign("SMTP_AUTH",''); +} + +if(isset($_REQUEST['emailconfig_mode']) && $_REQUEST['emailconfig_mode'] != '') + $smarty->assign("EMAILCONFIG_MODE",vtlib_purify($_REQUEST['emailconfig_mode'])); +else + $smarty->assign("EMAILCONFIG_MODE",'view'); + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->display("Settings/EmailConfig.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/Forms.php b/oss/vtiger/trunk/modules/Settings/Forms.php new file mode 100644 index 00000000..6a0b7093 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/Forms.php @@ -0,0 +1,268 @@ + + + + +EOQ; + +return $the_script; +} + +/** + * Create HTML form to enter a new record with the minimum necessary vtiger_fields. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ + +function get_new_record_form () { +global $mod_strings; +global $app_strings; +global $current_user; +global $adb;//for dynamic quickcreateform construction + + +$lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; +$lbl_first_name = $mod_strings['LBL_FIRST_NAME']; +$lbl_last_name = $mod_strings['LBL_LAST_NAME']; +$lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; +$lbl_phone = $mod_strings['LBL_PHONE']; +$lbl_email_address = $mod_strings['LBL_EMAIL_ADDRESS']; +$lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; +$lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; +$lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; +$user_id = $current_user->id; + +$qcreate_form = get_left_form_header($mod_strings['LBL_NEW_FORM_TITLE']); + + +$qcreate_get_field="select * from vtiger_field where tabid=4 and quickcreate=0 and vtiger_field.presence in (0,2) order by quickcreatesequence"; +$qcreate_get_result=$adb->pquery($qcreate_get_field, array()); +$qcreate_get_noofrows=$adb->num_rows($qcreate_get_result); + +$fieldName_array = Array();//for validation + +$qcreate_form.='
    '; +$qcreate_form.=''; +$qcreate_form.=''; +$qcreate_form.=''; +$qcreate_form.=''; +$qcreate_form.=''; +//$qcreate_form.=''; +//$qcreate_form.=''; + +$qcreate_form.=''; + +for($j=0;$j<$qcreate_get_noofrows;$j++) +{ + $qcreate_form.=''; + $fieldlabel=$adb->query_result($qcreate_get_result,$j,'fieldlabel'); + $uitype=$adb->query_result($qcreate_get_result,$j,'uitype'); + $tabid=$adb->query_result($qcreate_get_result,$j,'tabid'); + + $fieldname=$adb->query_result($qcreate_get_result,$j,'fieldname');//for validation + $typeofdata=$adb->query_result($qcreate_get_result,$j,'typeofdata');//for validation + $qcreate_form .= get_quickcreate_form($fieldlabel,$uitype,$fieldname,$tabid); + + + //to get validationdata + //start + $fldLabel_array = Array(); + $fldLabel_array[$fieldlabel] = $typeofdata; + $fieldName_array['QCK_'.$fieldname] = $fldLabel_array; + + //end + + $qcreate_form.=''; + +} + + +//for validation +$validationData = $fieldName_array; +$fieldName = ''; +$fieldLabel = ''; +$fldDataType = ''; + +$rows = count($validationData); +foreach($validationData as $fldName => $fldLabel_array) +{ + if($fieldName == '') + { + $fieldName="'".$fldName."'"; + } + else + { + $fieldName .= ",'".$fldName ."'"; + } + foreach($fldLabel_array as $fldLabel => $datatype) + { + if($fieldLabel == '') + { + + $fieldLabel = "'".$fldLabel ."'"; + } + else + { + $fieldLabel .= ",'".$fldLabel ."'"; + } + if($fldDataType == '') + { + $fldDataType = "'".$datatype ."'"; + } + else + { + $fldDataType .= ",'".$datatype ."'"; + } + } +} + +$qcreate_form.='
    '; + + +$qcreate_form.=''; +$qcreate_form.='
    '; +$qcreate_form.=''; + +$qcreate_form .= get_left_form_footer(); +return $qcreate_form; + + + + +} + +/*function get_new_record_form () { +global $mod_strings; +global $app_strings; +global $current_user; + +$lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; +$lbl_first_name = $mod_strings['LBL_FIRST_NAME']; +$lbl_last_name = $mod_strings['LBL_LAST_NAME']; +$lbl_phone = $mod_strings['LBL_PHONE']; +$lbl_email_address = $mod_strings['LBL_EMAIL_ADDRESS']; +$lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; +$lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; +$lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; +$user_id = $current_user->id; + +$the_form = get_left_form_header($mod_strings['LBL_NEW_FORM_TITLE']); +$the_form .= << + + + + + + $lbl_first_name
    +
    + $lbl_required_symbol$lbl_last_name
    +
    + $lbl_phone
    +
    + $lbl_email_address
    +

    + + + +EOQ; +$the_form .= get_left_form_footer(); +$the_form .= get_validate_record_js(); + +return $the_form; +}*/ + +?> diff --git a/oss/vtiger/trunk/modules/Settings/GetFieldInfo.php b/oss/vtiger/trunk/modules/Settings/GetFieldInfo.php new file mode 100644 index 00000000..08bbdd0a --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/GetFieldInfo.php @@ -0,0 +1,62 @@ +' . + '
    + + + + + + + + + + + + +
    '.$label.'
    + + + + + + + + + + +
    + +  Mandatory Field +
    + +  Show +
    +   + +
    +
    '; + + echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/GroupDetailView.php b/oss/vtiger/trunk/modules/Settings/GroupDetailView.php new file mode 100644 index 00000000..7d91081e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/GroupDetailView.php @@ -0,0 +1,158 @@ +assign("GROUPINFO", getStdOutput($groupInfoArr,$groupId, $mod_strings)); +$smarty->assign("GROUPID",$groupId); +$smarty->assign("GROUP_NAME",$groupInfoArr[0]); + + +/** Gives the group info and the group member info array + * @param $groupInfoArr -- Group Info Array got by calling getGroupInfo($groupId):: Type array + * @param $groupID -- group id::Type integer + * @param $mod_strings -- i18n mod strings array::Type array + * @returns $returndata:: Type array, Example array format given below + Array + ( + [0] => Array + ( + [groupname] => vtiger grp + [description] => + ) + + [1] => Array + ( + [Role] => Array + ( + [0] => Array + ( + [membername] => CEO + [memberid] => H2 + [membertype] => Role + [memberaction] => RoleDetailView + [actionparameter] => roleid + ) + + ) + + [Role and Subordinates] => Array + ( + [0] => Array + ( + [membername] => Vice President + [memberid] => H3 + [membertype] => Role and Subordinates + [memberaction] => RoleDetailView + [actionparameter] => roleid + ) + + ) + + [User] => Array + ( + [0] => Array + ( + [membername] => standarduser + [memberid] => 2 + [membertype] => User + [memberaction] => DetailView + [actionparameter] => record + ) + + ) + + ) + + ) + * + * + */ +function getStdOutput($groupInfoArr,$groupId, $mod_strings) +{ + global $adb; + $groupfields['groupname'] = $groupInfoArr[0]; + $groupfields['description'] = $groupInfoArr[1]; + + $row=1; + $groupMember = $groupInfoArr[2]; + $information = array(); + foreach($groupMember as $memberType=>$memberValue) + { + $memberinfo = array(); + foreach($memberValue as $memberId) + { + $groupmembers = array(); + if($memberType == 'roles') + { + $memberName=getRoleName($memberId); + $memberAction="RoleDetailView"; + $memberActionParameter="roleid"; + $memberDisplayType="Role"; + } + elseif($memberType == 'rs') + { + $memberName=getRoleName($memberId); + $memberAction="RoleDetailView"; + $memberActionParameter="roleid"; + $memberDisplayType="Role and Subordinates"; + } + elseif($memberType == 'groups') + { + $memberName=fetchGroupName($memberId); + $memberAction="GroupDetailView"; + $memberActionParameter="groupId"; + $memberDisplayType="Group"; + } + elseif($memberType == 'users') + { + $memberName=getUserName($memberId); + $memberAction="DetailView"; + $memberActionParameter="record"; + $memberDisplayType="User"; + } + $groupmembers ['membername'] = $memberName; + $groupmembers ['memberid'] = $memberId; + $groupmembers ['membertype'] = $memberDisplayType; + $groupmembers ['memberaction'] = $memberAction; + $groupmembers ['actionparameter'] = $memberActionParameter; + $row++; + $memberinfo [] = $groupmembers; + } + if(sizeof($memberinfo) >0) + $information[$memberDisplayType] = $memberinfo; + } + $returndata=array($groupfields,$information); + return $returndata; +} + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->display("GroupDetailview.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/LayoutBlockList.php b/oss/vtiger/trunk/modules/Settings/LayoutBlockList.php new file mode 100644 index 00000000..91bdb712 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/LayoutBlockList.php @@ -0,0 +1,1034 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); + +if ($subMode == 'updateFieldProperties') + updateFieldProperties(); +elseif($subMode == 'deleteCustomField') + deleteCustomField(); +elseif($subMode == 'changeOrder') + changeFieldOrder(); +elseif($subMode == 'addBlock') + $duplicate = addblock(); +elseif($subMode == 'deleteCustomBlock') + deleteBlock(); +elseif($subMode == 'addCustomField') + $duplicate = addCustomField(); +elseif($subMode == 'movehiddenfields' || $subMode == 'showhiddenfields') + show_move_hiddenfields($subMode); +elseif($subMode == 'changeRelatedInfoOrder') + changeRelatedListOrder(); + +$smarty->assign("THEME", $theme); +$module_array=getCustomFieldSupportedModules(); + +$cfimagecombo = Array( + $image_path."text.gif", + $image_path."number.gif", + $image_path."percent.gif", + $image_path."currency.gif", + $image_path."date.gif", + $image_path."email.gif", + $image_path."phone.gif", + $image_path."picklist.gif", + $image_path."url.gif", + $image_path."checkbox.gif", + $image_path."text.gif", + $image_path."picklist.gif" + ); + +$cftextcombo = Array( + $mod_strings['Text'], + $mod_strings['Number'], + $mod_strings['Percent'], + $mod_strings['Currency'], + $mod_strings['Date'], + $mod_strings['Email'], + $mod_strings['Phone'], + $mod_strings['PickList'], + $mod_strings['LBL_URL'], + $mod_strings['LBL_CHECK_BOX'], + $mod_strings['LBL_TEXT_AREA'], + $mod_strings['LBL_MULTISELECT_COMBO'] + ); + + + +$smarty->assign("MODULES",$module_array); +$smarty->assign("CFTEXTCOMBO",$cftextcombo); +$smarty->assign("CFIMAGECOMBO",$cfimagecombo); + +if($_REQUEST['formodule'] !='') + $fld_module = vtlib_purify($_REQUEST['formodule']); +elseif($_REQUEST['fld_module'] != ''){ + $fld_module = vtlib_purify($_REQUEST['fld_module']); +}else + $fld_module = 'Accounts'; + +$block_array = getModuleBlocks($fld_module); + +$smarty->assign("BLOCKS",$block_array); +$smarty->assign("MODULE",$fld_module); +$smarty->assign("CFENTRIES",getFieldListEntries($fld_module)); +$smarty->assign("RELATEDLIST",getRelatedListInfo($fld_module)); + +if(isset($_REQUEST["duplicate"]) && $_REQUEST["duplicate"] == "yes" || $duplicate == 'yes') +{ + echo "ERROR"; + exit; +} +if($duplicate == 'LENGTH_ERROR'){ + echo "LENGTH_ERROR"; + exit; +} +if($_REQUEST['mode'] !='') + $mode = vtlib_purify($_REQUEST['mode']); + +$smarty->assign("MODE", $mode); + +if($_REQUEST['ajax'] != 'true'){ + $smarty->display('Settings/LayoutBlockList.tpl'); +} +elseif(($subMode == 'getRelatedInfoOrder' || $subMode == 'changeRelatedInfoOrder') && $_REQUEST['ajax'] == 'true'){ + $smarty->display('Settings/OrderRelatedList.tpl'); +} +else{ + $smarty->display('Settings/LayoutBlockEntries.tpl'); +} + + +function InStrCount($String,$Find,$CaseSensitive = false) { + global $log; + $i=0; + $x=0; + $substring = ''; + while (strlen($String)>=$i) { + unset($substring); + if ($CaseSensitive) { + $Find=strtolower($Find); + $String=strtolower($String); + } + $substring=substr($String,$i,strlen($Find)); + if ($substring==$Find) $x++; + $i++; + } + $log->debug("In InStrCount function".$String,$Find); + return $x; +} + + +/** +* Function to get customfield entries +* @param string $module - Module name +* return array $cflist - customfield entries +*/ +function getFieldListEntries($module) +{ + $tabid = getTabid($module); + global $adb, $smarty,$log; + global $theme; + $theme_path="themes/".$theme."/"; + $image_path="themes/images/"; + + $dbQuery = "select vtiger_blocks.*,vtiger_tab.presence as tabpresence from vtiger_blocks" . + " inner join vtiger_tab on vtiger_tab.tabid = vtiger_blocks.tabid" . + " where vtiger_blocks.tabid=? and vtiger_tab.presence = 0 order by sequence"; + $result = $adb->pquery($dbQuery, array($tabid)); + $row = $adb->fetch_array($result); + + $focus = CRMEntity::getInstance($module); + + $nonEditableUiTypes = array('4','70'); + + $cflist=Array(); + $i=0; + if($row!='') + { + do + { + if($row["blocklabel"] == 'LBL_CUSTOM_INFORMATION' ) + { + $smarty->assign("CUSTOMSECTIONID",$row["blockid"]); + } + if($row["blocklabel"] == 'LBL_RELATED_PRODUCTS' ) + { + $smarty->assign("RELPRODUCTSECTIONID",$row["blockid"]); + } + if($row["blocklabel"] == 'LBL_COMMENTS' || $row['blocklabel'] == 'LBL_COMMENT_INFORMATION' ) + { + $smarty->assign("COMMENTSECTIONID",$row["blockid"]); + } + if($row['blocklabel'] == 'LBL_TICKET_RESOLUTION'){ + $smarty->assign("SOLUTIONBLOCKID",$row["blockid"]); + } + if($row['blocklabel'] == ''){ + continue; + } + $cflist[$i]['tabpresence']= $row['tabpresence']; + $cflist[$i]['module'] = $module; + $cflist[$i]['blocklabel']=getTranslatedString($row["blocklabel"], $module); + $cflist[$i]['blockid']=$row["blockid"]; + $cflist[$i]['display_status']=$row["display_status"]; + $cflist[$i]['tabid']=$tabid; + $cflist[$i]['blockselect']=$row["blockid"]; + $cflist[$i]['sequence'] = $row["sequence"]; + $cflist[$i]['iscustom'] = $row["iscustom"]; + + if($module!='Invoices' && $module!='Quotes' && $module!='SalesOrder' && $module!='Invoice') + { + $sql_field="select * from vtiger_field where block=? and vtiger_field.displaytype IN (1,2,4) order by sequence"; + $sql_field_params = array($row["blockid"]); + }else + { + $sql_field="select * from vtiger_field where block=? and (vtiger_field.fieldlabel!='Total' and vtiger_field.fieldlabel!='Sub Total' and vtiger_field.fieldlabel!='Tax') and vtiger_field.displaytype IN (1,2,4) order by sequence"; + $sql_field_params = array($row["blockid"]); + } + + $result_field = $adb->pquery($sql_field,$sql_field_params); + $row_field= $adb->fetch_array($result_field); + if($row_field!='') + { + $cf_element=Array(); + $cf_hidden_element=Array(); + $count=0; + $hiddencount=0; + do + { + $fieldid = $row_field['fieldid']; + $presence = $row_field['presence']; + $fieldname = $row_field['fieldname']; + $customfieldflag=InStrCount($row_field['fieldname'],'cf_',true); + $quickcreate = $row_field['quickcreate']; + $massedit = $row_field['masseditable']; + $typeofdata = $row_field['typeofdata']; + $displaytype = $row_field['displaytype']; + $uitype = $row_field['uitype']; + $fld_type_name = getCustomFieldTypeName($row_field['uitype']); + + $fieldlabel = getTranslatedString($row_field['fieldlabel'], $module); + + $strictlyMandatory = false; + if(isset($focus->mandatory_fields) && (!empty($focus->mandatory_fields)) && in_array($fieldname, $focus->mandatory_fields)){ + $strictlyMandatory = true; + } elseif (in_array($uitype, $nonEditableUiTypes) || $displaytype == 2) { + $strictlyMandatory = true; + } + $visibility = getFieldInfo($fieldname,$typeofdata,$quickcreate,$massedit,$presence,$strictlyMandatory,$customfieldflag,$displaytype,$uitype); + + if ($presence == 0 || $presence == 2) { + $cf_element[$count]['fieldselect']=$fieldid; + $cf_element[$count]['blockid']=$row['blockid']; + $cf_element[$count]['tabid']=$tabid; + $cf_element[$count]['no']=$count; + $cf_element[$count]['label']=$fieldlabel; + $cf_element[$count]['fieldlabel'] = $row_field['fieldlabel']; + $cf_element[$count]['type']=$fld_type_name; + $cf_element[$count]['uitype']=$uitype; + $cf_element[$count]['columnname']=$row_field['columnname']; + $cf_element[$count] = array_merge($cf_element[$count], $visibility); + + $count++; + } else { + $cf_hidden_element[$hiddencount]['fieldselect']=$fieldid; + $cf_hidden_element[$hiddencount]['blockid']=$row['blockid']; + $cf_hidden_element[$hiddencount]['tabid']=$tabid; + $cf_hidden_element[$hiddencount]['no']=$hiddencount; + $cf_hidden_element[$hiddencount]['label']=$fieldlabel; + $cf_hidden_element[$hiddencount]['fieldlabel'] = $row_field['fieldlabel']; + $cf_hidden_element[$hiddencount]['type']=$fld_type_name; + $cf_hidden_element[$hiddencount]['uitype']=$uitype; + $cf_hidden_element[$hiddencount]['columnname']=$row_field['columnname']; + $cf_hidden_element[$hiddencount] = array_merge($cf_hidden_element[$hiddencount], $visibility); + + $hiddencount++; + } + } while($row_field = $adb->fetch_array($result_field)); + + $cflist[$i]['no']=$count; + $cflist[$i]['hidden_count'] = $hiddencount; + } + else + { + $cflist[$i]['no']= 0; + } + + $query_fields_not_in_block ='select fieldid,fieldlabel,block from vtiger_field ' . + 'inner join vtiger_blocks on vtiger_field.block=vtiger_blocks.blockid ' . + 'where vtiger_field.block != ? and vtiger_blocks.blocklabel not in ("LBL_TICKET_RESOLUTION","LBL_COMMENTS","LBL_COMMENT_INFORMATION") ' . + 'AND vtiger_field.tabid = ? and vtiger_field.displaytype IN (1,2,4) order by vtiger_field.sequence'; + + $params =array($row['blockid'],$tabid); + $fields = $adb->pquery($query_fields_not_in_block,$params); + $row_field= $adb->fetch_array($fields); + + if($row_field != ''){ + $movefields = array(); + $movefieldcount = 0; + do{ + $movefields[$movefieldcount]['fieldid'] = $row_field['fieldid']; + $movefields[$movefieldcount]['fieldlabel'] = getTranslatedString($row_field['fieldlabel'], $module); + $movefieldcount++; + }while($row_field = $adb->fetch_array($fields)); + $cflist[$i]['movefieldcount'] = $movefieldcount; + } + else{ + $cflist[$i]['movefieldcount'] = 0 ; + } + + $cflist[$i]['field']= $cf_element; + $cflist[$i]['hiddenfield']= $cf_hidden_element; + $cflist[$i]['movefield'] = $movefields; + + $cflist[$i]['hascustomtable'] = $focus->customFieldTable; + unset($cf_element); + unset($cf_hidden_element); + unset($movefields); + $i++; + } while($row = $adb->fetch_array($result)); + } + return $cflist; +} + +/** +* Function to Lead customfield Mapping entries +* @param integer $cfid - Lead customfield id +* return array $label - customfield mapping +*/ +function getListLeadMapping($cfid) +{ + global $adb; + $sql='select * from vtiger_convertleadmapping where cfmid = ?'; + $result = $adb->pquery($sql, array($cfid)); + $noofrows = $adb->num_rows($result); + for($i =0;$i <$noofrows;$i++) + { + $leadid = $adb->query_result($result,$i,'leadfid'); + $accountid = $adb->query_result($result,$i,'accountfid'); + $contactid = $adb->query_result($result,$i,'contactfid'); + $potentialid = $adb->query_result($result,$i,'potentialfid'); + $cfmid = $adb->query_result($result,$i,'cfmid'); + + $sql2="select fieldlabel from vtiger_field where fieldid = ? and vtiger_field.presence in (0,2)"; + $result2 = $adb->pquery($sql2, array($accountid)); + $accountfield = $adb->query_result($result2,0,'fieldlabel'); + $label['accountlabel'] = $accountfield; + + $sql3="select fieldlabel from vtiger_field where fieldid = ? and vtiger_field.presence in (0,2)"; + $result3 = $adb->pquery($sql3, array($contactid)); + $contactfield = $adb->query_result($result3,0,'fieldlabel'); + $label['contactlabel'] = $contactfield; + $sql4="select fieldlabel from vtiger_field where fieldid = ? and vtiger_field.presence in (0,2)"; + $result4 = $adb->pquery($sql4, array($potentialid)); + $potentialfield = $adb->query_result($result4,0,'fieldlabel'); + $label['potentiallabel'] = $potentialfield; + } + return $label; +} + +/* function to get the modules supports Custom Fields +*/ +function getCustomFieldSupportedModules() +{ + global $adb; + $sql="select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_field.tabid=vtiger_tab.tabid where vtiger_field.tabid not in(9,10,16,15,8,29)"; + $result = $adb->query($sql); + while($moduleinfo=$adb->fetch_array($result)) + { + $modulelist[$moduleinfo['name']] = $moduleinfo['name']; + } + return $modulelist; +} + + +function getModuleBlocks($module){ + global $adb; + $tabid = getTabid($module); + $blockquery = "select blocklabel,blockid from vtiger_blocks where tabid = ?"; + $blockres = $adb->pquery($blockquery,array($tabid)); + while($blockinfo = $adb->fetch_array($blockres)){ + $blocklist[$blockinfo['blockid']] = getTranslatedString($blockinfo['blocklabel'],$module); + } + return $blocklist; +} + +/** + * + */ +function changeFieldOrder(){ + global $adb,$log,$smarty; + if(!empty($_REQUEST['what_to_do'])){ + if($_REQUEST['what_to_do']=='block_down'){ + $sql="select * from vtiger_blocks where blockid=?"; + $result = $adb->pquery($sql, array($_REQUEST['blockid'])); + $row= $adb->fetch_array($result); + $current_sequence=$row[sequence]; + + $sql_next="select * from vtiger_blocks where sequence > ? and tabid=? limit 0,1"; + $result_next = $adb->pquery($sql_next, array($current_sequence,$_REQUEST[tabid])); + $row_next= $adb->fetch_array($result_next); + $next_sequence=$row_next[sequence]; + $next_id=$row_next[blockid]; + + + $sql_up_current="update vtiger_blocks set sequence=? where blockid=?"; + $result_up_current = $adb->pquery($sql_up_current, array($next_sequence,$_REQUEST['blockid'])); + + + $sql_up_next="update vtiger_blocks set sequence=? where blockid=?"; + $result_up_next = $adb->pquery($sql_up_next, array($current_sequence,$next_id)); + } + + if($_REQUEST['what_to_do']=='block_up'){ + $sql="select * from vtiger_blocks where blockid=?"; + $result = $adb->pquery($sql, array($_REQUEST['blockid'])); + $row= $adb->fetch_array($result); + $current_sequence=$row[sequence]; + + $sql_previous="select * from vtiger_blocks where sequence < ? and tabid=? order by sequence desc limit 0,1"; + $result_previous = $adb->pquery($sql_previous, array($current_sequence,$_REQUEST[tabid])); + $row_previous= $adb->fetch_array($result_previous); + $previous_sequence=$row_previous[sequence]; + $previous_id=$row_previous[blockid]; + + + $sql_up_current="update vtiger_blocks set sequence=? where blockid=?"; + $result_up_current = $adb->pquery($sql_up_current, array($previous_sequence,$_REQUEST['blockid'])); + + + $sql_up_previous="update vtiger_blocks set sequence=? where blockid=?"; + $result_up_previous = $adb->pquery($sql_up_previous, array($current_sequence,$previous_id)); + } + + if($_REQUEST['what_to_do']=='down' || $_REQUEST['what_to_do']=='Right'){ + $sql="select * from vtiger_field where fieldid=? and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array($_REQUEST['fieldid'])); + $row= $adb->fetch_array($result); + $current_sequence=$row['sequence']; + if($_REQUEST['what_to_do']=='down'){ + $sql_next="select * from vtiger_field where sequence > ? and block = ? and vtiger_field.presence in (0,2) order by sequence limit 1,1"; + $sql_next_params = array($current_sequence, $_REQUEST['blockid']); + }else{ + $sql_next="select * from vtiger_field where sequence > ? and block = ? and vtiger_field.presence in (0,2) order by sequence limit 0,1"; + $sql_next_params = array($current_sequence, $_REQUEST['blockid']); + } + + $result_next = $adb->pquery($sql_next,$sql_next_params); + $row_next= $adb->fetch_array($result_next); + $next_sequence=$row_next['sequence']; + $next_id=$row_next['fieldid']; + + $sql_up_current="update vtiger_field set sequence=? where fieldid=?"; + $result_up_current = $adb->pquery($sql_up_current, array($next_sequence,$_REQUEST['fieldid'])); + + $sql_up_next="update vtiger_field set sequence=? where fieldid=?"; + $result_up_next = $adb->pquery($sql_up_next, array($current_sequence,$next_id)); + $smarty->assign("COLORID",vtlib_purify($_REQUEST['fieldid'])); + } + + if($_REQUEST['what_to_do']=='up' || $_REQUEST['what_to_do']=='Left'){ + $sql="select * from vtiger_field where fieldid=? and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array($_REQUEST['fieldid'])); + $row= $adb->fetch_array($result); + $current_sequence=$row['sequence']; + + if($_REQUEST['what_to_do']=='up'){ + $sql_previous="select * from vtiger_field where sequence < ? and block=? and vtiger_field.presence in (0,2) order by sequence desc limit 1,1"; + $sql_prev_params = array($current_sequence,$_REQUEST['blockid']); + }else{ + $sql_previous="select * from vtiger_field where sequence < ? and block=? and vtiger_field.presence in (0,2) order by sequence desc limit 0,1"; + $sql_prev_params = array($current_sequence,$_REQUEST['blockid']); + } + + $result_previous = $adb->pquery($sql_previous,$sql_prev_params); + $row_previous= $adb->fetch_array($result_previous); + $previous_sequence=$row_previous['sequence']; + $previous_id=$row_previous['fieldid']; + + $sql_up_current="update vtiger_field set sequence=? where fieldid=?"; + $result_up_current = $adb->pquery($sql_up_current, array($previous_sequence,$_REQUEST['fieldid'])); + + $sql_up_previous="update vtiger_field set sequence=? where fieldid=?"; + $result_up_previous = $adb->pquery($sql_up_previous, array($current_sequence,$previous_id)); + $smarty->assign("COLORID",vtlib_purify($_REQUEST['fieldid'])); + } + + if($_REQUEST['what_to_do']=='show'){ + $sql_up_display="update vtiger_blocks set display_status='1' where blockid=?"; + $result_up_display = $adb->pquery($sql_up_display, array($_REQUEST['blockid'])); + } + + if($_REQUEST['what_to_do']=='hide'){ + $sql_up_display="update vtiger_blocks set display_status='0' where blockid=?"; + $result_up_display = $adb->pquery($sql_up_display, array($_REQUEST['blockid'])); + } + } +} +/** + * + */ +function getFieldInfo($fieldname,$typeofdata,$quickcreate,$massedit,$presence,$strictlyMandatory,$customfieldflag,$displaytype,$uitype){ + global $log; + + $fieldtype = explode("~",$typeofdata); + + if($strictlyMandatory){//fields without which the CRM Record will be inconsistent + $mandatory = '0'; + }elseif($fieldtype[1] == "M"){//fields which are made mandatory + $mandatory = '2'; + }else{ + $mandatory = '1'; //fields not mandatory + } + if ($uitype == 4 || $displaytype == 2) { + $mandatory = '3'; + } + + + $visibility = array(); + $visibility['mandatory'] = $mandatory; + $visibility['quickcreate'] = $quickcreate; + $visibility['presence'] = $presence; + $visibility['massedit'] = $massedit; + $visibility['displaytype'] = $displaytype; + $visibility['customfieldflag'] = $customfieldflag; + $visibility['fieldtype'] = $fieldtype[1]; + return $visibility; + } + +function updateFieldProperties(){ + + global $adb,$smarty,$log; + $fieldid = $_REQUEST['fieldid']; + $req_sql = "select * from vtiger_field where fieldid = ? and fieldname not in('salutationtype') and vtiger_field.presence in (0,2)"; + $req_result = $adb->pquery($req_sql, array($fieldid)); + + $typeofdata = $adb->query_result($req_result,0,'typeofdata'); + $tabid = $adb->query_result($req_result,0,'tabid'); + $fieldname = $adb->query_result($req_result,0,'fieldname'); + $uitype = $adb->query_result($req_result,0,'uitype'); + $oldfieldlabel = $adb->query_result($req_result,0,'fieldlabel'); + $tablename = $adb->query_result($req_result,0,'tablename'); + $columnname = $adb->query_result($req_result,0,'columnname'); + $oldquickcreate = $adb->query_result($req_result,0,'quickcreate'); + $oldmassedit = $adb->query_result($req_result,0,'masseditable'); + $oldpresence = $adb->query_result($req_result,0,'presence'); + + if(!empty($_REQUEST['fld_module'])){ + $fld_module = vtlib_purify($_REQUEST['fld_module']); + }else{ + $fld_module = getTabModuleName($tabid); + } + + $focus = CRMEntity::getInstance($fld_module); + + $fieldtype = explode("~",$typeofdata); + $mandatory_checked= $_REQUEST['ismandatory']; + $quickcreate_checked = $_REQUEST['quickcreate']; + $presence_check = $_REQUEST['isPresent']; + $massedit_check = $_REQUEST['massedit']; + + + if(isset($focus->mandatory_fields) && (!empty($focus->mandatory_fields)) && in_array($fieldname, $focus->mandatory_fields)){ + $fieldtype[1] = 'M'; + } elseif($mandatory_checked == 'true' || $mandatory_checked == ''){ + $fieldtype[1] = 'M'; + } else{ + $fieldtype[1] = 'O'; + } + $datatype = implode('~', $fieldtype); + $maxseq = ''; + if($oldquickcreate != 3){ + if(($quickcreate_checked == 'true' || $quickcreate_checked == '' )){ + $qcdata = 2; + $quickcreateseq_Query = 'select max(quickcreatesequence) as maxseq from vtiger_field where tabid = ?'; + $res = $adb->pquery($quickcreateseq_Query,array($tabid)); + $maxseq = $adb->query_result($res,0,'maxseq'); + + }else{ + $qcdata = 1; + } + } + if($oldpresence != 3){ + if($presence_check == 'true' || $presence_check == ''){ + $presence = 2; + }else{ + $presence = 1; + } + }else{ + $presence =1; + } + + if($oldmassedit != 3){ + if(($massedit_check == 'true' || $massedit_check == '')){ + $massedit = 1; + }else{ + $massedit = 2; + } + }else{ + $massedit=1; + } + + if(isset($focus->mandatory_fields) && (!empty($focus->mandatory_fields))){ + $fieldname_list = implode(',',$focus->mandatory_fields); + }else{ + $fieldname_list = ''; + } + + $mandatory_query = "update vtiger_field set typeofdata=? where fieldid=? and fieldname not in (?) AND displaytype != 2"; + $mandatory_params = array($datatype,$fieldid,$fieldname_list); + $adb->pquery($mandatory_query, $mandatory_params); + + if(!empty($qcdata)){ + $quickcreate_query = "update vtiger_field set quickcreate = ? ,quickcreatesequence = ? where fieldid = ? and quickcreate not in (0,3) AND displaytype != 2"; + $quickcreate_params = array($qcdata,$maxseq+1,$fieldid); + $adb->pquery($quickcreate_query,$quickcreate_params); + } + + $presence_query = "update vtiger_field set presence = ? where fieldid = ? and presence not in (0,3) and quickcreate != 0"; + $quickcreate_params = array($presence,$fieldid); + $adb->pquery($presence_query,$quickcreate_params); + + $massedit_query = "update vtiger_field set masseditable = ? where fieldid = ? and masseditable not in (0,3) AND displaytype != 2"; + $massedit_params = array($massedit,$fieldid); + $adb->pquery($massedit_query,$massedit_params); + +} + + + +function deleteCustomField(){ + global $adb; + + $fld_module = $_REQUEST["fld_module"]; + $id = $_REQUEST["fld_id"]; + $colName = $_REQUEST["colName"]; + $uitype = $_REQUEST["uitype"]; + + $fieldquery = 'select * from vtiger_field where fieldid = ?'; + $res = $adb->pquery($fieldquery,array($id)); + + $typeofdata = $adb->query_result($res,0,'typeofdata'); + $fieldname = $adb->query_result($res,0,'fieldname'); + $oldfieldlabel = $adb->query_result($res,0,'fieldlabel'); + $tablename = $adb->query_result($res,0,'tablename'); + $columnname = $adb->query_result($res,0,'columnname'); + $fieldtype = explode("~",$typeofdata); + + //Deleting the CustomField from the Custom Field Table + $query='delete from vtiger_field where fieldid = ? and vtiger_field.presence in (0,2)'; + $adb->pquery($query, array($id)); + + //Deleting from vtiger_profile2field table + $query='delete from vtiger_profile2field where fieldid=?'; + $adb->pquery($query, array($id)); + + //Deleting from vtiger_def_org_field table + $query='delete from vtiger_def_org_field where fieldid=?'; + $adb->pquery($query, array($id)); + + $focus = CRMEntity::getInstance($fld_module); + + $deletecolumnname =$tablename .":". $columnname .":".$fieldname.":".$fld_module. "_" .str_replace(" ","_",$oldfieldlabel).":".$fieldtype[0]; + $column_cvstdfilter = $tablename .":". $columnname .":".$fieldname.":".$fld_module. "_" .str_replace(" ","_",$oldfieldlabel); + $select_columnname = $tablename.":".$columnname .":".$fld_module. "_" . str_replace(" ","_",$oldfieldlabel).":".$fieldname.":".$fieldtype[0]; + $reportsummary_column = $tablename.":".$columnname.":".str_replace(" ","_",$oldfieldlabel); + + $dbquery = 'alter table '. $adb->sql_escape_string($focus->customFieldTable[0]).' drop column '. $adb->sql_escape_string($colName); + $adb->pquery($dbquery, array()); + + //To remove customfield entry from vtiger_field table + $dbquery = 'delete from vtiger_field where columnname= ? and fieldid=? and vtiger_field.presence in (0,2)'; + $adb->pquery($dbquery, array($colName, $id)); + //we have to remove the entries in customview and report related tables which have this field ($colName) + $adb->pquery("delete from vtiger_cvcolumnlist where columnname = ? ", array($deletecolumnname)); + $adb->pquery("delete from vtiger_cvstdfilter where columnname = ?", array($column_cvstdfilter)); + $adb->pquery("delete from vtiger_cvadvfilter where columnname = ?", array($deletecolumnname)); + $adb->pquery("delete from vtiger_selectcolumn where columnname = ?", array($select_columnname)); + $adb->pquery("delete from vtiger_relcriteria where columnname = ?", array($select_columnname)); + $adb->pquery("delete from vtiger_reportsortcol where columnname = ?", array($select_columnname)); + $adb->pquery("delete from vtiger_reportdatefilter where datecolumnname = ?", array($column_cvstdfilter)); + $adb->pquery("delete from vtiger_reportsummary where columnname like ?", array('%'.$reportsummary_column.'%')); + + + //Deleting from convert lead mapping vtiger_table- Jaguar + if($fld_module=="Leads") + { + $deletequery = 'delete from vtiger_convertleadmapping where leadfid=?'; + $adb->pquery($deletequery, array($id)); + }elseif($fld_module=="Accounts" || $fld_module=="Contacts" || $fld_module=="Potentials") + { + $map_del_id = array("Accounts"=>"accountfid","Contacts"=>"contactfid","Potentials"=>"potentialfid"); + $map_del_q = "update vtiger_convertleadmapping set ".$map_del_id[$fld_module]."=0 where ".$map_del_id[$fld_module]."=?"; + $adb->pquery($map_del_q, array($id)); + } + + //HANDLE HERE - we have to remove the table for other picklist type values which are text area and multiselect combo box + if($uitype == 15) + { + $deltablequery = 'drop table vtiger_'.$adb->sql_escape_string($colName); + $adb->pquery($deltablequery, array()); + } +} + + +function addblock(){ + + global $mod_strings,$log,$adb; + $fldmodule=$_REQUEST['fld_module']; + $mode=$_REQUEST['mode']; + + $newblocklabel = trim($_REQUEST['blocklabel']); + $after_block = $_REQUEST['after_blockid']; + + $tabid = getTabid($fldmodule); + $flag = 0; + $dup_check_query = $adb->pquery("SELECT blocklabel from vtiger_blocks WHERE tabid = ?",array($tabid)); + $norows = $adb->num_rows($dup_check_query); + for($i=0;$i<$norows;$i++){ + $blklbl = $adb->query_result($dup_check_query,$i,'blocklabel'); + $blklbltran = getTranslatedString($blklbl,$fldmodule); + if(strtolower($blklbltran) == strtolower($newblocklabel)){ + $flag = 1; + $duplicate='yes'; + return $duplicate; + } + } + $length = strlen($newblocklabel); + if($length > 50){ + $flag = 1; + $duplicate='LENGTH_ERROR'; + return $duplicate; + } + + if($flag!=1){ + $sql_seq="select sequence from vtiger_blocks where blockid=?"; + $res_seq= $adb->pquery($sql_seq, array($after_block)); + $row_seq=$adb->fetch_array($res_seq); + $block_sequence=$row_seq['sequence']; + $newblock_sequence=$block_sequence+1; + + $sql_up="update vtiger_blocks set sequence=sequence+1 where tabid=? and sequence > ?"; + $adb->pquery($sql_up, array($tabid,$block_sequence)); + + $max_blockid=$adb->getUniqueID('vtiger_blocks'); + $iscustom = 1; + $sql="INSERT INTO vtiger_blocks (tabid, blockid, sequence, blocklabel,iscustom) values (?,?,?,?,?)"; + $params = array($tabid,$max_blockid,$newblock_sequence,$newblocklabel,$iscustom); + $adb->pquery($sql,$params); + } + +} + +function deleteBlock(){ + global $adb; + $blockid = $_REQUEST['blockid']; + $deleteblock = 'delete from vtiger_blocks where blockid = ? and iscustom = 1'; + $res = $adb->pquery($deleteblock,array($blockid)); + +} + +function addCustomField(){ + +global $current_user,$log,$adb; + +$fldmodule=vtlib_purify($_REQUEST['fld_module']); +$fldlabel=vtlib_purify(trim($_REQUEST['fldLabel'])); +$fldType= vtlib_purify($_REQUEST['fieldType']); +$parenttab=vtlib_purify($_REQUEST['parenttab']); +$mode=vtlib_purify($_REQUEST['mode']); +$blockid = vtlib_purify($_REQUEST['blockid']); + +$tabid = getTabid($fldmodule); +if ($fldmodule == 'Calendar' && isset($_REQUEST['activity_type'])) { + $activitytype = $_REQUEST['activity_type']; + if ($activitytype == 'E') $tabid = '16'; + if ($activitytype == 'T') $tabid = '9'; +} +if(get_magic_quotes_gpc() == 1){ + $fldlabel = stripslashes($fldlabel); +} + +$dup_check_tab_id = $tabid; +if ($fldmodule == 'Calendar') + $dup_check_tab_id = array('9', '16'); +$checkquery="select * from vtiger_field where tabid in (". generateQuestionMarks($dup_check_tab_id) .") and fieldlabel=?"; +$params = array($dup_check_tab_id, $fldlabel); +$checkresult=$adb->pquery($checkquery,$params); + +if($adb->num_rows($checkresult) > 0 ) +{ + $duplicate = 'yes'; + return $duplicate ; +} +else{ + $max_fieldid = $adb->getUniqueID("vtiger_field"); + $columnName = 'cf_'.$max_fieldid; + $custfld_fieldid = $max_fieldid; + //Assigning the vtiger_table Name + if($fldmodule != '') { + $focus = CRMEntity::getInstance($fldmodule); + if (isset($focus->customFieldTable)) { + $tableName=$focus->customFieldTable[0]; + } else { + $tableName= 'vtiger_'.strtolower($fldmodule).'cf'; + } + } + //Assigning the uitype + $fldlength=$_REQUEST['fldLength']; + $uitype=''; + $fldPickList=''; + if(isset($_REQUEST['fldDecimal']) && $_REQUEST['fldDecimal'] != ''){ + $decimal=$_REQUEST['fldDecimal']; + }else{ + $decimal=0; + } + $type=''; + $uichekdata=''; + if($fldType == 'Text'){ + $uichekdata='V~O~LE~'.$fldlength; + $uitype = 1; + $type = "C(".$fldlength.") default ()"; // adodb type + }elseif($fldType == 'Number'){ + $uitype = 7; + //this may sound ridiculous passing decimal but that is the way adodb wants + $dbfldlength = $fldlength + $decimal + 1; + $type="N(".$dbfldlength.".".$decimal.")"; // adodb type + $uichekdata='N~O~'.$fldlength .','.$decimal; + }elseif($fldType == 'Percent'){ + $uitype = 9; + $type="N(5.2)"; //adodb type + $uichekdata='N~O~2~2'; + }elseif($fldType == 'Currency'){ + $uitype = 71; + $dbfldlength = $fldlength + $decimal + 1; + $type="N(".$dbfldlength.".".$decimal.")"; //adodb type + $uichekdata='N~O~'.$fldlength .','.$decimal; + }elseif($fldType == 'Date'){ + $uichekdata='D~O'; + $uitype = 5; + $type = "D"; // adodb type + }elseif($fldType == 'Email'){ + $uitype = 13; + $type = "C(50) default () "; //adodb type + $uichekdata='E~O'; + }elseif($fldType == 'Phone'){ + $uitype = 11; + $type = "C(30) default () "; //adodb type + $uichekdata='V~O'; + }elseif($fldType == 'Picklist'){ + $uitype = 15; + $type = "C(255) default () "; //adodb type + $uichekdata='V~O'; + }elseif($fldType == 'URL'){ + $uitype = 17; + $type = "C(255) default () "; //adodb type + $uichekdata='V~O'; + }elseif($fldType == 'Checkbox'){ + $uitype = 56; + $type = "C(3) default 0"; //adodb type + $uichekdata='C~O'; + }elseif($fldType == 'TextArea'){ + $uitype = 21; + $type = "X"; //adodb type + $uichekdata='V~O'; + }elseif($fldType == 'MultiSelectCombo'){ + $uitype = 33; + $type = "X"; //adodb type + $uichekdata='V~O'; + }elseif($fldType == 'Skype'){ + $uitype = 85; + $type = "C(255) default () "; //adodb type + $uichekdata='V~O'; + } + + if(is_numeric($blockid)){ + if($_REQUEST['fieldid'] == ''){ + $max_fieldsequence = "select max(sequence) as maxsequence from vtiger_field where block = ? "; + $res = $adb->pquery($max_fieldsequence,array($blockid)); + $max_seq = $adb->query_result($res,0,'maxsequence'); + if($fldmodule == 'Quotes' || $fldmodule == 'PurchaseOrder' || $fldmodule == 'SalesOrder' || $fldmodule == 'Invoice'){ + $quickcreate = 3; + }else{ + $quickcreate = 1; + } + $query = "insert into vtiger_field (tabid,fieldid,columnname,tablename,generatedtype,uitype,fieldname,fieldlabel,readonly,presence,selected,maximumlength,sequence,block,displaytype,typeofdata,quickcreate,quickcreatesequence,info_type,masseditable) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $qparams = array($tabid,$custfld_fieldid,$columnName,$tableName,2,$uitype,$columnName,$fldlabel,0,2,0,100,$max_seq+1,$blockid,1,$uichekdata,$quickcreate,0,'BAS',1); + $adb->pquery($query, $qparams); + $adb->alterTable($tableName, $columnName." ".$type, "Add_Column"); + //Inserting values into vtiger_profile2field vtiger_tables + $sql1 = "select * from vtiger_profile"; + $sql1_result = $adb->pquery($sql1, array()); + $sql1_num = $adb->num_rows($sql1_result); + for($i=0; $i<$sql1_num; $i++){ + $profileid = $adb->query_result($sql1_result,$i,"profileid"); + $sql2 = "insert into vtiger_profile2field values(?,?,?,?,?)"; + $adb->pquery($sql2, array($profileid, $tabid, $custfld_fieldid, 0, 1)); + } + + //Inserting values into def_org vtiger_tables + $sql_def = "insert into vtiger_def_org_field values(?,?,?,?)"; + $adb->pquery($sql_def, array($tabid, $custfld_fieldid, 0, 1)); + + if($fldType == 'Picklist' || $fldType == 'MultiSelectCombo'){ + $columnName = $adb->sql_escape_string($columnName); + // Creating the PickList Table and Populating Values + if($_REQUEST['fieldid'] == ''){ + $qur = "CREATE TABLE vtiger_".$columnName." ( + ".$columnName."id int(19) NOT NULL auto_increment, + ".$columnName." varchar(200) NOT NULL, + presence int(1) NOT NULL default '1', + picklist_valueid int(19) NOT NULL default '0', + PRIMARY KEY (".$columnName."id) + )"; + $adb->pquery($qur, array()); + } + + //Adding a new picklist value in the picklist table + if($mode != 'edit'){ + $picklistid = $adb->getUniqueID("vtiger_picklist"); + $sql="insert into vtiger_picklist values(?,?)"; + $adb->pquery($sql, array($picklistid,$columnName)); + } + $roleid=$current_user->roleid; + $qry="select picklistid from vtiger_picklist where name=?"; + $picklistid = $adb->query_result($adb->pquery($qry, array($columnName)), 0,'picklistid'); + $pickArray = Array(); + $fldPickList = $_REQUEST['fldPickList']; + $pickArray = explode("\n",$fldPickList); + $count = count($pickArray); + for($i = 0; $i < $count; $i++) + { + $pickArray[$i] = trim(from_html($pickArray[$i])); + if($pickArray[$i] != '') + { + $picklistcount=0; + $sql ="select $columnName from vtiger_$columnName"; + $numrow = $adb->num_rows($adb->pquery($sql, array())); + for($x=0;$x < $numrow ; $x++) + { + $picklistvalues = $adb->query_result($adb->pquery($sql, array()),$x,$columnName); + if($pickArray[$i] == $picklistvalues) + { + $picklistcount++; + } + } + if($picklistcount == 0) + { + $picklist_valueid = getUniquePicklistID(); + $query = "insert into vtiger_".$columnName." values(?,?,?,?)"; + $adb->pquery($query, array($adb->getUniqueID("vtiger_".$columnName),$pickArray[$i],1,$picklist_valueid)); + /*$sql="update vtiger_picklistvalues_seq set id = ?"; + $adb->pquery($sql, array(++$picklist_valueid));*/ + } + $sql = "select picklist_valueid from vtiger_$columnName where $columnName=?"; + $pick_valueid = $adb->query_result($adb->pquery($sql, array($pickArray[$i])),0,'picklist_valueid'); + $sql = "insert into vtiger_role2picklist select roleid,$pick_valueid,$picklistid,$i from vtiger_role"; + $adb->pquery($sql, array()); + } + } + } + //Inserting into LeadMapping table - Jaguar + if($fldmodule == 'Leads' && $_REQUEST['fieldid'] == '') + { + $sql_def = "insert into vtiger_convertleadmapping (leadfid) values(?)"; + $adb->pquery($sql_def, array($custfld_fieldid)); + } + } + } +} +} + +function show_move_hiddenfields($submode){ + global $adb,$log; + $selected_fields = $_REQUEST['selected']; + $selected = trim($selected_fields,":"); + $sel_arr = array(); + $sel_arr = explode(":",$selected); + $sequence = $adb->pquery('select max(sequence) as maxseq from vtiger_field where block = ? and tabid = ?',array($_REQUEST['blockid'],$_REQUEST['tabid'])); + $max = $adb->query_result($sequence,0,'maxseq'); + $max_seq = $max + 1; + + if($submode == 'showhiddenfields'){ + for($i=0; $i< count($sel_arr);$i++){ + $res = $adb->pquery('update vtiger_field set presence = 2,sequence = ? where block = ? and fieldid = ?', array($max_seq,$_REQUEST['blockid'],$sel_arr[$i])); + $max_seq++; + } + } + else{ + for($i=0; $i< count($sel_arr);$i++){ + $res = $adb->pquery('update vtiger_field set sequence = ? , block = ? where fieldid = ?', array($max_seq,$_REQUEST['blockid'],$sel_arr[$i])); + $max_seq++; + } + } +} + +function getRelatedListInfo($module){ + global $adb; + $tabid = getTabid($module); + $related_query = 'select * from vtiger_relatedlists ' . + 'inner join vtiger_tab on vtiger_relatedlists.related_tabid = vtiger_tab.tabid and vtiger_tab.presence = 0 where vtiger_relatedlists.tabid = ? order by sequence'; + $relinfo = $adb->pquery($related_query,array($tabid)); + $noofrows = $adb->num_rows($relinfo); + for($i=0;$i<$noofrows;$i++){ + $res[$i]['name'] = $adb->query_result($relinfo,$i,'name'); + $res[$i]['sequence'] = $adb->query_result($relinfo,$i,'sequence'); + $label = $adb->query_result($relinfo,$i,'label'); + $relatedModule = getTabname($adb->query_result($relinfo,$i,'related_tabid')); + $res[$i]['label'] = getTranslatedString($label,$relatedModule); + $res[$i]['presence'] = $adb->query_result($relinfo,$i,'presence'); + $res[$i]['tabid'] = $tabid; + $res[$i]['id'] = $adb->query_result($relinfo,$i,'relation_id'); + } + return $res; +} + +function changeRelatedListOrder(){ + global $adb,$log; + $tabid = $_REQUEST['tabid']; + $what_todo = $_REQUEST['what_to_do']; + if(!empty($_REQUEST['what_to_do'])){ + if($_REQUEST['what_to_do'] == 'move_up'){ + $currentsequence = $_REQUEST['sequence']; + + $previous_relation = $adb->pquery('select relation_id,sequence from vtiger_relatedlists where sequence < ? and tabid = ? order by sequence desc limit 0,1',array($currentsequence,$tabid)); + $previous_sequence = $adb->query_result($previous_relation,0,'sequence'); + $previous_relationid = $adb->query_result($previous_relation,0,'relation_id'); + + $adb->pquery('update vtiger_relatedlists set sequence = ? where relation_id = ? and tabid = ?',array($previous_sequence,$_REQUEST['id'],$tabid)); + $adb->pquery('update vtiger_relatedlists set sequence = ? where tabid = ? and relation_id = ?',array($currentsequence,$tabid,$previous_relationid)); + }elseif($_REQUEST['what_to_do'] == 'move_down'){ + + $currentsequence = $_REQUEST['sequence']; + + $next_relation = $adb->pquery('select relation_id,sequence from vtiger_relatedlists where sequence > ? and tabid = ? order by sequence limit 0,1',array($currentsequence,$tabid)); + $next_sequence = $adb->query_result($next_relation,0,'sequence'); + $next_relationid = $adb->query_result($next_relation,0,'relation_id'); + + $adb->pquery('update vtiger_relatedlists set sequence = ? where relation_id = ? and tabid = ?',array($next_sequence,$_REQUEST['id'],$tabid)); + $adb->pquery('update vtiger_relatedlists set sequence = ? where tabid = ? and relation_id = ?',array($currentsequence,$tabid,$next_relationid)); + + } + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/LeadCustomFieldMapping.php b/oss/vtiger/trunk/modules/Settings/LeadCustomFieldMapping.php new file mode 100644 index 00000000..46731c6a --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/LeadCustomFieldMapping.php @@ -0,0 +1,151 @@ +assign("IMAGE_PATH", $image_path); + +/** + * Function to get Account custom fields + * @param integer $leadid - lead customfield id + * @param integer $accountid - account customfield id + * return array $accountcf - account customfield + */ +function getAccountCustomValues($leadid,$accountid) +{ + global $adb; + $accountcf=Array(); + $sql="select fieldid,fieldlabel,uitype,typeofdata from vtiger_field,vtiger_tab where vtiger_field.tabid=vtiger_tab.tabid and generatedtype=2 and vtiger_tab.name='Accounts' and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array()); + $noofrows = $adb->num_rows($result); + + for($i=0;$i<$noofrows;$i++) + { + $account_field['fieldid']=$adb->query_result($result,$i,"fieldid"); + $account_field['fieldlabel']=getTranslatedString($adb->query_result($result,$i,"fieldlabel"),'Accounts'); + $account_field['typeofdata']=$adb->query_result($result,$i,"typeofdata"); + $account_field['fieldtype']=getCustomFieldTypeName($adb->query_result($result,$i,"uitype")); + if($account_field['fieldid']==$accountid) + $account_field['selected'] = "selected"; + else + $account_field['selected'] = ""; + $account_cfelement[]=$account_field; + } + $accountcf[$leadid.'_account']=$account_cfelement; + return $accountcf; +} + +/** + * Function to get contact custom fields + * @param integer $leadid - lead customfield id + * @param integer $contactid - contact customfield id + * return array $contactcf - contact customfield + */ +function getContactCustomValues($leadid,$contactid) +{ + global $adb; + $contactcf=Array(); + $sql="select fieldid,fieldlabel,uitype,typeofdata from vtiger_field,vtiger_tab where vtiger_field.tabid=vtiger_tab.tabid and generatedtype=2 and vtiger_tab.name='Contacts'and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array()); + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $contact_field['fieldid']=$adb->query_result($result,$i,"fieldid"); + $contact_field['fieldlabel']=getTranslatedString($adb->query_result($result,$i,"fieldlabel"),'Contacts'); + $contact_field['typeofdata']=$adb->query_result($result,$i,"typeofdata"); + $contact_field['fieldtype']=getCustomFieldTypeName($adb->query_result($result,$i,"uitype")); + + if($contact_field['fieldid']==$contactid) + $contact_field['selected']="selected"; + else + $contact_field['selected'] = ""; + $contact_cfelement[]=$contact_field; + } + $contactcf[$leadid.'_contact'] = $contact_cfelement; + return $contactcf; +} + +/** + * Function to get potential custom fields + * @param integer $leadid - lead customfield id + * @param integer $potentialid - potential customfield id + * return array $potentialcf - potential customfield + */ +function getPotentialCustomValues($leadid,$potentialid) +{ + global $adb; + $potentialcf=Array(); + $sql="select fieldid,fieldlabel,uitype,typeofdata from vtiger_field,vtiger_tab where vtiger_field.tabid=vtiger_tab.tabid and generatedtype=2 and vtiger_tab.name='Potentials' and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql, array()); + $noofrows = $adb->num_rows($result); + for($i=0; $i<$noofrows; $i++) + { + $potential_field['fieldid']=$adb->query_result($result,$i,"fieldid"); + $potential_field['fieldlabel']=getTranslatedString($adb->query_result($result,$i,"fieldlabel"),'Potentials'); + $potential_field['typeofdata']=$adb->query_result($result,$i,"typeofdata"); + $potential_field['fieldtype']=getCustomFieldTypeName($adb->query_result($result,$i,"uitype")); + + if($potential_field['fieldid']==$potentialid) + $potential_field['selected']="selected"; + else + $potential_field['selected'] = ""; + $potential_cfelement[]=$potential_field; + } + $potentialcf[$leadid.'_potential']=$potential_cfelement; + return $potentialcf; +} + +/** + * Function to get leads mapping custom fields + * return array $leadcf - mapping custom fields + */ + +function customFieldMappings() +{ + global $adb; + + $convert_sql="select vtiger_convertleadmapping.*,uitype,fieldlabel,typeofdata from vtiger_convertleadmapping left join vtiger_field on vtiger_field.fieldid = vtiger_convertleadmapping.leadfid and vtiger_field.presence in (0,2)"; + $convert_result = $adb->pquery($convert_sql, array()); + + $no_rows = $adb->num_rows($convert_result); + for($j=0; $j<$no_rows; $j++) + { + $leadid = $adb->query_result($convert_result,$j,"leadfid"); + $accountid=$adb->query_result($convert_result,$j,"accountfid"); + $contactid=$adb->query_result($convert_result,$j,"contactfid"); + $potentialid=$adb->query_result($convert_result,$j,"potentialfid"); + $lead_field['sno'] = $j+1; + $lead_field['leadid'] = getTranslatedString($adb->query_result($convert_result,$j,"fieldlabel"),'Leads'); + $lead_field['typeofdata']=$adb->query_result($convert_result,$j,"typeofdata"); + $lead_field['fieldtype'] = getCustomFieldTypeName($adb->query_result($convert_result,$j,"uitype"));; + $lead_field['account'] = getAccountCustomValues($leadid,$accountid); + $lead_field['contact'] = getContactCustomValues($leadid,$contactid); + $lead_field['potential'] = getPotentialCustomValues($leadid,$potentialid); + $leadcf[]= $lead_field; + } + return $leadcf; +} +$module = 'Leads'; +$smarty->assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("CUSTOMFIELDMAPPING",customFieldMappings()); +$smarty->assign("MODULE",$module); +$smarty->display("CustomFieldMapping.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/ListLoginHistory.php b/oss/vtiger/trunk/modules/Settings/ListLoginHistory.php new file mode 100644 index 00000000..2bd44f0f --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ListLoginHistory.php @@ -0,0 +1,58 @@ +assign("CMOD", $mod_strings); +$smarty->assign("MOD", $current_module_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("USERLIST", $user_list); +$smarty->assign("CATEGORY",$category); + +$smarty->display("ListLoginHistory.tpl"); +?> + diff --git a/oss/vtiger/trunk/modules/Settings/ListMailAccount.php b/oss/vtiger/trunk/modules/Settings/ListMailAccount.php new file mode 100644 index 00000000..0193b733 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ListMailAccount.php @@ -0,0 +1,162 @@ +'; +echo get_module_title($mod_strings['LBL_MODULE_NAME'], $mod_strings['LBL_MODULE_NAME'].' : '.$mod_strings['LBL_ADD_MAIL_ACCOUNT'], true); +echo '

    '; + + +if($_REQUEST['problem']) +{ + echo 'Error in incoming mail server configuration! '; +} + +?> + +
    + + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + +fetch_array($result); + $rowcount = $adb->num_rows($result); +$edit="Edit "; +$del="Del "; +$bar=" | "; +$cnt=1; + +if($rowcount!=0) +{ +do +{ + + if ($cnt%2==0) + printf(''); + else + printf(''); + printf('','blank.gif'); + printf("",$temprow["display_name"]); + printf('','blank.gif'); + printf("",$temprow["mail_servername"]); + printf('','blank.gif'); + printf("",$temprow["mail_id"]); + + printf('','blank.gif'); + printf("",$temprow["mail_protocol"]); + + + printf('','blank.gif'); + printf("",$temprow["mail_username"]); + + printf('','blank.gif'); + if($temprow["set_default"]==1); + $DEFAULT="Selected"; + printf('',$temprow["account_id"]); + printf('','blank.gif'); + printf('',$temprow["account_id"]); + $cnt++; + printf(""); + $DEFAULT=''; +} +while($temprow = $adb->fetch_array($result)); +} +?> + +
           
     
      %s %s %s %s %s '.$mod_strings["Edit"].'
    + diff --git a/oss/vtiger/trunk/modules/Settings/ListModuleOwners.php b/oss/vtiger/trunk/modules/Settings/ListModuleOwners.php new file mode 100644 index 00000000..56076a21 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ListModuleOwners.php @@ -0,0 +1,144 @@ +pquery($sql, array($userid, $tabid)); + } + } + +} +elseif($_REQUEST['list_module_mode'] != '' && $_REQUEST['list_module_mode'] == 'edit') +{ + $user_array = get_user_array(false); + foreach($module_array as $val) + { + $user_combo = getUserCombo($user_array,$val); + + $user_list []= $val; + $user_list []= $user_combo; + + } + $user_list = array_chunk($user_list,2); +} + +$smarty = new vtigerCRM_Smarty; +if($_REQUEST['list_module_mode'] != 'edit') +{ + foreach($module_array as $val) + { + $user_list []= $val; + + //get the user array as a combo list + $user_id = getModuleOwner(getTabid($val)); + $user_name = getUserName($user_id); + + $user_list []= $user_id; + $user_list []= $user_name; + } + + $user_list = array_chunk($user_list,3); +} +$log->info("Settings Module Owners view"); + +$smarty->assign("MODULE_MODE",vtlib_purify($_REQUEST['list_module_mode'])); +$smarty->assign("USER_LIST", $user_list); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +if($_REQUEST['file_mode'] != 'ajax') + $smarty->display("Settings/ModuleOwners.tpl"); +else + $smarty->display("Settings/ModuleOwnersContents.tpl"); + + /** Function to get the module owner for the tabid + * @ param $tabid + * It gets the module owner for the given tabid from vtiger_moduleowners table + * returns the userid of the module owner for the given tabid + */ +function getModuleOwner($tabid) +{ + global $adb; + $sql = "select * from vtiger_moduleowners where tabid=?"; + $res = $adb->pquery($sql, array($tabid)); + $userid = $adb->query_result($res,0,'user_id'); + + return $userid; +} + /** Function to get the module List to which the owners can be assigned + * It gets the module list and returns in an array + */ +function getModuleNameList1() +{ + global $adb; + + // vtlib customization: Ignore disabled modules + //$sql = "select vtiger_moduleowners.*, vtiger_tab.name from vtiger_moduleowners inner join vtiger_tab on vtiger_moduleowners.tabid = vtiger_tab.tabid order by vtiger_tab.tabsequence"; + $sql = "select vtiger_moduleowners.*, vtiger_tab.name from vtiger_moduleowners inner join vtiger_tab on vtiger_moduleowners.tabid = vtiger_tab.tabid WHERE vtiger_tab.presence != 1 order by vtiger_tab.tabsequence"; + // END + $res = $adb->pquery($sql, array()); + $mod_array = Array(); + while($row = $adb->fetchByAssoc($res)) + { + array_push($mod_array,$row['name']); + } + return $mod_array; +} + /** Function to get combostrings of users + * @ $user_array : type Array + * @ $modulename : Type String + * returns the html string for module owners for the given module owners + */ + +function getUserCombo($user_array,$name) +{ + global $adb; + + $tabid = getTabid($name); + $sql = "select * from vtiger_moduleowners where tabid=?"; + $res = $adb->pquery($sql, array($tabid)); + $db_userid = $adb->query_result($res,0,'user_id'); + + //Form the user combo list for each module + $combo_name = "user_".strtolower($name); + $user_combo = ''; + + return $user_combo; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ListProfiles.php b/oss/vtiger/trunk/modules/Settings/ListProfiles.php new file mode 100644 index 00000000..fa6d3563 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ListProfiles.php @@ -0,0 +1,73 @@ +pquery($sql, array()); +$noofrows = $adb->num_rows($profileListResult); +$list_entries = array($mod_strings['LBL_LIST_NO'],$mod_strings['LBL_LIST_TOOLS'],$mod_strings['LBL_NEW_PROFILE_NAME'],$mod_strings['LBL_DESCRIPTION']); + +/** gives the profile list info array + * @param $profileListResult -- profile list database result:: Type array + * @param $noofrows -- no of rows in the $profileListResult:: Type integer + * @param $mod_strings -- i18n mod_strings array:: Type array + * @returns $return_date -- profile list info array:: Type array + * + */ +function getStdOutput($profileListResult, $noofrows, $mod_strings) +{ + global $adb; + $return_data = array(); + for($i=0; $i<$noofrows; $i++) + { + $standCustFld = array(); + $profile_name = $adb->query_result($profileListResult,$i,"profilename"); + $profile_id = $adb->query_result($profileListResult,$i,"profileid"); + $description = $adb->query_result($profileListResult,$i,"description"); + global $current_user; + $current_profile = fetchUserProfileId($current_user->id); + if($profile_id != 1 && $profile_id != $current_profile) + $standCustFld['del_permission']='yes'; + else + $standCustFld['del_permission']='no'; + + $standCustFld['profileid']= $profile_id; + $standCustFld['profilename']= $profile_name; + $standCustFld['description']= $description; + $return_data[]=$standCustFld; + } + return $return_data; +} + +$smarty->assign("LIST_HEADER",$list_entries); +$smarty->assign("LIST_ENTRIES",getStdOutput($profileListResult, $noofrows, $mod_strings)); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("PROFILES", $standCustFld); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("COUNT",$noofrows); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +$smarty->display("UserProfileList.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner.php b/oss/vtiger/trunk/modules/Settings/MailScanner.php new file mode 100644 index 00000000..0a9db292 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner.php @@ -0,0 +1,47 @@ + + diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerEdit.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerEdit.php new file mode 100644 index 00000000..d6a06ee5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerEdit.php @@ -0,0 +1,31 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH","themes/$theme/images/"); + +$scannername = $_REQUEST['scannername']; + +$scannerinfo = new Vtiger_MailScannerInfo($scannername); + +$smarty->assign("SCANNERINFO", $scannerinfo->getAsMap()); + +$smarty->display('MailScanner/MailScannerEdit.tpl'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolder.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolder.php new file mode 100644 index 00000000..068d178d --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolder.php @@ -0,0 +1,31 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH","themes/$theme/images/"); + +$scannername = $_REQUEST['scannername']; +$scannerinfo = new Vtiger_MailScannerInfo($scannername); + +$smarty->assign("SCANNERINFO", $scannerinfo->getAsMap()); +$smarty->assign("FOLDERINFO", $scannerinfo->getFolderInfo()); + +$smarty->display('MailScanner/MailScannerFolder.tpl'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolderSave.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolderSave.php new file mode 100644 index 00000000..3d177869 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolderSave.php @@ -0,0 +1,28 @@ +$value) { + $matches = Array(); + if(preg_match("/folder_([0-9]+)/", $key, $matches)) { + $folderinfo[$value] = Array('folderid'=>$matches[1], 'enabled'=>1); + } +} +$scannerinfo->enableFoldersForScan($folderinfo); + +include('modules/Settings/MailScanner/MailScannerInfo.php'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolderUpdate.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolderUpdate.php new file mode 100644 index 00000000..5319b493 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerFolderUpdate.php @@ -0,0 +1,39 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH","themes/$theme/images/"); + +$scannername = $_REQUEST['scannername']; +$scannerinfo = new Vtiger_MailScannerInfo($scannername); + +$mailbox = new Vtiger_MailBox($scannerinfo); +$isconnected = $mailbox->connect(); +if($isconnected) { + $folders = $mailbox->getFolders(); + $scannerinfo->updateFolderInfo($folders); +} + +$smarty->assign("SCANNERINFO", $scannerinfo->getAsMap()); +$smarty->assign("FOLDERINFO", $scannerinfo->getFolderInfo()); + +$smarty->display('MailScanner/MailScannerFolder.tpl'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerInfo.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerInfo.php new file mode 100644 index 00000000..d2543688 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerInfo.php @@ -0,0 +1,32 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH","themes/$theme/images/"); + +$scannerinfo = new Vtiger_MailScannerInfo('DEFAULT'); + +$smarty->assign("SCANNERINFO", $scannerinfo->getAsMap()); +$smarty->assign("APP_KEY", $application_unique_key); + +$smarty->display('MailScanner/MailScannerInfo.tpl'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRule.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRule.php new file mode 100644 index 00000000..8cf0ce2e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRule.php @@ -0,0 +1,32 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH","themes/$theme/images/"); + +$smarty->assign("SCANNERINFO", $scannerinfo->getAsMap()); +$smarty->assign("SCANNERRULES", $scannerinfo->rules); + +$smarty->display('MailScanner/MailScannerRule.tpl'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleDelete.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleDelete.php new file mode 100644 index 00000000..f4f0fb48 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleDelete.php @@ -0,0 +1,20 @@ +delete(); + +include('modules/Settings/MailScanner/MailScannerRule.php'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleEdit.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleEdit.php new file mode 100644 index 00000000..2ec62406 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleEdit.php @@ -0,0 +1,34 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH","themes/$theme/images/"); + +$scannername = $_REQUEST['scannername']; +$scannerruleid= $_REQUEST['ruleid']; +$scannerinfo = new Vtiger_MailScannerInfo($scannername); +$scannerrule = new Vtiger_MailScannerRule($scannerruleid); + +$smarty->assign("SCANNERINFO", $scannerinfo->getAsMap()); +$smarty->assign("SCANNERRULE", $scannerrule); + +$smarty->display('MailScanner/MailScannerRuleEdit.tpl'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleMove.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleMove.php new file mode 100644 index 00000000..0f081e7b --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleMove.php @@ -0,0 +1,26 @@ + diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleSave.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleSave.php new file mode 100644 index 00000000..dc785d96 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerRuleSave.php @@ -0,0 +1,40 @@ +scannerid = $scannerinfo->scannerid; +$scannerrule->fromaddress = $_REQUEST['rule_from']; +$scannerrule->toaddress = $_REQUEST['rule_to']; +$scannerrule->subjectop = $_REQUEST['rule_subjectop']; +$scannerrule->subject = $_REQUEST['rule_subject']; +$scannerrule->bodyop = $_REQUEST['rule_bodyop']; +$scannerrule->body = $_REQUEST['rule_body']; +$scannerrule->matchusing= $_REQUEST['rule_matchusing']; + +$scannerrule->update(); + +$scannerrule->updateAction($scanneractionid, $_REQUEST['rule_actiontext']); + +include('modules/Settings/MailScanner/MailScannerRule.php'); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerSave.php b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerSave.php new file mode 100644 index 00000000..716648c2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/MailScannerSave.php @@ -0,0 +1,75 @@ +scannername = trim($_REQUEST['mailboxinfo_scannername']); +$newscannerinfo->server = trim($_REQUEST['mailboxinfo_server']); +$newscannerinfo->protocol = trim($_REQUEST['mailboxinfo_protocol']); +$newscannerinfo->username = trim($_REQUEST['mailboxinfo_username']); +$newscannerinfo->password = trim($_REQUEST['mailboxinfo_password']); +$newscannerinfo->ssltype = trim($_REQUEST['mailboxinfo_ssltype']); +$newscannerinfo->sslmethod = trim($_REQUEST['mailboxinfo_sslmethod']); +$newscannerinfo->server = trim($_REQUEST['mailboxinfo_server']); +$newscannerinfo->searchfor = trim($_REQUEST['mailboxinfo_searchfor']); +$newscannerinfo->markas = trim($_REQUEST['mailboxinfo_markas']); +$newscannerinfo->isvalid =($_REQUEST['mailboxinfo_enable'] == 'true')? true : false; + +// Rescan all folders on next run? +$rescanfolder = ($_REQUEST['mailboxinfo_rescan_folders'] == 'true')? true : false; + +$isconnected = false; + +$scannerinfo = new Vtiger_MailScannerInfo('DEFAULT'); + +if(!$scannerinfo->compare($newscannerinfo)) { + $mailbox = new Vtiger_MailBox($newscannerinfo); + + $isconnected = $mailbox->connect(); + if($isconnected) $newscannerinfo->connecturl = $mailbox->_imapurl; + +} else { + $isconnected = true; + $scannerinfo->isvalid = $newscannerinfo->isvalid; // Copy new value + $newscannerinfo = $scannerinfo; +} + +if(!$isconnected) { + require_once('Smarty_setup.php'); + global $app_strings, $mod_strings, $currentModule, $theme, $current_language; + + $smarty = new vtigerCRM_Smarty; + $smarty->assign("MOD", return_module_language($current_language,'Settings')); + $smarty->assign("CMOD", $mod_strings); + $smarty->assign("APP", $app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH","themes/$theme/images/"); + + $smarty->assign("SCANNERINFO", $newscannerinfo->getAsMap()); + $smarty->assign("CONNECTFAIL", "Connecting to mailbox failed!"); + $smarty->display('MailScanner/MailScannerEdit.tpl'); +} else { + + $mailServerChanged = $scannerinfo->update($newscannerinfo); + + $scannerinfo->updateAllFolderRescan($rescanfolder); + + // Update lastscan on all the available folders. + if($mailServerChanged && $mailbox) { + $folders = $mailbox->getFolders(); + foreach($folders as $folder) $scannerinfo->updateLastscan($folder); + } + + require('modules/Settings/MailScanner/MailScannerInfo.php'); +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailAttachmentMIME.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailAttachmentMIME.php new file mode 100644 index 00000000..0e7fa73c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailAttachmentMIME.php @@ -0,0 +1,252 @@ +getType($filename); + } +} + +/** +Copyright (C) 2002 Jason Sheets . +All rights reserved. + +THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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. +**/ + +/** + Name: PHP MimeType Class + + Version: 1.0 + Date Released: 10/20/02 + + Description: This class allows a PHP script to determine the mime type + a file based on the file extension. This class is handy for PHP versions + without the benefit of other tools to determine the mime type. The class + defaults to octet-stream so if the file type is not recognized the user + is presented with a file download prompt. + + NOTES: The mime types for this version are based on Apache 1.3.27 + mime types may change or need to be added in the future, the mime types + are stored in an array so that an awk or other script can automatically + generate the code to make the array. + + Usage: + + First an instance of the mimetype class must be created, then the + getType method should be called with the filename. It will return + the mime type, an example follows. + + Example: + + $mimetype = new mimetype(); + print $mimetype->getType('acrobat.pdf'); + + Author: Jason Sheets + + License: This script is distributed under the BSD License, you are free + to use, or modify it however you like. If you find this script useful please + e-mail me. +**/ + +class mimetype { + function getType($filename) { + // get base name of the filename provided by user + $filename = basename($filename); + + // break file into parts seperated by . + $filename = explode('.', $filename); + + // take the last part of the file to get the file extension + $filename = $filename[count($filename)-1]; + + // find mime type + return $this->privFindType($filename); + } + + function privFindType($ext) { + // create mimetypes array + $mimetypes = $this->privBuildMimeArray(); + + // return mime type for extension + if (isset($mimetypes[$ext])) { + return $mimetypes[$ext]; + // if the extension wasn't found return octet-stream + } else { + return 'application/octet-stream'; + } + + } + + function privBuildMimeArray() { + return array( + "ez" => "application/andrew-inset", + "hqx" => "application/mac-binhex40", + "cpt" => "application/mac-compactpro", + "doc" => "application/msword", + "bin" => "application/octet-stream", + "dms" => "application/octet-stream", + "lha" => "application/octet-stream", + "lzh" => "application/octet-stream", + "exe" => "application/octet-stream", + "class" => "application/octet-stream", + "so" => "application/octet-stream", + "dll" => "application/octet-stream", + "oda" => "application/oda", + "pdf" => "application/pdf", + "ai" => "application/postscript", + "eps" => "application/postscript", + "ps" => "application/postscript", + "smi" => "application/smil", + "smil" => "application/smil", + "wbxml" => "application/vnd.wap.wbxml", + "wmlc" => "application/vnd.wap.wmlc", + "wmlsc" => "application/vnd.wap.wmlscriptc", + "bcpio" => "application/x-bcpio", + "vcd" => "application/x-cdlink", + "pgn" => "application/x-chess-pgn", + "cpio" => "application/x-cpio", + "csh" => "application/x-csh", + "dcr" => "application/x-director", + "dir" => "application/x-director", + "dxr" => "application/x-director", + "dvi" => "application/x-dvi", + "spl" => "application/x-futuresplash", + "gtar" => "application/x-gtar", + "hdf" => "application/x-hdf", + "js" => "application/x-javascript", + "skp" => "application/x-koan", + "skd" => "application/x-koan", + "skt" => "application/x-koan", + "skm" => "application/x-koan", + "latex" => "application/x-latex", + "nc" => "application/x-netcdf", + "cdf" => "application/x-netcdf", + "sh" => "application/x-sh", + "shar" => "application/x-shar", + "swf" => "application/x-shockwave-flash", + "sit" => "application/x-stuffit", + "sv4cpio" => "application/x-sv4cpio", + "sv4crc" => "application/x-sv4crc", + "tar" => "application/x-tar", + "tcl" => "application/x-tcl", + "tex" => "application/x-tex", + "texinfo" => "application/x-texinfo", + "texi" => "application/x-texinfo", + "t" => "application/x-troff", + "tr" => "application/x-troff", + "roff" => "application/x-troff", + "man" => "application/x-troff-man", + "me" => "application/x-troff-me", + "ms" => "application/x-troff-ms", + "ustar" => "application/x-ustar", + "src" => "application/x-wais-source", + "xhtml" => "application/xhtml+xml", + "xht" => "application/xhtml+xml", + "zip" => "application/zip", + "au" => "audio/basic", + "snd" => "audio/basic", + "mid" => "audio/midi", + "midi" => "audio/midi", + "kar" => "audio/midi", + "mpga" => "audio/mpeg", + "mp2" => "audio/mpeg", + "mp3" => "audio/mpeg", + "aif" => "audio/x-aiff", + "aiff" => "audio/x-aiff", + "aifc" => "audio/x-aiff", + "m3u" => "audio/x-mpegurl", + "ram" => "audio/x-pn-realaudio", + "rm" => "audio/x-pn-realaudio", + "rpm" => "audio/x-pn-realaudio-plugin", + "ra" => "audio/x-realaudio", + "wav" => "audio/x-wav", + "pdb" => "chemical/x-pdb", + "xyz" => "chemical/x-xyz", + "bmp" => "image/bmp", + "gif" => "image/gif", + "ief" => "image/ief", + "jpeg" => "image/jpeg", + "jpg" => "image/jpeg", + "jpe" => "image/jpeg", + "png" => "image/png", + "tiff" => "image/tiff", + "tif" => "image/tif", + "djvu" => "image/vnd.djvu", + "djv" => "image/vnd.djvu", + "wbmp" => "image/vnd.wap.wbmp", + "ras" => "image/x-cmu-raster", + "pnm" => "image/x-portable-anymap", + "pbm" => "image/x-portable-bitmap", + "pgm" => "image/x-portable-graymap", + "ppm" => "image/x-portable-pixmap", + "rgb" => "image/x-rgb", + "xbm" => "image/x-xbitmap", + "xpm" => "image/x-xpixmap", + "xwd" => "image/x-windowdump", + "igs" => "model/iges", + "iges" => "model/iges", + "msh" => "model/mesh", + "mesh" => "model/mesh", + "silo" => "model/mesh", + "wrl" => "model/vrml", + "vrml" => "model/vrml", + "css" => "text/css", + "html" => "text/html", + "htm" => "text/html", + "asc" => "text/plain", + "txt" => "text/plain", + "rtx" => "text/richtext", + "rtf" => "text/rtf", + "sgml" => "text/sgml", + "sgm" => "text/sgml", + "tsv" => "text/tab-seperated-values", + "wml" => "text/vnd.wap.wml", + "wmls" => "text/vnd.wap.wmlscript", + "etx" => "text/x-setext", + "xml" => "text/xml", + "xsl" => "text/xml", + "mpeg" => "video/mpeg", + "mpg" => "video/mpeg", + "mpe" => "video/mpeg", + "qt" => "video/quicktime", + "mov" => "video/quicktime", + "mxu" => "video/vnd.mpegurl", + "avi" => "video/x-msvideo", + "movie" => "video/x-sgi-movie", + "ice" => "x-conference-xcooltalk" + ); + } +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailBox.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailBox.php new file mode 100644 index 00000000..16687584 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailBox.php @@ -0,0 +1,222 @@ +debug)) { $log->debug($message); } + else if( ($force || $this->debug) ) echo "$message\n"; + } + + /** + * Constructor + */ + function __construct($scannerinfo) { + $this->_scannerinfo = $scannerinfo; + $this->_mailboxsettings = $scannerinfo->getAsMap(); + + if($this->_mailboxsettings[ssltype] == '') $this->_mailboxsettings[ssltype] = 'notls'; + if($this->_mailboxsettings[sslmethod]== '') $this->_mailboxsettings[sslmethod] = 'novalidate-cert'; + + if($this->_mailboxsettings[protocol] == 'pop3') { $port = '110'; } + else { + if($this->_mailboxsettings[ssltype] == 'tls' || + $this->_mailboxsettings[ssltype] == 'ssl') { + $port = '993'; + } + else $port = '143'; + } + $this->_mailboxsettings[port] = $port; + } + + /** + * Connect to mail box folder. + */ + function connect($folder='INBOX') { + $imap = false; + $mailboxsettings = $this->_mailboxsettings; + + $isconnected = false; + + // Connect using last successful url + if($mailboxsettings['connecturl']) { + $connecturl = $mailboxsettings['connecturl']; + $this->log("Trying to connect using connecturl $connecturl$folder", true); + $imap = @imap_open("$connecturl$folder", $mailboxsettings[username], $mailboxsettings[password]); + if($imap) { + $this->_imapurl = $connecturl; + $this->_imapfolder = $folder; + $isconnected = true; + + $this->log("Successfully connected", true); + } + } + + if(!$imap) { + $connectString = '{'. "$mailboxsettings[server]:$mailboxsettings[port]/$mailboxsettings[protocol]/$mailboxsettings[ssltype]/$mailboxsettings[sslmethod]" ."}"; + $connectStringShort = '{'. "$mailboxsettings[server]/$mailboxsettings[protocol]:$mailboxsettings[port]" ."}"; + + $this->log("Trying to connect using $connectString$folder", true); + if(!$imap = @imap_open("$connectString$folder", $mailboxsettings[username], $mailboxsettings[password])) { + $this->log("Connect failed using $connectString$folder, trying with $connectStringShort$folder...", true); + $imap = @imap_open("$connectStringShort$folder", $mailboxsettings[username], $mailboxsettings[password]); + if($imap) { + $this->_imapurl = $connectStringShort; + $this->_imapfolder = $folder; + $isconnected = true; + $this->log("Successfully connected", true); + } else { + $this->log("Connect failed using $connectStringShort$folder", true); + } + } else { + $this->_imapurl = $connectString; + $this->_imapfolder = $folder; + $isconnected = true; + $this->log("Successfully connected", true); + } + } + + $this->_imap = $imap; + return $isconnected; + } + + /** + * Open the mailbox folder. + * @param $folder Folder name to open + * @param $reopen set to true for re-opening folder if open (default=false) + * @return true if connected, false otherwise + */ + function open($folder, $reopen=false) { + /** Avoid re-opening of the box if not requested. */ + if(!$reopen && ($folder == $this->_imapfolder)) return true; + + if(!$this->_imap) return $this->connect($folder); + + $mailboxsettings = $this->_mailboxsettings; + + $isconnected = false; + $connectString = $this->_imapurl; + $this->log("Trying to open folder using $connectString$folder"); + $imap = @imap_open("$connectString$folder", $mailboxsettings[username], $mailboxsettings[password]); + if($imap) { + + // Perform cleanup task before re-initializing the connection + $this->close(); + + $this->_imapfolder = $folder; + $this->_imap = $imap; + $isconnected = true; + } + return $isconnected; + } + + /** + * Get the mails based on searchquery. + * @param $folder Folder in which mails to be read. + * @param $searchQuery IMAP query, (default false: fetches mails newer from lastscan) + * @return imap_search records or false + */ + function search($folder, $searchQuery=false) { + if(!$searchQuery) { + $lastscanOn = $this->_scannerinfo->getLastscan($folder); + $searchfor = $this->_scannerinfo->searchfor; + + if($searchfor && $lastscanOn) { + if($searchfor == 'ALL') { + $searchQuery = "SINCE $lastscanOn"; + } else { + $searchQuery = "$useSearchFor SINCE $lastscanOn"; + } + } else { + $searchQuery = $lastscanOn? "SINCE $lastscanOn" : "BEFORE ". date('d-M-Y'); + } + } + if($this->open($folder)) { + $this->log("Searching mailbox[$folder] using query: $searchQuery"); + return imap_search($this->_imap, $searchQuery); + } + return false; + } + + /** + * Get folder names (as list) for the given mailbox connection + */ + function getFolders() { + $folders = false; + if($this->_imap) { + $imapfolders = imap_list($this->_imap, $this->_imapurl, '*'); + if($imapfolders) { + foreach($imapfolders as $imapfolder) { + $folders[] = substr($imapfolder, strlen($this->_imapurl)); + } + } + } + return $folders; + } + + /** + * Fetch the email based on the messageid. + * @param $messageid messageid of the email + * @param $fetchbody set to false to defer fetching the body, (default: true) + */ + function getMessage($messageid, $fetchbody=true) { + return new Vtiger_MailRecord($this->_imap, $messageid, $fetchbody); + } + + /** + * Mark the message in the mailbox. + */ + function markMessage($messageid) { + $markas = $this->_scannerinfo->markas; + if($this->_imap && $markas) { + if(strtoupper($markas) == 'SEEN') $markas = "\\Seen"; + imap_setflag_full($this->_imap, $messageid, $markas); + } + } + + /** + * Close the open IMAP connection. + */ + function close() { + if($this->_needExpunge) { + imap_expunge($this->_imap); + } + $this->_needExpunge = false; + if($this->_imap) { + imap_close($this->_imap); + $this->_imap = false; + } + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailRecord.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailRecord.php new file mode 100644 index 00000000..23f745c9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailRecord.php @@ -0,0 +1,318 @@ +__toString(); + + global $log; + if($log && $this->debug) { $log->debug($message); } + else if($this->debug) { + echo var_export($message, true) . "\n"; + } + } + + /** + * String representation of the object. + */ + function __toString() { + $tostring = ''; + $tostring .= 'FROM: ['. implode(',', $this->_from) . ']'; + $tostring .= ',TO: [' . implode(',', $this->_to) . ']'; + if(!empty($this->_cc)) $tostring .= ',CC: [' . implode(',', $this->_cc) . ']'; + if(!empty($this->_bcc))$tostring .= ',BCC: [' . implode(',', $this->_bcc) . ']'; + $tostring .= ',DATE: ['. $this->_date . ']'; + $tostring .= ',SUBJECT: ['. $this->_subject . ']'; + return $tostring; + } + + /** + * Constructor. + */ + function __construct($imap, $messageid, $fetchbody=true) { + $this->__parseHeader($imap, $messageid); + if($fetchbody) $this->__parseBody($imap, $messageid); + } + + /** + * Get body content as Text. + */ + function getBodyText($striptags=true) { + $bodytext = $this->_body; + + if($this->_plainmessage) { + $bodytext = $this->_plainmessage; + } else if($this->_isbodyhtml) { + // TODO This conversion can added multiple lines if + // content is displayed directly on HTML page + $bodytext = preg_replace("/
    /", "\n", $bodytext); + $bodytext = strip_tags($bodytext); + } + return $bodytext; + } + + /** + * Get body content as HTML. + */ + function getBodyHTML() { + $bodyhtml = $this->_body; + if(!$this->_isbodyhtml) { + $bodyhtml = preg_replace( Array("/\r\n/", "/\n/"), Array('
    ','
    '), $bodyhtml ); + } + return $bodyhtml; + } + + /** + * Fetch the mail body from server. + */ + function fetchBody($imap, $messageid) { + if(!$this->_bodyparsed) $this->__parseBody($imap, $messageid); + } + + /** + * Parse the email id from the mail header text. + * @access private + */ + function __getEmailIdList($inarray) { + if(empty($inarray)) return Array(); + $emails = Array(); + foreach($inarray as $emailinfo) { + $emails[] = $emailinfo->mailbox . '@' . $emailinfo->host; + } + return $emails; + } + + /** + * Helper function to convert the encoding of input to target charset. + */ + static function __convert_encoding($input, $to, $from = false) { + if(function_exists('mb_convert_encoding')) { + if(!$from) $from = mb_detect_encoding($input); + + if(strtolower(trim($to)) == strtolower(trim($from))) { + return $input; + } else { + return mb_convert_encoding($input, $to, $from); + } + } + return $input; + } + + /** + * MIME decode function to parse IMAP header or mail information + */ + static function __mime_decode($input, &$words=null, $targetEncoding='UTF-8') { + if(is_null($words)) $words = array(); + $returnvalue = $input; + + if(preg_match_all('/=\?([^\?]+)\?([^\?]+)\?([^\?]+)\?=/', $input, $matches)) { + $totalmatches = count($matches[0]); + + for($index = 0; $index < $totalmatches; ++$index) { + $charset = $matches[1][$index]; + $encoding= strtoupper($matches[2][$index]); // B - base64 or Q - quoted printable + $data = $matches[3][$index]; + + if($encoding == 'B') { + $decodevalue = base64_decode($data); + } else if($encoding == 'Q') { + $decodevalue = quoted_printable_decode($data); + } + $value = self::__convert_encoding($decodevalue, $targetEncoding, $charset); + array_push($words, $value); + } + } + if(!empty($words)) { + $returnvalue = implode('', $words); + } + return $returnvalue; + } + + /** + * MIME encode function to prepare input to target charset supported by normal IMAP clients. + */ + static function __mime_encode($input, $encoding='Q', $charset='iso-8859-1') { + $returnvalue = $input; + $encoded = false; + + if(strtoupper($encoding) == 'B' ) { + $returnvalue = self::__convert_encoding($input, $charset); + $returnvalue = base64_encode($returnvalue); + $encoded = true; + } else { + $returnvalue = self::__convert_encoding($input, $charset); + if(function_exists('imap_qprint')) { + $returnvalue = imap_qprint($returnvalue); + $encoded = true; + } else { + // TODO: Handle case when imap_qprint is not available. + } + } + if($encoded) { + $returnvalue = "=?$charset?$encoding?$returnvalue?="; + } + return $returnvalue; + } + + /** + * Parse header of the email. + * @access private + */ + function __parseHeader($imap, $messageid) { + $this->_from = Array(); + $this->_to = Array(); + + $mailheader = imap_headerinfo($imap, $messageid); + + $this->_uniqueid = $mailheader->message_id; + + $this->_from = $this->__getEmailIdList($mailheader->from); + $this->_to = $this->__getEmailIdList($mailheader->to); + $this->_cc = $this->__getEmailIdList($mailheader->cc); + $this->_bcc = $this->__getEmailIdList($mailheader->bcc); + + $this->_date = $mailheader->udate; + + $this->_subject = self::__mime_decode($mailheader->subject); + if(!$this->_subject) $this->_subject = 'Untitled'; + } + // Modified: http://in2.php.net/manual/en/function.imap-fetchstructure.php#85685 + function __parseBody($imap, $messageid) { + $structure = imap_fetchstructure($imap, $messageid); + + $this->_plainmessage = ''; + $this->_htmlmessage = ''; + $this->_body = ''; + $this->_isbodyhtml = false; + + if($structure->parts) { /* multipart */ + foreach($structure->parts as $partno0=>$p) { + $this->__getpart($imap, $messageid, $p, $partno0+1); + } + } else { /* not multipart */ + $this->__getpart($imap, $messageid, $structure, 0); + } + + // Set the body (either plain or html content) + if($this->_htmlmessage != '') { + $this->_body = $this->_htmlmessage; + $this->_isbodyhtml = true; + } else { + $this->_body = $this->_plainmessage; + } + + if($this->_attachments) { + $this->log("Attachments: "); + $this->log(array_keys($this->_attachments)); + } + + $this->_bodyparsed = true; + } + // Modified: http://in2.php.net/manual/en/function.imap-fetchstructure.php#85685 + function __getpart($imap, $messageid, $p, $partno) { + // $partno = '1', '2', '2.1', '2.1.3', etc if multipart, 0 if not multipart + + // DECODE DATA + $data = ($partno)? + imap_fetchbody($imap,$messageid,$partno): // multipart + imap_body($imap,$messageid); // not multipart + + // Any part may be encoded, even plain text messages, so check everything. + if ($p->encoding==4) $data = quoted_printable_decode($data); + elseif ($p->encoding==3) $data = base64_decode($data); + // no need to decode 7-bit, 8-bit, or binary + + // PARAMETERS + // get all parameters, like charset, filenames of attachments, etc. + $params = array(); + if ($p->parameters) { + foreach ($p->parameters as $x) $params[ strtolower( $x->attribute ) ] = $x->value; + } + if ($p->dparameters) { + foreach ($p->dparameters as $x) $params[ strtolower( $x->attribute ) ] = $x->value; + } + + // ATTACHMENT + // Any part with a filename is an attachment, + // so an attached text file (type 0) is not mistaken as the message. + if ($params['filename'] || $params['name']) { + // filename may be given as 'Filename' or 'Name' or both + $filename = ($params['filename'])? $params['filename'] : $params['name']; + // filename may be encoded, so see imap_mime_header_decode() + if(!$this->_attachments) $this->_attachments = Array(); + $this->_attachments[$filename] = $data; // TODO: this is a problem if two files have same name + } + + // TEXT + elseif ($p->type==0 && $data) { + $this->_charset = $params['charset']; // assume all parts are same charset + $data = self::__convert_encoding($data, 'UTF-8', $this->_charset); + + // Messages may be split in different parts because of inline attachments, + // so append parts together with blank row. + if (strtolower($p->subtype)=='plain') $this->_plainmessage .= trim($data) ."\n\n"; + else $this->_htmlmessage .= $data ."

    "; + } + + // EMBEDDED MESSAGE + // Many bounce notifications embed the original message as type 2, + // but AOL uses type 1 (multipart), which is not handled here. + // There are no PHP functions to parse embedded messages, + // so this just appends the raw source to the main message. + elseif ($p->type==2 && $data) { + $this->_plainmessage .= trim($data) ."\n\n"; + } + + // SUBPART RECURSION + if ($p->parts) { + foreach ($p->parts as $partno0=>$p2) + $this->__getpart($imap,$messageid,$p2,$partno.'.'.($partno0+1)); // 1.2, 1.2.1, etc. + } + } +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScanner.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScanner.php new file mode 100644 index 00000000..2ad748fb --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScanner.php @@ -0,0 +1,412 @@ +debug) { $log->debug($message); } + else if($this->debug) echo "$message\n"; + } + + /** + * Constructor. + */ + function __construct($scannerinfo) { + $this->_scannerinfo = $scannerinfo; + } + + /** + * Get mailbox instance configured for the scan + */ + function getMailBox() { + if(!$this->_mailbox) { + $this->_mailbox = new Vtiger_MailBox($this->_scannerinfo); + $this->_mailbox->debug = $this->debug; + } + return $this->_mailbox; + } + + /** + * Start Scanning. + */ + function performScanNow() { + // Check if rules exists to proceed + $rules = $this->_scannerinfo->rules; + + if(empty($rules)) { + $this->log("No rules setup for scanner [". $this->_scannerinfo->scannername . "] SKIPING\n"); + return; + } + + // Build ignore folder list + $ignoreFolders = Array() + $this->_generalIgnoreFolders; + $folderinfoList = $this->_scannerinfo->getFolderInfo(); + foreach($folderinfoList as $foldername=>$folderinfo) { + if(!$folderinfo[enabled]) $ignoreFolders[] = $foldername; + } + + // Get mailbox instance to work with + $mailbox = $this->getMailBox(); + $mailbox->connect(); + + /** Loop through all the folders. */ + $folders = $mailbox->getFolders(); + + if($folders) $this->log("Folders found: " . implode(',', $folders) . "\n"); + + foreach($folders as $lookAtFolder) { + // Skip folder scanning? + if(in_array($lookAtFolder, $ignoreFolders)) { + $this->log("\nIgnoring Folder: $lookAtFolder\n"); + continue; + } + // If a new folder has been added we should avoid scanning it + if(!isset($folderinfoList[$lookAtFolder])) { + $this->log("\nSkipping New Folder: $lookAtFolder\n"); + continue; + } + + // Search for mail in the folder + $mailsearch = $mailbox->search($lookAtFolder); + $this->log($mailsearch? "Total Mails Found in [$lookAtFolder]: " . count($mailsearch) : "No Mails Found in [$lookAtFolder]"); + + // No emails? Continue with next folder + if(empty($mailsearch)) continue; + + // Loop through each of the email searched + foreach($mailsearch as $messageid) { + // Fetch only header part first, based on account lookup fetch the body. + $mailrecord = $mailbox->getMessage($messageid, false); + $mailrecord->debug = $mailbox->debug; + $mailrecord->log(); + + // If the email is already scanned & rescanning is not set, skip it + if($this->isMessageScanned($mailrecord, $lookAtFolder)) { + $this->log("\nMessage already scanned [$mailrecord->_subject], IGNORING...\n"); + unset($mailrecord); + continue; + } + + // Apply rules configured for the mailbox + $crmid = false; + foreach($rules as $mailscannerrule) { + $crmid = $this->applyRule($mailscannerrule, $mailrecord, $mailbox, $messageid); + if($crmid) { + break; // Rule was successfully applied and action taken + } + } + // Mark the email message as scanned + $this->markMessageScanned($mailrecord, $crmid); + $mailbox->markMessage($messageid); + + /** Free the resources consumed. */ + unset($mailrecord); + } + /* Update lastscan for this folder and reset rescan flag */ + // TODO: Update lastscan only if all the mail searched was parsed successfully? + $rescanFolderFlag = false; + $this->updateLastScan($lookAtFolder, $rescanFolderFlag); + } + // Close the mailbox at end + $mailbox->close(); + } + + /** + * Apply all the rules configured for a mailbox on the mailrecord. + */ + function applyRule($mailscannerrule, $mailrecord, $mailbox, $messageid) { + // If no actions are set, don't proceed + if(empty($mailscannerrule->actions)) return false; + + // Check if rule is defined for the body + $bodyrule = $mailscannerrule->hasBodyRule(); + + if($bodyrule) { + // We need the body part for rule evaluation + $mailrecord->fetchBody($mailbox->_imap, $messageid); + } + + // Apply rule to check if record matches the criteria + $matchresult = $mailscannerrule->applyAll($mailrecord, $bodyrule); + + // If record matches the conditions fetch body to take action. + $crmid = false; + if($matchresult) { + $mailrecord->fetchBody($mailbox->_imap, $messageid); + $crmid = $mailscannerrule->takeAction($this, $mailrecord, $matchresult); + } + // Return the CRMID + return $crmid; + } + + /** + * Mark the email as scanned. + */ + function markMessageScanned($mailrecord, $crmid=false) { + global $adb; + if($crmid === false) $crmid = null; + // TODO Make sure we have unique entry + $adb->pquery("INSERT INTO vtiger_mailscanner_ids(scannerid, messageid, crmid) VALUES(?,?,?)", + Array($this->_scannerinfo->scannerid, $mailrecord->_uniqueid, $crmid)); + } + + /** + * Check if email was scanned. + */ + function isMessageScanned($mailrecord, $lookAtFolder) { + global $adb; + $messages = $adb->pquery("SELECT * FROM vtiger_mailscanner_ids WHERE scannerid=? AND messageid=?", + Array($this->_scannerinfo->scannerid, $mailrecord->_uniqueid)); + + $folderRescan = $this->_scannerinfo->needRescan($lookAtFolder); + $isScanned = false; + + if($adb->num_rows($messages)) { + $isScanned = true; + + // If folder is scheduled for rescan and earlier message was not acted upon? + $relatedCRMId = $adb->query_result($messages, 0, 'crmid'); + + if($folderRescan && empty($relatedCRMId)) { + $adb->pquery("DELETE FROM vtiger_mailscanner_ids WHERE scannerid=? AND messageid=?", + Array($this->_scannerinfo->scannerid, $mailrecord->_uniqueid)); + $isScanned = false; + } + } + return $isScanned; + } + + /** + * Update last scan on the folder. + */ + function updateLastscan($folder) { + $this->_scannerinfo->updateLastscan($folder); + } + + /** + * Convert string to integer value. + * @param $strvalue + * @returns false if given contain non-digits, else integer value + */ + function __toInteger($strvalue) { + $ival = intval($strvalue); + $intvalstr = "$ival"; + if(strlen($strvalue) == strlen($intvalstr)) { + return $ival; + } + return false; + } + + /** Lookup functionality. */ + var $_cachedContactIds = Array(); + var $_cachedAccountIds = Array(); + var $_cachedTicketIds = Array(); + + var $_cachedAccounts = Array(); + var $_cachedContacts = Array(); + var $_cachedTickets = Array(); + + /** + * Lookup Contact record based on the email given. + */ + function LookupContact($email) { + global $adb; + if($this->_cachedContactIds[$email]) { + $this->log("Reusing Cached Contact Id for email: $email"); + return $this->_cachedContactIds[$email]; + } + $contactid = false; + $contactres = $adb->pquery("SELECT contactid FROM vtiger_contactdetails WHERE email=?", Array($email)); + if($adb->num_rows($contactres)) { + $contactid = $adb->query_result($contactres, 0, 'contactid'); + $crmres = $adb->pquery("SELECT deleted FROM vtiger_crmentity WHERE crmid=?", Array($contactid)); + if($adb->num_rows($crmres) && $adb->query_result($crmres, 0, 'deleted')) $contactid = false; + } + if($contactid) { + $this->log("Caching Contact Id found for email: $email"); + $this->_cachedContactIds[$email] = $contactid; + } else { + $this->log("No matching Contact found for email: $email"); + } + return $contactid; + } + /** + * Lookup Account record based on the email given. + */ + function LookupAccount($email) { + global $adb; + if($this->_cachedAccountIds[$email]) { + $this->log("Reusing Cached Account Id for email: $email"); + return $this->_cachedAccountIds[$email]; + } + + $accountid = false; + $accountres = $adb->pquery("SELECT accountid FROM vtiger_account WHERE email1=? OR email2=?", Array($email, $email)); + if($adb->num_rows($accountres)) { + $accountid = $adb->query_result($accountres, 0, 'accountid'); + $crmres = $adb->pquery("SELECT deleted FROM vtiger_crmentity WHERE crmid=?", Array($accountid)); + if($adb->num_rows($crmres) && $adb->query_result($crmres, 0, 'deleted')) $accountid = false; + } + if($accountid) { + $this->log("Caching Account Id found for email: $email"); + $this->_cachedAccountIds[$email] = $accountid; + } else { + $this->log("No matching Account found for email: $email"); + } + return $accountid; + } + /** + * Lookup Ticket record based on the subject or id given. + */ + function LookupTicket($subjectOrId) { + global $adb; + + $checkTicketId = $this->__toInteger($subjectOrId); + if(!$checkTicketId) { + $ticketres = $adb->pquery("SELECT ticketid FROM vtiger_troubletickets WHERE title = ?", Array($subjectOrId)); + if($adb->num_rows($ticketres)) $checkTicketId = $adb->query_result($ticketres, 0, 'ticketid'); + } + if(!$checkTicketId) return false; + + if($this->_cachedTicketIds[$checkTicketId]) { + $this->log("Reusing Cached Ticket Id for: $subjectOrId"); + return $this->_cachedTicketIds[$checkTicketId]; + } + + $ticketid = false; + if($checkTicketId) { + $crmres = $adb->pquery("SELECT setype, deleted FROM vtiger_crmentity WHERE crmid=?", Array($checkTicketId)); + if($adb->num_rows($crmres)) { + if($adb->query_result($crmres, 0, 'setype') == 'HelpDesk' && + $adb->query_result($crmres, 0, 'deleted') == '0') $ticketid = $checkTicketId; + } + } + if($ticketid) { + $this->log("Caching Ticket Id found for: $subjectOrId"); + $this->_cachedTicketIds[$checkTicketId] = $ticketid; + } else { + $this->log("No matching Ticket found for: $subjectOrId"); + } + return $ticketid; + } + + /** + * Get Account record information based on email. + */ + function GetAccountRecord($email) { + require_once('modules/Accounts/Accounts.php'); + $accountid = $this->LookupAccount($email); + $account_focus = false; + if($accountid) { + if($this->_cachedAccounts[$accountid]) { + $account_focus = $this->_cachedAccounts[$accountid]; + $this->log("Reusing Cached Account [" . $account_focus->column_fields[accountname] . "]"); + } else { + $account_focus = new Accounts(); + $account_focus->retrieve_entity_info($accountid, 'Accounts'); + $account_focus->id = $accountid; + + $this->log("Caching Account [" . $account_focus->column_fields[accountname] . "]"); + $this->_cachedAccounts[$accountid] = $account_focus; + } + } + return $account_focus; + } + /** + * Get Contact record information based on email. + */ + function GetContactRecord($email) { + require_once('modules/Contacts/Contacts.php'); + $contactid = $this->LookupContact($email); + $contact_focus = false; + if($contactid) { + if($this->_cachedContacts[$contactid]) { + $contact_focus = $this->_cachedContacts[$contactid]; + $this->log("Reusing Cached Contact [" . $contact_focus->column_fields[lastname] . + '-' . $contact_focus->column_fields[firstname] . "]"); + } else { + $contact_focus = new Contacts(); + $contact_focus->retrieve_entity_info($contactid, 'Contacts'); + $contact_focus->id = $contactid; + + $this->log("Caching Contact [" . $contact_focus->column_fields[lastname] . + '-' . $contact_focus->column_fields[firstname] . "]"); + $this->_cachedContacts[$contactid] = $contact_focus; + } + } + return $contact_focus; + } + + /** + * Lookup Contact or Account based on from email and with respect to given CRMID + */ + function LookupContactOrAccount($fromemail, $checkWithId=false) { + $recordid = $this->LookupContact($fromemail); + if($checkWithId && $recordid != $checkWithId) { + $recordid = $this->LookupAccount($fromemail); + if($checkWithId && $recordid != $checkWithId) $recordid = false; + } + return $recordid; + } + + /** + * Get Ticket record information based on subject or id. + */ + function GetTicketRecord($subjectOrId, $fromemail=false) { + require_once('modules/HelpDesk/HelpDesk.php'); + $ticketid = $this->LookupTicket($subjectOrId); + $ticket_focus = false; + if($ticketid) { + if($this->_cachedTickets[$ticketid]) { + $ticket_focus = $this->_cachedTickets[$ticketid]; + // Check the parentid association if specified. + if($fromemail && !$this->LookupContactOrAccount($fromemail, $ticket_focus->column_fields[parent_id])) { + $ticket_focus = false; + } + if($ticket_focus) { + $this->log("Reusing Cached Ticket [" . $ticket_focus->column_fields[ticket_title] ."]"); + } + } else { + $ticket_focus = new HelpDesk(); + $ticket_focus->retrieve_entity_info($ticketid, 'HelpDesk'); + $ticket_focus->id = $ticketid; + // Check the parentid association if specified. + if($fromemail && !$this->LookupContactOrAccount($fromemail, $ticket_focus->column_fields[parent_id])) { + $ticket_focus = false; + } + if($ticket_focus) { + $this->log("Caching Ticket [" . $ticket_focus->column_fields[ticket_title] . "]"); + $this->_cachedTickets[$ticketid] = $ticket_focus; + } + } + } + return $ticket_focus; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerAction.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerAction.php new file mode 100644 index 00000000..d03f475c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerAction.php @@ -0,0 +1,359 @@ +debug) { $log->debug($message); } + else if($this->debug) echo "$message\n"; + } + + /** + * Constructor. + */ + function __construct($foractionid) { + $this->initialize($foractionid); + } + + /** + * Initialize this instance. + */ + function initialize($foractionid) { + global $adb; + $result = $adb->pquery("SELECT * FROM vtiger_mailscanner_actions WHERE actionid=? ORDER BY sequence", Array($foractionid)); + + if($adb->num_rows($result)) { + $this->actionid = $adb->query_result($result, 0, 'actionid'); + $this->scannerid = $adb->query_result($result, 0, 'scannerid'); + $this->actiontype = $adb->query_result($result, 0, 'actiontype'); + $this->module = $adb->query_result($result, 0, 'module'); + $this->lookup = $adb->query_result($result, 0, 'lookup'); + $this->actiontext = "$this->actiontype,$this->module,$this->lookup"; + } + } + + /** + * Create/Update the information of Action into database. + */ + function update($ruleid, $actiontext) { + global $adb; + + $inputparts = explode(',', $actiontext); + $this->actiontype = $inputparts[0]; // LINK, CREATE + $this->module = $inputparts[1]; // Module name + $this->lookup = $inputparts[2]; // FROM, TO + + $this->actiontext = $actiontext; + + if($this->actionid) { + $adb->pquery("UPDATE vtiger_mailscanner_actions SET scannerid=?, actiontype=?, module=?, lookup=? WHERE actionid=?", + Array($this->scannerid, $this->actiontype, $this->module, $this->lookup, $this->actionid)); + } else { + $this->sequence = $this->__nextsequence(); + $adb->pquery("INSERT INTO vtiger_mailscanner_actions(scannerid, actiontype, module, lookup, sequence) VALUES(?,?,?,?,?)", + Array($this->scannerid, $this->actiontype, $this->module, $this->lookup, $this->sequence)); + $this->actionid = $adb->database->Insert_ID(); + } + $checkmapping = $adb->pquery("SELECT COUNT(*) AS ruleaction_count FROM vtiger_mailscanner_ruleactions + WHERE ruleid=? AND actionid=?", Array($ruleid, $this->actionid)); + if($adb->num_rows($checkmapping) && !$adb->query_result($checkmapping, 0, 'ruleaction_count')) { + $adb->pquery("INSERT INTO vtiger_mailscanner_ruleactions(ruleid, actionid) VALUES(?,?)", + Array($ruleid, $this->actionid)); + } + } + + /** + * Delete the actions from tables. + */ + function delete() { + global $adb; + if($this->actionid) { + $adb->pquery("DELETE FROM vtiger_mailscanner_actions WHERE actionid=?", Array($this->actionid)); + $adb->pquery("DELETE FROM vtiger_mailscanner_ruleactions WHERE actionid=?", Array($this->actionid)); + } + } + + /** + * Get next sequence of Action to use. + */ + function __nextsequence() { + global $adb; + $seqres = $adb->pquery("SELECT max(sequence) AS max_sequence FROM vtiger_mailscanner_actions", Array()); + $maxsequence = 0; + if($adb->num_rows($seqres)) { + $maxsequence = $adb->query_result($seqres, 0, 'max_sequence'); + } + ++$maxsequence; + return $maxsequence; + } + + /** + * Apply the action on the mail record. + */ + function apply($mailscanner, $mailrecord, $mailscannerrule, $matchresult) { + $returnid = false; + if($this->actiontype == 'CREATE') { + if($this->module == 'HelpDesk') { + $returnid = $this->__CreateTicket($mailscanner, $mailrecord); + } + } else if($this->actiontype == 'LINK') { + $returnid = $this->__LinkToRecord($mailscanner, $mailrecord); + } else if($this->actiontype == 'UPDATE') { + if($this->module == 'HelpDesk') { + $returnid = $this->__UpdateTicket($mailscanner, $mailrecord, + $mailscannerrule->hasRegexMatch($matchresult)); + } + } + return $returnid; + } + + /** + * Update ticket action. + */ + function __UpdateTicket($mailscanner, $mailrecord, $regexMatchInfo) { + global $adb; + $returnid = false; + + $usesubject = false; + if($this->lookup == 'SUBJECT') { + // If regex match was performed on subject use the matched group + // to lookup the ticket record + if($regexMatchInfo) $usesubject = $regexMatchInfo['matches']; + else $usesubject = $mailrecord->_subject; + + // Get the ticket record that was created by SENDER earlier + $fromemail = $mailrecord->_from[0]; + + $linkfocus = $mailscanner->GetTicketRecord($usesubject, $fromemail); + $relatedid = $linkfocus->column_fields[parent_id]; + + // If matching ticket is found, update comment, attach email + if($linkfocus) { + $timestamp = $adb->formatDate(date('YmdHis'), true); + $adb->pquery("INSERT INTO vtiger_ticketcomments(ticketid, comments, ownerid, ownertype, createdtime) VALUES(?,?,?,?,?)", + Array($linkfocus->id, $mailrecord->getBodyText(), $relatedid, 'customer', $timestamp)); + // Set the ticket status to Open if its Closed + $adb->pquery("UPDATE vtiger_troubletickets set status=? WHERE ticketid=? AND status='Closed'", Array('Open', $linkfocus->id)); + + $returnid = $this->__CreateNewEmail($mailrecord, $this->module, $linkfocus); + + } else { + // TODO If matching ticket was not found, create ticket? + // $returnid = $this->__CreateTicket($mailscanner, $mailrecord); + } + } + return $returnid; + } + + /** + * Create ticket action. + */ + function __CreateTicket($mailscanner, $mailrecord) { + // Prepare data to create trouble ticket + $usetitle = $mailrecord->_subject; + $description = $mailrecord->getBodyText(); + + // There will be only on FROM address to email, so pick the first one + $fromemail = $mailrecord->_from[0]; + $linktoid = $mailscanner->LookupContact($fromemail); + if(!$linktoid) $linktoid = $mailscanner->LookupAccount($fromemail); + + /** Now Create Ticket **/ + global $current_user; + if(!$current_user) $current_user = new Users(); + $current_user->id = 1; + + // Create trouble ticket record + $ticket = new HelpDesk(); + $ticket->column_fields['ticket_title'] = $usetitle; + $ticket->column_fields['description'] = $description; + $ticket->column_fields['ticketstatus'] = 'Open'; + $ticket->column_fields['assigned_user_id'] = $current_user->id; + if($linktoid) $ticket->column_fields['parent_id'] = $linktoid; + $ticket->save('HelpDesk'); + + // Associate any attachement of the email to ticket + $this->__SaveAttachements($mailrecord, 'HelpDesk', $ticket); + + return $ticket->id; + } + + /** + * Add email to CRM record like Contacts/Accounts + */ + function __LinkToRecord($mailscanner, $mailrecord) { + $linkfocus = false; + + $useemail = false; + if($this->lookup == 'FROM') $useemail = $mailrecord->_from; + else if($this->lookup == 'TO') $useemail = $mailrecord->_to; + + if($this->module == 'Contacts') { + foreach($useemail as $email) { + $linkfocus = $mailscanner->GetContactRecord($email); + if($linkfocus) break; + } + } else if($this->module == 'Accounts') { + foreach($useemail as $email) { + $linkfocus = $mailscanner->GetAccountRecord($email); + if($linkfocus) break; + } + } + + $returnid = false; + if($linkfocus) { + $returnid = $this->__CreateNewEmail($mailrecord, $this->module, $linkfocus); + } + return $returnid; + } + + /** + * Create new Email record (and link to given record) including attachements + */ + function __CreateNewEmail($mailrecord, $module, $linkfocus) { + global $current_user, $adb; + if(!$current_user) $current_user = new Users(); + $current_user->id = 1; + + $focus = new Emails(); + $focus->column_fields['parent_type'] = $module; + $focus->column_fields['activitytype'] = 'Emails'; + $focus->column_fields['parent_id'] = "$linkfocus->id@-1|"; + $focus->column_fields['subject'] = $mailrecord->_subject; + + $focus->column_fields['description'] = $mailrecord->getBodyHTML(); + $focus->column_fields['assigned_user_id'] = $linkfocus->column_fields['assigned_user_id']; + $focus->column_fields["date_start"]= date('Y-m-d', $mailrecord->_date); + + $emailid = $focus->id; + $from=$mailrecord->_from[0]; + $to = $mailrecord->_to[0]; + $cc = (!empty($mailrecord->_cc))? implode(',', $mailrecord->_cc) : ''; + $bcc= (!empty($mailrecord->_bcc))? implode(',', $mailrecord->_bcc) : ''; + $flag=''; // 'SENT'/'SAVED' + //emails field were restructured and to,bcc and cc field are JSON arrays + $focus->column_fields['from_email'] = $from; + $focus->column_fields['saved_toid'] = $to; + $focus->column_fields['ccmail'] = $cc; + $focus->column_fields['bccmail'] = $bcc; + $focus->save('Emails'); + + $this->log("Created [$focus->id]: $mailrecord->_subject linked it to " . $linkfocus->id); + + // TODO: Handle attachments of the mail (inline/file) + $this->__SaveAttachements($mailrecord, 'Emails', $focus); + + return $emailid; + } + + /** + * Save attachments from the email and add it to the module record. + */ + function __SaveAttachements($mailrecord, $basemodule, $basefocus) { + global $adb; + + // If there is no attachments return + if(!$mailrecord->_attachments) return; + + $userid = $basefocus->column_fields['assigned_user_id']; + $setype = "$basemodule Attachment"; + + $date_var = $adb->formatDate(date('YmdHis'), true); + + foreach($mailrecord->_attachments as $filename=>$filecontent) { + $attachid = $adb->getUniqueId('vtiger_crmentity'); + $description = $filename; + $usetime = $adb->formatDate($date_var, true); + + $adb->pquery("INSERT INTO vtiger_crmentity(crmid, smcreatorid, smownerid, + modifiedby, setype, description, createdtime, modifiedtime, presence, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + Array($attachid, $userid, $userid, $userid, $setype, $description, $usetime, $usetime, 1, 0)); + + $issaved = $this->__SaveAttachmentFile($attachid, $filename, $filecontent); + if($issaved) { + // Create document record + $document = new Documents(); + $document->column_fields['notes_title'] = $filename; + $document->column_fields['filename'] = $filename; + $document->column_fields['filestatus'] = 1; + $document->column_fields['filelocationtype'] = 'I'; + $document->column_fields['folderid'] = 1; // Default Folder + $document->column_fields['assigned_user_id'] = $userid; + $document->save('Documents'); + + // Link file attached to document + $adb->pquery("INSERT INTO vtiger_seattachmentsrel(crmid, attachmentsid) VALUES(?,?)", + Array($document->id, $attachid)); + + // Link document to base record + $adb->pquery("INSERT INTO vtiger_senotesrel(crmid, notesid) VALUES(?,?)", + Array($basefocus->id, $document->id)); + } + } + } + + /** + * Save the attachment to the file + */ + function __SaveAttachmentFile($attachid, $filename, $filecontent) { + global $adb; + + $dirname = $this->STORAGE_FOLDER; + if(!is_dir($dirname)) mkdir($dirname); + + $description = $filename; + $filename = str_replace(' ', '-', $filename); + $saveasfile = "$dirname$attachid" . "_$filename"; + if(!file_exists($saveasfile)) { + + $this->log("Saved attachement as $saveasfile\n"); + + $fh = fopen($saveasfile, 'wb'); + fwrite($fh, $filecontent); + fclose($fh); + } + + $mimetype = MailAttachmentMIME::detect($saveasfile); + + $adb->pquery("INSERT INTO vtiger_attachments SET attachmentsid=?, name=?, description=?, type=?, path=?", + Array($attachid, $filename, $description, $mimetype, $dirname)); + + return true; + } +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerInfo.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerInfo.php new file mode 100644 index 00000000..df3a5a66 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerInfo.php @@ -0,0 +1,375 @@ +initialize($scannername); + } + + /** + * Encrypt/Decrypt input. + * @access private + */ + function __crypt($password, $encrypt=true) { + require_once('include/utils/encryption.php'); + $cryptobj = new Encryption(); + if($encrypt) return $cryptobj->encrypt(trim($password)); + else return $cryptobj->decrypt(trim($password)); + } + + /** + * Initialize this instance. + */ + function initialize($scannername) { + global $adb; + $result = $adb->pquery("SELECT * FROM vtiger_mailscanner WHERE scannername=?", Array($scannername)); + + if($adb->num_rows($result)) { + $this->scannerid = $adb->query_result($result, 0, 'scannerid'); + $this->scannername= $adb->query_result($result, 0, 'scannername'); + $this->server = $adb->query_result($result, 0, 'server'); + $this->protocol = $adb->query_result($result, 0, 'protocol'); + $this->username = $adb->query_result($result, 0, 'username'); + $this->password = $adb->query_result($result, 0, 'password'); + $this->password = $this->__crypt($this->password, false); + $this->ssltype = $adb->query_result($result, 0, 'ssltype'); + $this->sslmethod = $adb->query_result($result, 0, 'sslmethod'); + $this->connecturl = $adb->query_result($result, 0, 'connecturl'); + $this->searchfor = $adb->query_result($result, 0, 'searchfor'); + $this->markas = $adb->query_result($result, 0, 'markas'); + $this->isvalid = $adb->query_result($result, 0, 'isvalid'); + + $this->initializeFolderInfo(); + $this->initializeRules(); + } + } + + /** + * Initialize the folder details + */ + function initializeFolderInfo() { + global $adb; + if($this->scannerid) { + $this->lastscan = Array(); + $this->rescan = Array(); + $lastscanres = $adb->pquery("SELECT * FROM vtiger_mailscanner_folders WHERE scannerid=?",Array($this->scannerid)); + $lastscancount = $adb->num_rows($lastscanres); + if($lastscancount) { + for($lsindex = 0; $lsindex < $lastscancount; ++$lsindex) { + $folder = $adb->query_result($lastscanres, $lsindex, 'foldername'); + $scannedon =$adb->query_result($lastscanres, $lsindex, 'lastscan'); + $nextrescan =$adb->query_result($lastscanres, $lsindex, 'rescan'); + $this->lastscan[$folder] = $scannedon; + $this->rescan[$folder] = ($nextrescan == 0)? false : true; + } + } + } + } + + /** + * Delete lastscan details with this scanner + */ + function clearLastscan() { + global $adb; + $adb->pquery("DELETE FROM vtiger_mailscanner_folders WHERE scannerid=?", Array($this->scannerid)); + $this->lastscan = false; + } + + /** + * Update rescan flag on all folders + */ + function updateAllFolderRescan($rescanFlag=false) { + global $adb; + $useRescanFlag = $rescanFlag? 1 : 0; + $adb->pquery("UPDATE vtiger_mailscanner_folders set rescan=? WHERE scannerid=?", + Array($rescanFlag, $this->scannerid)); + if($this->rescan) { + foreach($this->rescan as $folderName=>$oldRescanFlag) { + $this->rescan[$folderName] = $rescanFlag; + } + } + } + + /** + * Update lastscan information on folder (or set for rescan next) + */ + function updateLastscan($folderName, $rescanFolder=false) { + global $adb; + + $scannedOn = date('d-M-Y'); + + $needRescan = $rescanFolder? 1 : 0; + + $folderInfo = $adb->pquery("SELECT folderid FROM vtiger_mailscanner_folders WHERE scannerid=? AND foldername=?", + Array($this->scannerid, $folderName)); + if($adb->num_rows($folderInfo)) { + $folderid = $adb->query_result($folderInfo, 0, 'folderid'); + $adb->pquery("UPDATE vtiger_mailscanner_folders SET lastscan=?, rescan=? WHERE folderid=?", + Array($scannedOn, $needRescan, $folderid)); + } else { + $enabledForScan = 1; // Enable folder for scan by default + $adb->pquery("INSERT INTO vtiger_mailscanner_folders(scannerid, foldername, lastscan, rescan, enabled) + VALUES(?,?,?,?,?)", Array($this->scannerid, $folderName, $scannedOn, $needRescan, $enabledForScan)); + } + if(!$this->lastscan) $this->lastscan = Array(); + $this->lastscan[$folderName] = $scannedOn; + + if(!$this->rescan) $this->rescan = Array(); + $this->rescan[$folderName] = $needRescan; + } + + /** + * Get lastscan of the folder. + */ + function getLastscan($folderName) { + if($this->lastscan) return $this->lastscan[$folderName]; + else return false; + } + + /** + * Does the folder need message rescan? + */ + function needRescan($folderName) { + if($this->rescan && isset($this->rescan[$folderName])) { + return $this->rescan[$folderName]; + } + // TODO Pick details of rescan flag of folder from database? + return false; + } + + /** + * Check if rescan is required atleast on a folder? + */ + function checkRescan() { + $rescanRequired = false; + if($this->rescan) { + foreach($this->rescan as $folderName=>$rescan) { + if($rescan) { + $rescanRequired = $folderName; + break; + } + } + } + return $rescanRequired; + } + + /** + * Get the folder information that has been scanned + */ + function getFolderInfo() { + $folderinfo = false; + if($this->scannerid) { + global $adb; + $fldres = $adb->pquery("SELECT * FROM vtiger_mailscanner_folders WHERE scannerid=?", Array($this->scannerid)); + $fldcount = $adb->num_rows($fldres); + if($fldcount) { + $folderinfo = Array(); + for($index = 0; $index < $fldcount; ++$index) { + $foldername = $adb->query_result($fldres, $index, 'foldername'); + $folderid = $adb->query_result($fldres, $index, 'folderid'); + $lastscan = $adb->query_result($fldres, $index, 'lastscan'); + $rescan = $adb->query_result($fldres, $index, 'rescan'); + $enabled = $adb->query_result($fldres, $index, 'enabled'); + $folderinfo[$foldername] = Array ('folderid'=>$folderid, 'lastscan'=>$lastscan, 'rescan'=> $rescan, 'enabled'=>$enabled); + } + } + } + return $folderinfo; + } + + /** + * Update the folder information with given folder names + */ + function updateFolderInfo($foldernames, $rescanFolder=false) { + if($this->scannerid && !empty($foldernames)) { + global $adb; + $qmarks = Array(); + foreach($foldernames as $foldername) { + $qmarks[] = '?'; + $this->updateLastscan($foldername, $rescanFolder); + } + // Delete the folder that is no longer present + $adb->pquery("DELETE FROM vtiger_mailscanner_folders WHERE scannerid=? AND foldername NOT IN + (". implode(',', $qmarks) . ")", Array($this->scannerid, $foldernames)); + } + } + + /** + * Enable only given folders for scanning + */ + function enableFoldersForScan($folderinfo) { + if($this->scannerid) { + global $adb; + $adb->pquery("UPDATE vtiger_mailscanner_folders set enabled=0 WHERE scannerid=?", Array($this->scannerid)); + foreach($folderinfo as $foldername=>$foldervalue) { + $folderid = $foldervalue[folderid]; + $enabled = $foldervalue[enabled]; + $adb->pquery("UPDATE vtiger_mailscanner_folders set enabled=? WHERE folderid=? AND scannerid=?", + Array($enabled,$folderid,$this->scannerid)); + } + } + } + + /** + * Initialize scanner rule information + */ + function initializeRules() { + global $adb; + if($this->scannerid) { + $this->rules = Array(); + $rulesres = $adb->pquery("SELECT * FROM vtiger_mailscanner_rules WHERE scannerid=? ORDER BY sequence",Array($this->scannerid)); + $rulescount = $adb->num_rows($rulesres); + if($rulescount) { + for($index = 0; $index < $rulescount; ++$index) { + $ruleid = $adb->query_result($rulesres, $index, 'ruleid'); + $scannerrule = new Vtiger_MailScannerRule($ruleid); + $scannerrule->debug = $this->debug; + $this->rules[] = $scannerrule; + } + } + } + } + + /** + * Get scanner information as map + */ + function getAsMap() { + $infomap = Array(); + $keys = Array('scannerid', 'scannername', 'server', 'protocol', 'username', 'password', 'ssltype', + 'sslmethod', 'connecturl', 'searchfor', 'markas', 'isvalid', 'rules'); + foreach($keys as $key) { + $infomap[$key] = $this->$key; + } + $infomap['requireRescan'] = $this->checkRescan(); + return $infomap; + } + + /** + * Compare this instance with give instance + */ + function compare($otherInstance) { + $checkkeys = Array('server', 'scannername', 'protocol', 'username', 'password', 'ssltype', 'sslmethod', 'searchfor', 'markas',); + foreach($checkkeys as $key) { + if($this->$key != $otherInstance->$key) return false; + } + return true; + } + + /** + * Create/Update the scanner information in database + */ + function update($otherInstance) { + $mailServerChanged = false; + + // Is there is change in server setup? + if($this->server != $otherInstance->server || $this->username != $otherInstance->username) { + $mailServerChanged = true; + $this->clearLastscan(); + // TODO How to handle lastscan info if server settings switches back in future? + } + + $this->server = $otherInstance->server; + $this->scannername= $otherInstance->scannername; + $this->protocol = $otherInstance->protocol; + $this->username = $otherInstance->username; + $this->password = $otherInstance->password; + $this->ssltype = $otherInstance->ssltype; + $this->sslmethod = $otherInstance->sslmethod; + $this->connecturl= $otherInstance->connecturl; + $this->searchfor = $otherInstance->searchfor; + $this->markas = $otherInstance->markas; + $this->isvalid = $otherInstance->isvalid; + + $useisvalid = ($this->isvalid)? 1 : 0; + + $usepassword = $this->__crypt($this->password); + + global $adb; + if($this->scannerid) { // This record exists in the database + $adb->pquery("UPDATE vtiger_mailscanner SET scannername=?,server=?,protocol=?,username=?,password=?,ssltype=?, + sslmethod=?,connecturl=?,searchfor=?,markas=?,isvalid=? WHERE scannerid=?", + Array($this->scannername,$this->server,$this->protocol, $this->username, $usepassword, $this->ssltype, + $this->sslmethod, $this->connecturl,$this->searchfor, $this->markas,$useisvalid, $this->scannerid)); + } else { + $adb->pquery("INSERT INTO vtiger_mailscanner(scannername,server,protocol,username,password,ssltype, + sslmethod,connecturl,searchfor,markas,isvalid) VALUES(?,?,?,?,?,?,?,?,?,?,?)", + Array($this->scannername,$this->server, $this->protocol, $this->username, $usepassword, + $this->ssltype, $this->sslmethod, $this->connecturl, $this->searchfor, $this->markas, $useisvalid)); + $this->scannerid = $adb->database->Insert_ID(); + } + + return $mailServerChanged; + } + + /** + * Delete the scanner information from database + */ + function delete() { + global $adb; + if($this->scannerid) { + $tables = Array( + 'vtiger_mailscanner', + 'vtiger_mailscanner_ids', + 'vtiger_mailscanner_folders', + 'vtiger_mailscanner_rules'); + foreach($tables as $table) { + $adb->pquery("DELETE FROM $table WHERE scannerid=?", + Array($this->scannerid)); + } + $adb->pquery("DELETE FROM vtiger_mailscanner_ruleactions + WHERE actionid in (SELECT actionid FROM vtiger_mailscanner_actions WHERE scannerid=?)", Array($this->scannerid)); + $adb->pquery("DELETE FROM vtiger_mailscanner_actions WHERE scannerid=?", Array($this->scannerid)); + } + } +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerRule.php b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerRule.php new file mode 100644 index 00000000..3f3d5b8e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/MailScanner/core/MailScannerRule.php @@ -0,0 +1,396 @@ +debug) { $log->debug($message); } + else if($this->debug) echo "$message\n"; + } + + /** + * Constructor + */ + function __construct($forruleid) { + $this->initialize($forruleid); + } + + /** + * String representation of this instance + */ + function __toString() { + $tostring = ''; + $tostring .= "FROM $this->fromaddress, TO $this->toaddress"; + $tostring .= ",SUBJECT $this->subjectop $this->subject, BODY $this->bodyop $this->body, MATCH USING, $this->matchusing"; + return $tostring; + } + + /** + * Initialize this instance + */ + function initialize($forruleid) { + global $adb; + $result = $adb->pquery("SELECT * FROM vtiger_mailscanner_rules WHERE ruleid=? ORDER BY sequence", Array($forruleid)); + + if($adb->num_rows($result)) { + $this->ruleid = $adb->query_result($result, 0, 'ruleid'); + $this->scannerid = $adb->query_result($result, 0, 'scannerid'); + $this->fromaddress= $adb->query_result($result, 0, 'fromaddress'); + $this->toaddress = $adb->query_result($result, 0, 'toaddress'); + $this->subjectop = $adb->query_result($result, 0, 'subjectop'); + $this->subject = $adb->query_result($result, 0, 'subject'); + $this->bodyop = $adb->query_result($result, 0, 'bodyop'); + $this->body = $adb->query_result($result, 0, 'body'); + $this->sequence = $adb->query_result($result, 0, 'sequence'); + $this->matchusing = $adb->query_result($result, 0, 'matchusing'); + $this->isvalid = true; + $this->initializeActions(); + // At present we support only one action for a rule + if(!empty($this->actions)) $this->useaction = $this->actions[0]; + } + } + + /** + * Initialize the actions + */ + function initializeActions() { + global $adb; + if($this->ruleid) { + $this->actions = Array(); + $actionres = $adb->pquery("SELECT actionid FROM vtiger_mailscanner_ruleactions WHERE ruleid=?",Array($this->ruleid)); + $actioncount = $adb->num_rows($actionres); + if($actioncount) { + for($index = 0; $index < $actioncount; ++$index) { + $actionid = $adb->query_result($actionres, $index, 'actionid'); + $ruleaction = new Vtiger_MailScannerAction($actionid); + $ruleaction->debug = $this->debug; + $this->actions[] = $ruleaction; + } + } + } + } + + /** + * Is body rule defined? + */ + function hasBodyRule() { + return (!empty($this->bodyop)); + } + + /** + * Check if the rule criteria is matching + */ + function isMatching($matchfound1, $matchfound2=null) { + if($matchfound2 === null) return $matchfound1; + + if($this->matchusing== 'AND') return ($matchfound1 && $matchfound2); + if($this->matchusing== 'OR') return ($matchfound1 || $matchfound2); + return false; + } + + /** + * Apply all the criteria. + * @param $mailrecord + * @param $includingBody + * @returns false if not match is found or else all matching result found + */ + function applyAll($mailrecord, $includingBody=true) { + $matchresults = Array(); + $matchfound = null; + + if($this->hasACondition()) { + $subrules = Array('FROM', 'TO', 'SUBJECT', 'BODY'); + + foreach($subrules as $subrule) { + // Body rule could be defered later to improve performance + // in that case skip it. + if($subrule == 'BODY' && !$includingBody) continue; + + $checkmatch = $this->apply($subrule, $mailrecord); + $matchfound = $this->isMatching($checkmatch, $matchfound); + // Collect matching result array + if($matchfound && is_array($checkmatch)) $matchresults[] = $checkmatch; + if($matchfound && $this->matchusing == 'OR') break; + } + } else { + $matchfound = false; + if($this->matchusing == 'OR') { + $matchfound = true; + $matchresults[] = $this->__CreateMatchResult('BLANK','','',''); + } + } + return ($matchfound)? $matchresults : false; + } + + /** + * Check if at least one condition is set for this rule. + */ + function hasACondition() { + $hasFromAddress = $this->fromaddress? true: false; + $hasToAddress = $this->toaddress? true : false; + $hasSubjectOp = $this->subjectop? true : false; + $hasBodyOp = $this->bodyop? true : false; + return ($hasFromAddress || $hasToAddress || $hasSubjectOp || $hasBodyOp); + } + + /** + * Apply required condition on the mail record. + */ + function apply($subrule, $mailrecord) { + $matchfound = false; + if($this->isvalid) { + switch(strtoupper($subrule)) { + case 'FROM': + if($this->fromaddress) { + $matchfound = $this->find($subrule, 'Contains', $mailrecord->_from[0], $this->fromaddress); + } else { + $matchfound = $this->__CreateDefaultMatchResult($subrule); + } + break; + case 'TO': + if($this->toaddress) { + foreach($mailrecord->_to as $toemail) { + $matchfound = $this->find($subrule, 'Contains', $toemail, $this->toaddress); + if($matchfound) break; + } + } else { + $matchfound = $this->__CreateDefaultMatchResult($subrule); + } + break; + case 'SUBJECT': + if($this->subjectop) { + $matchfound = $this->find($subrule, $this->subjectop, $mailrecord->_subject, $this->subject); + } else { + $matchfound = $this->__CreateDefaultMatchResult($subrule); + } + break; + case 'BODY': + if($this->bodyop) { + $matchfound = $this->find($subrule, $this->bodyop, $mailrecord->_body, $this->body); + } else { + $matchfound = $this->__CreateDefaultMatchResult($subrule); + } + break; + } + } + return $matchfound; + } + + /** + * Find if the rule matches based on condition and parameters + */ + function find($subrule, $condition, $input, $searchfor) { + if(!$input) return false; + + $matchfound = false; + $matches = false; + + switch($condition) { + case 'Contains': + $matchfound = stripos($input, $searchfor); + $matchfound = ($matchfound !== FALSE); + $matches = $searchfor; + break; + case 'Not Contains': + $matchfound = stripos($input, $searchfor); + $matchfound = ($matchfound === FALSE); + $matches = $searchfor; + break; + case 'Equals': + $matchfound = strcasecmp($input, $searchfor); + $matchfound = ($matchfound === 0); + $matches = $searchfor; + break; + case 'Not Equals': + $matchfound = strcasecmp($input, $searchfor); + $matchfound = ($matchfound !== 0); + $matches = $searchfor; + break; + case 'Begins With': + $matchfound = stripos($input, $searchfor); + $matchfound = ($matchfound === 0); + $matches = $searchfor; + break; + case 'Ends With': + $matchfound = strripos($input, $searchfor); + $matchfound = ($matchfound === strlen($input)-strlen($searchfor)); + $matches = $searchfor; + break; + case 'Regex': + $regmatches = Array(); + $matchfound = false; + $searchfor = str_replace('/', '\/', $searchfor); + if(preg_match("/$searchfor/i", $input, $regmatches)) { + // Pick the last matching group + $matches = $regmatches[count($regmatches)-1]; + $matchfound = true; + } + break; + } + if($matchfound) $matchfound = $this->__CreateMatchResult($subrule, $condition, $searchfor, $matches); + return $matchfound; + } + + /** + * Create matching result for the subrule. + */ + function __CreateMatchResult($subrule, $condition, $searchfor, $matches) { + return Array( 'subrule' => $subrule, 'condition' => $condition, 'searchfor' => $searchfor, 'matches' => $matches); + } + + /** + * Create default success matching result + */ + function __CreateDefaultMatchResult($subrule) { + if($this->matchusing == 'OR') return false; + if($this->matchusing == 'AND') return $this->__CreateMatchResult($subrule, 'Contains', '', ''); + } + + /** + * Detect if the rule match result has Regex condition + * @param $matchresult result of apply obtained earlier + * @returns matchinfo if Regex match is found, false otherwise + */ + function hasRegexMatch($matchresult) { + foreach($matchresult as $matchinfo) { + $match_condition = $matchinfo['condition']; + $match_string = $matchinfo['matches']; + if($match_condition == 'Regex' && $match_string) + return $matchinfo; + } + return false; + } + + /** + * Swap (reset) sequence of two rules. + */ + static function resetSequence($ruleid1, $ruleid2) { + global $adb; + $ruleresult = $adb->pquery("SELECT ruleid, sequence FROM vtiger_mailscanner_rules WHERE ruleid = ? or ruleid = ?", + Array($ruleid1, $ruleid2)); + $rule_partinfo = Array(); + if($adb->num_rows($ruleresult) != 2) { + return false; + } else { + $rule_partinfo[$adb->query_result($ruleresult, 0, 'ruleid')] = $adb->query_result($ruleresult, 0, 'sequence'); + $rule_partinfo[$adb->query_result($ruleresult, 1, 'ruleid')] = $adb->query_result($ruleresult, 1, 'sequence'); + $adb->pquery("UPDATE vtiger_mailscanner_rules SET sequence = ? WHERE ruleid = ?", Array($rule_partinfo[$ruleid2], $ruleid1)); + $adb->pquery("UPDATE vtiger_mailscanner_rules SET sequence = ? WHERE ruleid = ?", Array($rule_partinfo[$ruleid1], $ruleid2)); + } + } + + /** + * Update rule information in database. + */ + function update() { + global $adb; + if($this->ruleid) { + $adb->pquery("UPDATE vtiger_mailscanner_rules SET scannerid=?,fromaddress=?,toaddress=?,subjectop=?,subject=?,bodyop=?,body=?,matchusing=? + WHERE ruleid=?", Array($this->scannerid, $this->fromaddress, $this->toaddress, $this->subjectop, $this->subject, + $this->bodyop, $this->body,$this->matchusing, $this->ruleid)); + } else { + $this->sequence = $this->__nextsequence(); + $adb->pquery("INSERT INTO vtiger_mailscanner_rules(scannerid,fromaddress,toaddress,subjectop,subject,bodyop,body,matchusing,sequence) + VALUES(?,?,?,?,?,?,?,?,?)", + Array($this->scannerid,$this->fromaddress,$this->toaddress,$this->subjectop,$this->subject, + $this->bodyop,$this->body,$this->matchusing,$this->sequence)); + $this->ruleid = $adb->database->Insert_ID(); + } + } + + /** + * Get next sequence to use + */ + function __nextsequence() { + global $adb; + $seqres = $adb->pquery("SELECT max(sequence) AS max_sequence FROM vtiger_mailscanner_rules", Array()); + $maxsequence = 0; + if($adb->num_rows($seqres)) { + $maxsequence = $adb->query_result($seqres, 0, 'max_sequence'); + } + ++$maxsequence; + return $maxsequence; + } + + /** + * Delete the rule and associated information. + */ + function delete() { + global $adb; + if($this->ruleid) { + $adb->pquery("DELETE FROM vtiger_mailscanner_ruleactions WHERE ruleid = ?", Array($this->ruleid)); + $adb->pquery("DELETE FROM vtiger_mailscanner_rules WHERE ruleid=?", Array($this->ruleid)); + } + } + + /** + * Update action linked to the rule. + */ + function updateAction($actionid, $actiontext) { + $action = $this->useaction; + + if($actionid != '' && $actiontext == '') { + if($action) $action->delete(); + } else { + if($actionid == '') { + $action = new Vtiger_MailScannerAction($actionid); + } + $action->scannerid = $this->scannerid; + $action->update($this->ruleid, $actiontext); + } + } + + /** + * Take action on mail record + */ + function takeAction($mailscanner, $mailrecord, $matchresult) { + if(empty($this->actions)) return false; + + $action = $this->useaction; // Action is limited to One right now + return $action->apply($mailscanner, $mailrecord, $this, $matchresult); + } +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/ModifyPickList.php b/oss/vtiger/trunk/modules/Settings/ModifyPickList.php new file mode 100644 index 00000000..36673c52 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ModifyPickList.php @@ -0,0 +1,242 @@ +assign("IMAGE_PATH",$image_path); + + $fieldName=vtlib_purify($_REQUEST["fieldname"]); + $fieldLabel =vtlib_purify($_REQUEST["fieldlabel"]); + $moduleName=vtlib_purify($_REQUEST["fld_module"]); + $uitype=vtlib_purify($_REQUEST["uitype"]); + $mode=vtlib_purify($_REQUEST["mode"]); + + if($moduleName == 'Events') + $temp_module_strings = return_module_language($current_language, 'Calendar'); + else + $temp_module_strings = return_module_language($current_language, $moduleName); + + $sql = "select picklistid from vtiger_picklist where name=?"; + $result = $adb->pquery($sql, array($fieldName)); + $picklistid = $adb->query_result($result,0,"picklistid"); + + if($mode == 'addnew') + { + $newValues = $_REQUEST['newValues']; + $selectedRoles = $_REQUEST['selectedRoles']; + + $newPicklist = explode(",",$newValues); + $roleIds = explode(":",$selectedRoles); + + $tableName = $adb->sql_escape_string($fieldName); + foreach($newPicklist as $key => $val) + { + $val = urldecode($val); + $picklistvalue_id = getUniquePicklistID(); + $picklist_id = $adb->getUniqueID("vtiger_".$tableName); + + $query = "insert into vtiger_".$tableName." values(?,?,?,?)"; + $params = array($picklist_id, $val, 1, $picklistvalue_id); + $adb->pquery($query, $params); + + $num_roles = count($roleIds); + for($i=0;$i<$num_roles;$i++) { + $roleid = $roleIds[$i]; + + $sql ="select max(sortid)+1 as sortid from vtiger_role2picklist left join vtiger_$tableName on vtiger_$tableName.picklist_valueid=vtiger_role2picklist.picklistvalueid where roleid=? and picklistid=?"; + $sortid = $adb->query_result($adb->pquery($sql, array($roleid, $picklistid)),0,'sortid'); + if ($sortid == '') { + $sortid = 0; + } + + $sql = "insert into vtiger_role2picklist values(?,?,?,?)"; + $adb->pquery($sql, array($roleid, $picklistvalue_id, $picklistid, $sortid)); + } + } + echo ":#:SUCCESS"; + exit; + } + if($mode == 'replace') + { + $mode_type = $_REQUEST['mode_type']; + $replaceWith = addslashes($_REQUEST['replaceFields']); + if($replaceWith == '--None--') + { + $replaceWith=''; + } + $selectedFields = $_REQUEST['selectedFields']; + $unwantedPicklist = explode(',',$selectedFields); + + $selectedRoles = $_REQUEST['selectedRoles']; + $roleIds = explode(":",$selectedRoles); + + foreach($unwantedPicklist as $key => $val) + { + $qry="select tablename,columnname,uitype from vtiger_field where fieldname=?"; + $result = $adb->pquery($qry, array($fieldName)); + $num = $adb->num_rows($result); + $val = urldecode($val); + if($num > 0) + { + for($n=0;$n<$num;$n++) + { + $table_name = $adb->query_result($result,$n,'tablename'); + $column_name = $adb->query_result($result,$n,'columnname'); + if ($mode_type == 'delete') { + $update_picklist = "update $table_name set $column_name=? where $column_name=?"; + $adb->pquery($update_picklist, array($replaceWith, $val)); + + $dele_pick_val =" delete from vtiger_role2picklist where picklistvalueid in (select picklist_valueid from vtiger_$fieldName where $fieldName=?)"; + $adb->pquery($dele_pick_val, array($val)); + + $del_qry = "delete from vtiger_$fieldName where $fieldName=?"; + $adb->pquery($del_qry, array($val)); + } + if($mode_type == 'edit') { + $sel_qry = "select $fieldName from vtiger_$fieldName where $fieldName = ?"; + $cnt_res = $adb->pquery($sel_qry, array($replaceWith)); + if ($adb->num_rows($cnt_res) <= 0) { // Avoid inserting duplicate entries for the new picklist value + $picklistvalue_id = getUniquePicklistID(); + $picklist_id = $adb->getUniqueID("vtiger_$fieldName"); + $query = "insert into vtiger_$fieldName values(?,?,?,?)"; + $params = array($picklist_id, $replaceWith, 1, $picklistvalue_id); + $adb->pquery($query, $params); + + $old_query = "select * from vtiger_$fieldName where $fieldName=?"; + $old_res = $adb->pquery($old_query, array($val)); + $old_picklistvalue_id = $adb->query_result($old_res, 0, 'picklist_valueid'); + + $num_roles = count($roleIds); + for($i=0;$i<$num_roles;$i++) { + $roleid = $roleIds[$i]; + + $upd_qry = "update vtiger_role2picklist set picklistvalueid=? where picklistvalueid=? and picklistid=? and roleid=?"; + $adb->pquery($upd_qry, array($picklistvalue_id, $old_picklistvalue_id, $picklistid, $roleid)); + } + } + } + } + } + } + echo ":#:SUCCESS"; + exit; + + } + if(isset($fieldName)) + { + $fieldName = $adb->sql_escape_string($fieldName); + $sql="select $fieldName from vtiger_$fieldName where presence=1 and $fieldName <> '--None--'"; + $res = $adb->query($sql); + $RowCount = $adb->num_rows($res); + if($RowCount > 0) + { + for($i=0;$i<$RowCount;$i++) + { + $pick_val = $adb->query_result($res,$i,$fieldName); + if($temp_module_strings[$pick_val] != '') + { + $pick[]=$temp_module_strings[$pick_val]; + }else + { + $pick[]=$pick_val; + } + } + } + + $nonEdit ="select $fieldName from vtiger_$fieldName where presence=0"; + $res_ult = $adb->query($nonEdit); + $non_editNum = $adb->num_rows($res_ult); + if($non_editNum > 0) + { + for($l=0;$l<$non_editNum;$l++) + { + $non_val = $adb->query_result($res_ult,$l,$fieldName); + if($temp_module_strings[$non_val] != '') + { + $non_pick[]=$temp_module_strings[$non_val]; + } + else + { + $non_pick[]=$non_val; + } + } + } + if(is_array($non_pick)) + $smarty->assign('NONEDIT_FLAG','true'); + else + $smarty->assign('NONEDIT_FLAG','false'); + + + $smarty->assign('NONEDITPICKLIST',$non_pick); + + + if($mode == "transfer") + { + $option=''; + $selectedFields = $_REQUEST['selectedFields']; + $pick_arr = explode(",",$_REQUEST['selectedFields']); + foreach($pick_arr as $v) + { + $v = urldecode($v); + $pick_arr2[] = "'".addslashes($v)."'"; + } + $pick_str = implode(",",$pick_arr2); + $sql="select $fieldName from vtiger_$fieldName where $fieldName not in ($pick_str)"; + $res=$adb->query($sql); + $num_Rows = $adb->num_rows($res); + if($num_Rows > 0) + { + for($j=0;$j<$num_Rows;$j++) + { + $avail_entries = $adb->query_result($res,$j,$fieldName); + if($temp_module_strings[$avail_entries] != '') + { + $option .= ""; + }else + $option .= ""; + } + } + + + + $output=" + + + + +
    ".$mod_strings['LBL_PICKLIST_TRANSFER']."\"".$fieldLabel."\"
    ".$mod_strings['LBL_REPLACE_VALUE_WITH'].":
     
    "; + + $smarty->assign("OUTPUT",$output); + } + + $temp_label = getTranslatedString($fieldLabel); + $roleDetails=getAllRoleDetails(); + // Remove Organization from the list of roles (which is the first one in the list of roles) + array_shift($roleDetails); + $smarty->assign("FIELDNAME",$fieldName); + $smarty->assign("FIELDLABEL",$temp_label); + $smarty->assign("MODE",$mode); + $smarty->assign("MODULE",$moduleName); + $smarty->assign("PICKVAL",$pick); + $smarty->assign("ROLEDETAILS",$roleDetails); + $smarty->assign("MOD", return_module_language($current_language,'Settings')); + $smarty->assign("APP",$app_strings); + $smarty->display("Settings/ModifyPickList.tpl"); + } + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ModuleManager.php b/oss/vtiger/trunk/modules/Settings/ModuleManager.php new file mode 100644 index 00000000..62e885ae --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ModuleManager.php @@ -0,0 +1,81 @@ +assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", "themes/$theme/images/"); + + $module_disable = $_REQUEST['module_disable']; + $module_name = $_REQUEST['module_name']; + $module_enable = $_REQUEST['module_enable']; + $module_type = $_REQUEST['module_type']; + + if($module_name != '') { + if($module_type == 'language') { + if($module_enable == 'true') vtlib_toggleLanguageAccess($module_name, true); + if($module_disable== 'true') vtlib_toggleLanguageAccess($module_name, false); + } else { + if($module_enable == 'true') vtlib_toggleModuleAccess($module_name, true); + if($module_disable== 'true') vtlib_toggleModuleAccess($module_name, false); + } + } + + // Check write permissions on the required directories + $dir_notwritable = Array(); + if(!vtlib_isDirWriteable('test/vtlib')) $dir_notwritable[] = 'test/vtlib'; + if(!vtlib_isDirWriteable('cron/modules')) $dir_notwritable[] = 'cron/modules'; + if(!vtlib_isDirWriteable('modules')) $dir_notwritable[] = 'modules'; + if(!vtlib_isDirWriteable('Smarty/templates/modules')) $dir_notwritable[] = 'Smarty/templates/modules'; + + $smarty->assign("DIR_NOTWRITABLE_LIST", $dir_notwritable); + // END + + $smarty->assign("TOGGLE_MODINFO", vtlib_getToggleModuleInfo()); + $smarty->assign("TOGGLE_LANGINFO", vtlib_getToggleLanguageInfo()); + + if($_REQUEST['mode'] !='') $mode = $_REQUEST['mode']; + $smarty->assign("MODE", vtlib_purify($mode)); + + if($_REQUEST['ajax'] != 'true') $smarty->display('Settings/ModuleManager/ModuleManager.tpl'); + else $smarty->display('Settings/ModuleManager/ModuleManagerAjax.tpl'); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ModuleManager/Export.php b/oss/vtiger/trunk/modules/Settings/ModuleManager/Export.php new file mode 100644 index 00000000..e634390f --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ModuleManager/Export.php @@ -0,0 +1,19 @@ +export(Vtiger_Module::getInstance($module_export),'',"$module_export.zip",true); +exit; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ModuleManager/Import.php b/oss/vtiger/trunk/modules/Settings/ModuleManager/Import.php new file mode 100644 index 00000000..a77cfb47 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ModuleManager/Import.php @@ -0,0 +1,89 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", "themes/$theme/images/"); + +global $modulemanager_uploaddir; // Defined in modules/Settings/ModuleManager.php + +if($module_import_step == 'Step2') { + if(!is_dir($modulemanager_uploaddir)) mkdir($modulemanager_uploaddir); + $uploadfile = "usermodule_". time() . ".zip"; + $uploadfilename = "$modulemanager_uploaddir/$uploadfile"; + checkFileAccess($modulemanager_uploaddir); + + if(!move_uploaded_file($_FILES['module_zipfile']['tmp_name'], $uploadfilename)) { + $smarty->assign("MODULEIMPORT_FAILED", "true"); + } else { + $package = new Vtiger_Package(); + $moduleimport_name = $package->getModuleNameFromZip($uploadfilename); + + if($moduleimport_name == null) { + $smarty->assign("MODULEIMPORT_FAILED", "true"); + $smarty->assign("MODULEIMPORT_FILE_INVALID", "true"); + } else { + + if(!$package->isLanguageType()) { + $moduleInstance = Vtiger_Module::getInstance($moduleimport_name); + $moduleimport_exists=($moduleInstance)? "true" : "false"; + $moduleimport_dir_name="modules/$moduleimport_name"; + $moduleimport_dir_exists= (is_dir($moduleimport_dir_name)? "true" : "false"); + + $smarty->assign("MODULEIMPORT_EXISTS", $moduleimport_exists); + $smarty->assign("MODULEIMPORT_DIR", $moduleimport_dir_name); + $smarty->assign("MODULEIMPORT_DIR_EXISTS", $moduleimport_dir_exists); + } + + $moduleimport_dep_vtversion = $package->getDependentVtigerVersion(); + $moduleimport_license = $package->getLicense(); + + $smarty->assign("MODULEIMPORT_FILE", $uploadfile); + $smarty->assign("MODULEIMPORT_TYPE", $package->type()); + $smarty->assign("MODULEIMPORT_NAME", $moduleimport_name); + $smarty->assign("MODULEIMPORT_DEP_VTVERSION", $moduleimport_dep_vtversion); + $smarty->assign("MODULEIMPORT_LICENSE", $moduleimport_license); + } + } +} else if($module_import_step == 'Step3') { + $uploadfile = $_REQUEST['module_import_file']; + $uploadfilename = "$modulemanager_uploaddir/$uploadfile"; + checkFileAccess($uploadfilename); + + //$overwritedir = ($_REQUEST['module_dir_overwrite'] == 'true')? true : false; + $overwritedir = false; // Disallowing overwrites through Module Manager UI + + $importtype = $_REQUEST['module_import_type']; + if(strtolower($importtype) == 'language') { + $package = new Vtiger_Language(); + } else { + $package = new Vtiger_Package(); + } + $Vtiger_Utils_Log = true; + // NOTE: Import function will be called from Smarty to capture the log cleanly. + //$package->import($uploadfilename, $overwritedir); + //unlink($uploadfilename); + $smarty->assign("MODULEIMPORT_PACKAGE", $package); + $smarty->assign("MODULEIMPORT_DIR_OVERWRITE", $overwritedir); + $smarty->assign("MODULEIMPORT_PACKAGE_FILE", $uploadfilename); +} + +$smarty->display("Settings/ModuleManager/ModuleImport$module_import_step.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ModuleManager/Update.php b/oss/vtiger/trunk/modules/Settings/ModuleManager/Update.php new file mode 100644 index 00000000..5a278830 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ModuleManager/Update.php @@ -0,0 +1,106 @@ +assign("MOD",$mod_strings); +$smarty->assign("APP",$app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", "themes/$theme/images/"); + +global $modulemanager_uploaddir; // Defined in modules/Settings/ModuleManager.php + +$target_modulename = $_REQUEST['target_modulename']; + +if($module_update_step == 'Step2') { + if(!is_dir($modulemanager_uploaddir)) mkdir($modulemanager_uploaddir); + $uploadfile = "usermodule_". time() . ".zip"; + $uploadfilename = "$modulemanager_uploaddir/$uploadfile"; + checkFileAccess($modulemanager_uploaddir); + + if(!move_uploaded_file($_FILES['module_zipfile']['tmp_name'], $uploadfilename)) { + $smarty->assign("MODULEUPDATE_FAILED", "true"); + } else { + $package = new Vtiger_Package(); + $moduleupdate_name = $package->getModuleNameFromZip($uploadfilename); + + if($moduleupdate_name == null) { + $smarty->assign("MODULEUPDATE_FAILED", "true"); + $smarty->assign("MODULEUPDATE_FILE_INVALID", "true"); + } else if(!$package->isLanguageType() && ($moduleupdate_name != $target_modulename)) { + $smarty->assign("MODULEUPDATE_FAILED", "true"); + $smarty->assign("MODULEUPDATE_NAME_MISMATCH", "true"); + } else if($package->isLanguageType() && (trim($package->xpath_value('prefix')) != $target_modulename)) { + $smarty->assign("MODULEUPDATE_FAILED", "true"); + $smarty->assign("MODULEUPDATE_NAME_MISMATCH", "true"); + } else { + + $moduleupdate_dep_vtversion = $package->getDependentVtigerVersion(); + $moduleupdate_license = $package->getLicense(); + $moduleupdate_version = $package->getVersion(); + + if(!$package->isLanguageType()) { + $moduleInstance = Vtiger_Module::getInstance($moduleupdate_name); + $moduleupdate_exists=($moduleInstance)? "true" : "false"; + $moduleupdate_dir_name="modules/$moduleupdate_name"; + $moduleupdate_dir_exists= (is_dir($moduleupdate_dir_name)? "true" : "false"); + + $smarty->assign("MODULEUPDATE_CUR_VERSION", ($moduleInstance? $moduleInstance->version : '')); + $smarty->assign("MODULEUPDATE_NOT_EXISTS", !($moduleupdate_exists)); + $smarty->assign("MODULEUPDATE_DIR", $moduleupdate_dir_name); + $smarty->assign("MODULEUPDATE_DIR_NOT_EXISTS", !($moduleupdate_dir_exists)); + + // If version is matching, dis-allow migration + if(version_compare($moduleupdate_version, $moduleInstance->version, '=')) { + $smarty->assign("MODULEUPDATE_FAILED", "true"); + $smarty->assign("MODULEUPDATE_SAME_VERSION", "true"); + } + } + + $smarty->assign("MODULEUPDATE_FILE", $uploadfile); + $smarty->assign("MODULEUPDATE_TYPE", $package->type()); + $smarty->assign("MODULEUPDATE_NAME", $moduleupdate_name); + $smarty->assign("MODULEUPDATE_DEP_VTVERSION", $moduleupdate_dep_vtversion); + $smarty->assign("MODULEUPDATE_VERSION", $moduleupdate_version); + $smarty->assign("MODULEUPDATE_LICENSE", $moduleupdate_license); + } + } +} else if($module_update_step == 'Step3') { + $uploadfile = $_REQUEST['module_import_file']; + $uploadfilename = "$modulemanager_uploaddir/$uploadfile"; + checkFileAccess($uploadfilename); + + //$overwritedir = ($_REQUEST['module_dir_overwrite'] == 'true')? true : false; + $overwritedir = false; // Disallowing overwrites through Module Manager UI + + $updatetype = $_REQUEST['module_update_type']; + if(strtolower($updatetype) == 'language') { + $package = new Vtiger_Language(); + } else { + $package = new Vtiger_Package(); + } + $Vtiger_Utils_Log = true; + // NOTE: Import function will be called from Smarty to capture the log cleanly. + //$package->update($moduleInstance, $uploadfilename); + //unlink($uploadfilename); + $smarty->assign("MODULEUPDATE_PACKAGE", $package); + $smarty->assign("MODULEUPDATE_TARGETINSTANCE", Vtiger_Module::getInstance($target_modulename)); + $smarty->assign("MODULEUPDATE_PACKAGE_FILE", $uploadfilename); +} + +$smarty->display("Settings/ModuleManager/ModuleUpdate$module_update_step.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/OrgSharingDetailView.php b/oss/vtiger/trunk/modules/Settings/OrgSharingDetailView.php new file mode 100644 index 00000000..3e406d5c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/OrgSharingDetailView.php @@ -0,0 +1,163 @@ + $def_perr) +{ + + $entity_name = getTabname($tab_id); + if($tab_id == 6) + { + $cont_name = getTabname(4); + $entity_name .= ' & '.$cont_name; + } + + $entity_perr = getDefOrgShareActionName($def_perr); + + $access_privileges[] = $entity_name; + $access_privileges[] = $entity_perr; + if($entity_perr != 'Private') + $access_privileges[] = $mod_strings['LBL_USR_CAN_ACCESS'] .str_replace('Public:','',$mod_strings[$entity_perr]). $mod_strings['LBL_USR_OTHERS'] . $app_strings[$entity_name]; + else + $access_privileges[] = $mod_strings['LBL_USR_CANNOT_ACCESS'] . $app_strings[$entity_name]; + $row++; +} +$access_privileges=array_chunk($access_privileges,3); +$smarty->assign("DEFAULT_SHARING", $access_privileges); + +$custom_access = array(); +//Lead Sharing +$custom_access['Leads'] = getSharingRuleList('Leads'); + +//Account Sharing +$custom_access['Accounts'] = getSharingRuleList('Accounts'); + +//Potential Sharing +$custom_access['Potentials'] = getSharingRuleList('Potentials'); + +//HelpDesk Sharing +$custom_access['HelpDesk'] = getSharingRuleList('HelpDesk'); + +//Email Sharing +//$custom_access['Emails'] = getSharingRuleList('Emails'); + +//Campaign Sharing +$custom_access['Campaigns'] = getSharingRuleList('Campaigns'); + +//Quotes Sharing +$custom_access['Quotes'] = getSharingRuleList('Quotes'); + +//Purchase Order Sharing +$custom_access['PurchaseOrder'] = getSharingRuleList('PurchaseOrder'); + +//Sales Order Sharing +$custom_access['SalesOrder'] = getSharingRuleList('SalesOrder'); + +//Invoice Sharing +$custom_access['Invoice'] = getSharingRuleList('Invoice'); + +//Document Sharing +$custom_access['Documents'] = getSharingRuleList('Documents'); + +// Look up for modules for which sharing access is enabled. +// NOTE: Accounts and Contacts has been couple, so we need to elimiate Contacts also +$othermodules = getSharingModuleList(Array('Contacts')); +if(!empty($othermodules)) { + foreach($othermodules as $moduleresname) { + if(!isset($custom_access[$moduleresname])) { + $custom_access[$moduleresname] = getSharingRuleList($moduleresname); + } + } +} + +$smarty->assign("MODSHARING", $custom_access); + +/** returns the list of sharing rules for the specified module + * @param $module -- Module Name:: Type varchar + * @returns $access_permission -- sharing rules list info array:: Type array + * + */ +function getSharingRuleList($module) +{ + global $adb,$mod_strings; + + $tabid=getTabid($module); + $dataShareTableArray=getDataShareTableandColumnArray(); + + $i=1; + $access_permission = array(); + foreach($dataShareTableArray as $table_name => $colName) + { + + $colNameArr=explode("::",$colName); + $query = "select ".$table_name.".* from ".$table_name." inner join vtiger_datashare_module_rel on ".$table_name.".shareid=vtiger_datashare_module_rel.shareid where vtiger_datashare_module_rel.tabid=?"; + $result=$adb->pquery($query, array($tabid)); + $num_rows=$adb->num_rows($result); + + $share_colName=$colNameArr[0]; + $share_modType=getEntityTypeFromCol($share_colName); + + $to_colName=$colNameArr[1]; + $to_modType=getEntityTypeFromCol($to_colName); + + for($j=0;$j<$num_rows;$j++) + { + $shareid=$adb->query_result($result,$j,"shareid"); + $share_id=$adb->query_result($result,$j,$share_colName); + $to_id=$adb->query_result($result,$j,$to_colName); + $permission = $adb->query_result($result,$j,'permission'); + + $share_ent_disp = getEntityDisplayLink($share_modType,$share_id); + $to_ent_disp = getEntityDisplayLink($to_modType,$to_id); + + if($permission == 0) + { + $perr_out = $mod_strings['Read Only ']; + } + elseif($permission == 1) + { + $perr_out = $mod_strings['Read/Write']; + } + + $access_permission [] = $shareid; + $access_permission [] = $share_ent_disp; + $access_permission [] = $to_ent_disp; + $access_permission [] = $perr_out; + + $i++; + } + + } + if(is_array($access_permission)) + $access_permission = array_chunk($access_permission,4); + return $access_permission; +} +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); + +$smarty->display("OrgSharingDetailView.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/OrganizationConfig.php b/oss/vtiger/trunk/modules/Settings/OrganizationConfig.php new file mode 100644 index 00000000..de7d6dcf --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/OrganizationConfig.php @@ -0,0 +1,95 @@ +pquery($sql, array()); +$organization_name = $adb->query_result($result,0,'organizationname'); +$organization_address= $adb->query_result($result,0,'address'); +$organization_city = $adb->query_result($result,0,'city'); +$organization_state = $adb->query_result($result,0,'state'); +$organization_code = $adb->query_result($result,0,'code'); +$organization_country = $adb->query_result($result,0,'country'); +$organization_phone = $adb->query_result($result,0,'phone'); +$organization_fax = $adb->query_result($result,0,'fax'); +$organization_website = $adb->query_result($result,0,'website'); +//Handle for allowed organation logo/logoname likes UTF-8 Character +$organization_logo = decode_html($adb->query_result($result,0,'logo')); +$organization_logoname = decode_html($adb->query_result($result,0,'logoname')); + +if (isset($organization_name)) + $smarty->assign("ORGANIZATIONNAME",$organization_name); +if (isset($organization_address)) + $smarty->assign("ORGANIZATIONADDRESS",$organization_address); +if (isset($organization_city)) + $smarty->assign("ORGANIZATIONCITY",$organization_city); +if (isset($organization_state)) + $smarty->assign("ORGANIZATIONSTATE",$organization_state); +if (isset($organization_code)) + $smarty->assign("ORGANIZATIONCODE",$organization_code); +if (isset($organization_country)) + $smarty->assign("ORGANIZATIONCOUNTRY",$organization_country); +if (isset($organization_phone)) + $smarty->assign("ORGANIZATIONPHONE",$organization_phone); +if (isset($organization_fax)) + $smarty->assign("ORGANIZATIONFAX",$organization_fax); +if (isset($organization_website)) + $smarty->assign("ORGANIZATIONWEBSITE",$organization_website); +if (isset($organization_logo)) + $smarty->assign("ORGANIZATIONLOGO",$organization_logo); + +$path = "test/logo"; +$dir_handle = @opendir($path) or die("Unable to open directory $path"); + +while ($file = readdir($dir_handle)) +{ + $filetyp =str_replace(".",'',strtolower(substr($file, -4))); + if($organization_logoname==$file) + { + if ($filetyp == 'jpeg' OR $filetyp == 'jpg' OR $filetyp == 'png') + { + if($file!="." && $file!="..") + { + + $organization_logopath= $path; + $logo_name=$file; + } + + } + } +} + + +if (isset($organization_logopath)) + $smarty->assign("ORGANIZATIONLOGOPATH",$path); +if (isset($organization_logoname)) + $smarty->assign("ORGANIZATIONLOGONAME",$logo_name); +closedir($dir_handle); + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->display('Settings/CompanyInfo.tpl'); +?> diff --git a/oss/vtiger/trunk/modules/Settings/OrganizationTermsandConditions.php b/oss/vtiger/trunk/modules/Settings/OrganizationTermsandConditions.php new file mode 100644 index 00000000..b2edd44c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/OrganizationTermsandConditions.php @@ -0,0 +1,46 @@ +pquery($sql, array()); +$inventory_id = $adb->query_result($result,0,'id'); +$inventory_type = $adb->query_result($result,0,'type'); +$inventory_tandc = $adb->query_result($result,0,'tandc'); + +if(!isset($_REQUEST['inv_terms_mode'])) + $inventory_tandc = nl2br($inventory_tandc); + +if (isset($inventory_tandc)) + $smarty->assign("INV_TERMSANDCONDITIONS",$inventory_tandc); +if(isset($_REQUEST['inv_terms_mode']) && $_REQUEST['inv_terms_mode'] != '') + $smarty->assign("INV_TERMS_MODE",vtlib_purify($_REQUEST['inv_terms_mode'])); +else + $smarty->assign("INV_TERMS_MODE",'view'); + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->display("Settings/InventoryTerms.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ProxyServerConfig.php b/oss/vtiger/trunk/modules/Settings/ProxyServerConfig.php new file mode 100644 index 00000000..717a787c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ProxyServerConfig.php @@ -0,0 +1,61 @@ +assign("ERROR_MSG",''.$mod_strings[vtlib_purify($_REQUEST["error"])].''); + else + $smarty->assign("ERROR_MSG",''.vtlib_purify($_REQUEST["error"]).''); +} +$sql="select * from vtiger_systems where server_type = ?"; +$result = $adb->pquery($sql, array('proxy')); +$server = $adb->query_result($result,0,'server'); +$server_port = $adb->query_result($result,0,'server_port'); +$server_username = $adb->query_result($result,0,'server_username'); +$server_password = $adb->query_result($result,0,'server_password'); + +if(isset($_REQUEST['proxy_server_mode']) && $_REQUEST['proxy_server_mode'] != '') + $smarty->assign("PROXY_SERVER_MODE",vtlib_purify($_REQUEST['proxy_server_mode'])); +else + $smarty->assign("PROXY_SERVER_MODE",'view'); +if(isset($_REQUEST['server'])) + $smarty->assign("PROXYSERVER",vtlib_purify($_REQUEST['server'])); +elseif (isset($server)) + $smarty->assign("PROXYSERVER",$server); +if (isset($_REQUEST['port'])) + $smarty->assign("PROXYPORT",vtlib_purify($_REQUEST['port'])); +elseif (isset($server_port)) + $smarty->assign("PROXYPORT",$server_port); +if (isset($_REQUEST['server_user'])) + $smarty->assign("PROXYUSER",vtlib_purify($_REQUEST['server_user'])); +elseif (isset($server_username)) + $smarty->assign("PROXYUSER",$server_username); +if (isset($server_password)) + $smarty->assign("PROXYPASSWORD",$server_password); + + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->display("Settings/ProxyServer.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/RoleDeleteStep1.php b/oss/vtiger/trunk/modules/Settings/RoleDeleteStep1.php new file mode 100644 index 00000000..0b49acbc --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/RoleDeleteStep1.php @@ -0,0 +1,36 @@ +assign("APP", $app_strings); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("CMOD", $mod_strings); +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("IMAGE_PATH",$image_path); + +$smarty->assign("ROLEID", $delete_role_id); +$smarty->assign("ROLENAME", $delete_role_name); +$opt = ''; +$smarty->assign("ROLEPOPUPBUTTON", $opt); +$smarty->display("DeleteRole.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/RoleDetailView.php b/oss/vtiger/trunk/modules/Settings/RoleDetailView.php new file mode 100644 index 00000000..5a8f403e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/RoleDetailView.php @@ -0,0 +1,91 @@ +$profileName) + { + $profileinfo[]=$profileId; + $profileinfo[]=$profileName; + $profileList .= ''.$profileName.''; + } + $profileinfo=array_chunk($profileinfo,2); + + //Constructing the Users List + $userinfo = Array(); + foreach($roleUserArr as $userId=>$userName) + { + $userinfo[]= $userId; + $userinfo[]= $userName; + $userList .= ''.$userName.''; + } + $userinfo=array_chunk($userinfo,2); + + //Check for Current User + global $current_user; + $current_role = fetchUserRole($current_user->id); + $return_data = Array('profileinfo'=>$profileinfo,'userinfo'=>$userinfo); + return $return_data; +} + +if(isset($_REQUEST['roleid']) && $_REQUEST['roleid'] != '') +{ + $roleid= vtlib_purify($_REQUEST['roleid']); + $mode = vtlib_purify($_REQUEST['mode']); + $roleInfo=getRoleInformation($roleid); + $thisRoleDet=$roleInfo[$roleid]; + $rolename = $thisRoleDet[0]; + $parent = $thisRoleDet[3]; + //retreiving the vtiger_profileid + $roleRelatedProfiles=getRoleRelatedProfiles($roleid); + +} +$parentname=getRoleName($parent); +//Retreiving the Role Info +$roleInfoArr=getRoleInformation($roleid); +$rolename=$roleInfoArr[$roleid][0]; +$smarty->assign("ROLE_NAME",$rolename); +$smarty->assign("ROLEID",$roleid); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("ROLEINFO",getStdOutput($roleid)); +$smarty->assign("PARENTNAME",$parentname); + +$smarty->display("RoleDetailView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/Save.php b/oss/vtiger/trunk/modules/Settings/Save.php new file mode 100644 index 00000000..a4854cd1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/Save.php @@ -0,0 +1,173 @@ +query_result($adb->pquery($sql, array($server_type)),0,"id"); + +if($server_type == 'proxy') +{ + $action = 'ProxyServerConfig&proxy_server_mode=edit'; + if (!$sock =@fsockopen($server, $port, $errno, $errstr, 30)) + { + $error_str = 'error=Unable to connect "'.$server.':'.$port.'"'; + $db_update = false; + }else + { + $url = "http://www.google.co.in"; + $proxy_cont = ''; + $sock = fsockopen($server, $port); + if (!$sock) {return false;} + fputs($sock, "GET $url HTTP/1.0\r\nHost: $server\r\n"); + fputs($sock, "Proxy-Authorization: Basic " . base64_encode ("$server_username:$server_password") . "\r\n\r\n"); + while(!feof($sock)) {$proxy_cont .= fread($sock,4096);} + fclose($sock); + $proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4); + + if(substr_count($proxy_cont, "Cache Access Denied") > 0) + { + $error_str = 'error=LBL_PROXY_AUTHENTICATION_REQUIRED'; + $db_update = false; + } + else + { + $action = 'ProxyServerConfig'; + } + } +} + +if($server_type == 'ftp_backup') +{ + $action = 'BackupServerConfig&bkp_server_mode=edit&server='.$server.'&server_user='.$server_username.'&password='.$server_password; + if(!function_exists('ftp_connect')){ + $error_str = 'error=FTP support is not enabled.'; + $db_update = false; + }else + { + $conn_id = @ftp_connect($server); + if(!$conn_id) + { + $error_str = 'error=Unable to connect "'.$server.'"'; + $db_update = false; + }else + { + if(!@ftp_login($conn_id, $server_username, $server_password)) + { + $error_str = 'error=Couldn\'t connect to "'.$server.'" as user "'.$server_username.'"'; + $db_update = false; + } + else + { + $action = 'BackupServerConfig'; + } + ftp_close($conn_id); + } + } +} +if($server_type == 'local_backup') +{ + $action = 'BackupServerConfig&local_server_mode=edit&server_path="'.$server_path.'"'; + if(!is_dir($server_path)){ + $error_str = 'error1=Folder doesnt Exist or Specified a path which is not a folder'; + $db_update = false; + }else + { + if(!is_writable($server_path)) + { + $error_str = 'error1=Access Denied to write to "'.$server_path.'"'; + $db_update = false; + }else + { + $action = 'BackupServerConfig'; + } + } +} +if($server_type == 'proxy' || $server_type == 'ftp_backup' || $server_type == 'local_backup') +{ + if($db_update) + { + if($id=='') { + $id = $adb->getUniqueID('vtiger_systems'); + $sql="insert into vtiger_systems values(?,?,?,?,?,?,?,?)"; + $params = array($id, $server, $port, $server_username, $server_password, $server_type, $smtp_auth,$server_path); + } + else { + $sql="update vtiger_systems set server = ?, server_username = ?, server_password = ?, smtp_auth= ?, server_type = ?, server_port= ?, server_path = ? where id = ?"; + $params = array($server, $server_username, $server_password, $smtp_auth, $server_type, $port, $server_path, $id); + } + $adb->pquery($sql, $params); + } +} +//Added code to send a test mail to the currently logged in user +if($server_type != 'ftp_backup' && $server_type != 'proxy' && $server_type != 'local_backup') +{ + require_once("modules/Emails/mail.php"); + global $current_user; + + $to_email = getUserEmailId('id',$current_user->id); + $from_email = $to_email; + $subject = 'Test mail about the mail server configuration.'; + $description = 'Dear '.$current_user->user_name.',

    This is a test mail sent to confirm if a mail is actually being sent through the smtp server that you have configured.
    Feel free to delete this mail.

    Thanks and Regards,
    Team vTiger

    '; + if($to_email != '') + { + $mail_status = send_mail('Users',$to_email,$current_user->user_name,$from_email,$subject,$description); + $mail_status_str = $to_email."=".$mail_status."&&&"; + } + else + { + $mail_status_str = "'".$to_email."'=0&&&"; + } + $error_str = getMailErrorString($mail_status_str); + $action = 'EmailConfig'; + if($mail_status != 1) { + $action = 'EmailConfig&emailconfig_mode=edit&server_name='. + vtlib_purify($_REQUEST['server']).'&server_user='. + vtlib_purify($_REQUEST['server_username']).'&auth_check='. + vtlib_purify($_REQUEST['smtp_auth']); + } + else{ + if($db_update) + { + if($id=='') { + $id = $adb->getUniqueID("vtiger_systems"); + $sql="insert into vtiger_systems values(?,?,?,?,?,?,?,?)"; + $params = array($id, $server, $port, $server_username, $server_password, $server_type, $smtp_auth, ''); + } else { + $sql="update vtiger_systems set server=?, server_username=?, server_password=?, smtp_auth=?, server_type=?, server_port=? where id=?"; + $params = array($server, $server_username, $server_password, $smtp_auth, $server_type, $port, $id); + } + $adb->pquery($sql, $params); + } + } +} +//While configuring Proxy settings, the submitted values will be retained when exception is thrown - dina +if($server_type == 'proxy' && $error_str != '') +{ + header("Location: index.php?module=Settings&parenttab=Settings&action=$action&server=$server&port=$port&server_username=$server_username&$error_str"); +} +else +{ + header("Location: index.php?module=Settings&parenttab=Settings&action=$action&$error_str"); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/SaveAuditTrail.php b/oss/vtiger/trunk/modules/Settings/SaveAuditTrail.php new file mode 100644 index 00000000..49b0acd1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveAuditTrail.php @@ -0,0 +1,44 @@ + diff --git a/oss/vtiger/trunk/modules/Settings/SaveCompany.php b/oss/vtiger/trunk/modules/Settings/SaveCompany.php new file mode 100644 index 00000000..637dfbf3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveCompany.php @@ -0,0 +1,41 @@ +pquery($sql, array($org_name)); +$org_name = $adb->query_result($result,0,'organizationname'); + +if($org_name=='') +{ + $sql="insert into vtiger_organizationdetails values(?,?,?,?,?,?,?,?,?)"; + $params = array($organization_name, $organization_address, $organization_city, $organization_state, $organization_code, $organization_country, $organization_phone, $organization_fax, $organization_website); +} +else +{ + $sql="update vtiger_organizationdetails set organizationname = ?, address = ?, city = ?, state = ?, code = ?, country = ?, phone = ?, fax = ?, website = ? where organizationname = ?"; + $params = array($organization_name, $organization_address, $organization_city, $organization_state, $organization_code, $organization_country, $organization_phone, $organization_fax, $organization_website, $org_name); +} +$adb->pquery($sql, $params); + +header("Location: index.php?module=Settings&action=OrganizationConfig"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/SaveConvertLead.php b/oss/vtiger/trunk/modules/Settings/SaveConvertLead.php new file mode 100644 index 00000000..a9928b3c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveConvertLead.php @@ -0,0 +1,48 @@ +pquery($sql, array()); +$noofrows = $adb->num_rows($result); + +for($i=0;$i<$noofrows;$i++) +{ + $lead_id=$adb->query_result($result,$i,"fieldid"); + $account_id_name=$lead_id."_account"; + $contact_id_name=$lead_id."_contact"; + $potential_id_name=$lead_id."_potential"; + + $account_id_val=$_REQUEST[$account_id_name]; + $contact_id_val=$_REQUEST[$contact_id_name]; + $potential_id_val=$_REQUEST[$potential_id_name]; + + if($account_id_val=="None") + { + $account_id_val=0; + } + if($contact_id_val=="None") + { + $contact_id_val=0; + } + if($potential_id_val =="None") + { + $potential_id_val=0; + } + $update_sql="update vtiger_convertleadmapping set accountfid=?, contactfid=?, potentialfid=? where leadfid=?"; + $update_params = array($account_id_val, $contact_id_val, $potential_id_val, $lead_id); + $adb->pquery($update_sql, $update_params); +} +header("Location: index.php?action=CustomFieldList&module=Settings&parenttab=Settings"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/SaveCurrencyInfo.php b/oss/vtiger/trunk/modules/Settings/SaveCurrencyInfo.php new file mode 100644 index 00000000..8e4fd188 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveCurrencyInfo.php @@ -0,0 +1,43 @@ +pquery("select currency_status from vtiger_currency_info where id=?", array($_REQUEST['record'])); + $old_cur_status = $adb->query_result($cur_status_res,0,'currency_status'); + + if($currency_status != $old_cur_status && $currency_status == 'Inactive') { + $transfer_cur_id = $_REQUEST['transfer_currency_id']; + if($transfer_cur_id != null) transferCurrency($_REQUEST['record'], $transfer_cur_id); + } + + $sql = "update vtiger_currency_info set currency_name =?, currency_code =?, currency_symbol =?, conversion_rate =?,currency_status=? where id =?"; + $params = array($currency_name, $currency_code, $currency_symbol, $conversion_rate, $currency_status, $_REQUEST['record']); +} +else +{ + $sql = "insert into vtiger_currency_info values(?,?,?,?,?,?,?,?)"; + $params = array($db->getUniqueID("vtiger_currency_info"), $currency_name, $currency_code, $currency_symbol, $conversion_rate, $currency_status,'0','0'); +} +$adb->pquery($sql, $params); +$loc = "Location: index.php?module=Settings&action=CurrencyListView&parenttab=".vtlib_purify($_REQUEST['parenttab']); +header($loc); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/SaveEnableBackup.php b/oss/vtiger/trunk/modules/Settings/SaveEnableBackup.php new file mode 100644 index 00000000..72c26f94 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveEnableBackup.php @@ -0,0 +1,109 @@ +pquery("select * from vtiger_systems where server_type = ?", array('ftp_backup')); + $BackRowsCheck = $adb->num_rows($GetBackup); + + if($BackRowsCheck > 0) + echo "SUCCESS"; + else + echo "FAILURE"; + +} +if(isset($_REQUEST['enable_local_backup']) && $_REQUEST['enable_local_backup'] != '') +{ + global $root_directory; + $filename = $root_directory.'user_privileges/enable_backup.php'; + + $readhandle = @fopen($filename, "r+"); + + if($readhandle) + { + $buffer = ''; + $new_buffer = ''; + while(!feof($readhandle)) + { + $buffer = fgets($readhandle, 5200); + list($starter, $tmp) = explode(" = ", $buffer); + + if($starter == '$enable_local_backup' && stristr($tmp,'false')) + { + $new_buffer .= "\$enable_local_backup = 'true';\n"; + } + elseif($starter == '$enable_local_backup' && stristr($tmp,'true')) + { + $new_buffer .= "\$enable_local_backup = 'false';\n"; + } + else + $new_buffer .= $buffer; + } + fclose($readhandle); + } + + $handle = fopen($filename, "w"); + fputs($handle, $new_buffer); + fclose($handle); +} +elseif(isset($_REQUEST['GetBackupDetail']) && $_REQUEST['GetBackupDetail'] != '' && $_REQUEST['servertype'] == 'local_backup') +{ + require_once("include/database/PearDatabase.php"); + global $mod_strings,$adb; + + $GetBackup = $adb->pquery("select * from vtiger_systems where server_type = ?", array('local_backup')); + $BackRowsCheck = $adb->num_rows($GetBackup); + + if($BackRowsCheck > 0) + echo "SUCCESS"; + else + echo "FAILURE"; + +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/SaveInventoryNotification.php b/oss/vtiger/trunk/modules/Settings/SaveInventoryNotification.php new file mode 100644 index 00000000..bc88fd40 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveInventoryNotification.php @@ -0,0 +1,23 @@ +pquery($query, $params); +} +$loc = "Location: index.php?action=SettingsAjax&file=listinventorynotifications&module=Settings&directmode=ajax"; +header($loc); +?> diff --git a/oss/vtiger/trunk/modules/Settings/SaveNotification.php b/oss/vtiger/trunk/modules/Settings/SaveNotification.php new file mode 100644 index 00000000..1a55954f --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveNotification.php @@ -0,0 +1,36 @@ +pquery($query, $params); + } + $loc = "Location: index.php?action=SettingsAjax&file=listnotificationschedulers&module=Settings&directmode=ajax"; + header($loc); +} +else +{ + echo ":#:FAILURE"; +} + +?> diff --git a/oss/vtiger/trunk/modules/Settings/SaveRole.php b/oss/vtiger/trunk/modules/Settings/SaveRole.php new file mode 100644 index 00000000..9e70b9af --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveRole.php @@ -0,0 +1,65 @@ +pquery($query, $params); + if($adb->num_rows($result) > 0) + { + echo $mod_strings['LBL_ROLENAME_EXIST']; + die; + }else + { + echo 'SUCCESS'; + die; + } + +} +$parentRoleId=$_REQUEST['parent']; +//Inserting values into Role Table +if(isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'edit') +{ + $roleId = $_REQUEST['roleid']; + $selected_col_string = $_REQUEST['selectedColumnsString']; + $profile_array = explode(';',$selected_col_string); + updateRole($roleId,$rolename,$profile_array); + +} +elseif(isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'create') +{ + $selected_col_string = $_REQUEST['selectedColumnsString']; + $profile_array = explode(';',$selected_col_string); + //Inserting into vtiger_role Table + $roleId = createRole($rolename,$parentRoleId,$profile_array); + if($roleId != '') + { + insertRole2Picklist($roleId,$parentRoleId); + } + +} + +$loc = "Location: index.php?action=listroles&module=Settings&parenttab=Settings"; +header($loc); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/SaveSharingRule.php b/oss/vtiger/trunk/modules/Settings/SaveSharingRule.php new file mode 100644 index 00000000..2de05b5d --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SaveSharingRule.php @@ -0,0 +1,57 @@ +$ds_rm_id) + { + $reltabname=getTabModuleName($reltabid); + $relSharePermission=$_REQUEST[$reltabname.'_accessopt']; + addRelatedModuleSharingPermission($shareId,$tabid,$reltabid,$relSharePermission); + } + +} +elseif($mode == 'edit') +{ + $shareId=$_REQUEST['shareId']; + updateSharingRule($shareId,$tabid,$share_entity_type,$to_entity_type,$share_entity_id,$to_entity_id,$module_sharing_access); + //Adding the Related ModulePermission Sharing + foreach($relatedShareModuleArr as $reltabid=>$ds_rm_id) + { + $reltabname=getTabModuleName($reltabid); + $relSharePermission=$_REQUEST[$reltabname.'_accessopt']; + updateRelatedModuleSharingPermission($shareId,$tabid,$reltabid,$relSharePermission); + } +} + +$loc = "Location: index.php?action=OrgSharingDetailView&module=Settings&parenttab=Settings"; +header($loc); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/Settings.js b/oss/vtiger/trunk/modules/Settings/Settings.js new file mode 100644 index 00000000..3fd0758c --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/Settings.js @@ -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. + ************************************************************************************/ diff --git a/oss/vtiger/trunk/modules/Settings/SettingsAjax.php b/oss/vtiger/trunk/modules/Settings/SettingsAjax.php new file mode 100644 index 00000000..9ea113cb --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/SettingsAjax.php @@ -0,0 +1,36 @@ +pquery($sql, array($current_user->id)); + if($adb->num_rows($is_announce) > 0) { + $query="update vtiger_announcement set announcement=?,time=?,title=? where creatorid=?"; + $params = array($announcement, $adb->formatDate($date_var, true), 'announcement', $current_user->id); + } else { + $query="insert into vtiger_announcement values (?,?,?,?)"; + $params = array($current_user->id,$announcement,'announcement',$adb->formatDate($date_var, true)); + } + $result=$adb->pquery($query, $params); + echo $announcement; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/ShowAuditTrail.php b/oss/vtiger/trunk/modules/Settings/ShowAuditTrail.php new file mode 100644 index 00000000..40cf1c24 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/ShowAuditTrail.php @@ -0,0 +1,79 @@ +pquery($qry, array($userid)); +$no_of_rows = $adb->num_rows($qry_result); + +//Retreiving the start value from request +if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); +} else + $start=1; + +//Retreive the Navigation array +$navigation_array = getNavigationValues($start, $no_of_rows, '100'); + +$start_rec = $navigation_array['start']; +$end_rec = $navigation_array['end_val']; +$record_string= $app_strings[LBL_SHOWING]." " .$start_rec." - ".$end_rec." " .$app_strings[LBL_LIST_OF] ." ".$no_of_rows; + +$navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Settings","ShowAuditTrail",''); + +$smarty->assign("MOD", $current_module_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("THEME_PATH",$theme_path); +$smarty->assign("LIST_HEADER",$focus->getAuditTrailHeader()); +$smarty->assign("LIST_ENTRIES",$focus->getAuditTrailEntries($userid, $navigation_array, $sorder, $sortby)); +$smarty->assign("RECORD_COUNTS", $record_string); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("USERID", $userid); +$smarty->assign("CATEGORY",$category); + +if($_REQUEST['ajax'] !='') + $smarty->display("ShowAuditTrailContents.tpl"); +else + $smarty->display("ShowAuditTrail.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/TaxConfig.php b/oss/vtiger/trunk/modules/Settings/TaxConfig.php new file mode 100644 index 00000000..74da2ee1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/TaxConfig.php @@ -0,0 +1,243 @@ +assign("EDIT_MODE", 'true'); +} +elseif($_REQUEST['sh_edit_tax'] == 'true') +{ + $smarty->assign("SH_EDIT_MODE", 'true'); +} + +//To add tax +if($_REQUEST['add_tax_type'] == 'true') +{ + //Add the given tax name and value as a new tax type + echo addTaxType($_REQUEST['addTaxLabel'],$_REQUEST['addTaxValue']); + $getlist = true; +} +elseif($_REQUEST['sh_add_tax_type'] == 'true') +{ + echo addTaxType($_REQUEST['sh_addTaxLabel'],$_REQUEST['sh_addTaxValue'],'sh'); + $getlist = true; +} + +//To Disable ie., delete or enable +if(($_REQUEST['disable'] == 'true' || $_REQUEST['enable'] == 'true') && $_REQUEST['taxname'] != '') +{ + if($_REQUEST['disable'] == 'true') + changeDeleted($_REQUEST['taxname'],1); + else + changeDeleted($_REQUEST['taxname'],0); + $getlist = true; +} +elseif(($_REQUEST['sh_disable'] == 'true' || $_REQUEST['sh_enable'] == 'true') && $_REQUEST['sh_taxname'] != '') +{ + if($_REQUEST['sh_disable'] == 'true') + changeDeleted($_REQUEST['sh_taxname'],1,'sh'); + else + changeDeleted($_REQUEST['sh_taxname'],0,'sh'); + $getlist = true; +} + +//after done save or enable/disable or added new tax the list will be retrieved again from db +if($getlist) +{ + $tax_details = getAllTaxes(); + $sh_tax_details = getAllTaxes('all','sh'); +} + +$smarty->assign("TAX_COUNT", count($tax_details)); +$smarty->assign("SH_TAX_COUNT", count($sh_tax_details)); + +if(count($tax_details) == 0) + $smarty->assign("TAX_COUNT", 0); +if(count($sh_tax_details) == 0) + $smarty->assign("SH_TAX_COUNT", 0); + +$smarty->assign("TAX_VALUES", $tax_details); + +$smarty->assign("SH_TAX_VALUES", $sh_tax_details); + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("MOD", $mod_strings); +$smarty->display("Settings/TaxConfig.tpl"); + + +/** Function to update the list of Tax percentages for the passed tax types + * @param array $new_percentages - array of tax types and the values like [taxid]=new value ie., [1]=3.56, [2]=11.45 + * @param string $sh - sh or empty, if sh passed then update will be done in shipping and handling related table + * @return void + */ +function updateTaxPercentages($new_percentages, $sh='') +{ + global $adb, $log; + $log->debug("Entering into the function updateTaxPercentages"); + + foreach($new_percentages as $taxid => $new_val) + { + if($new_val != '') + { + if($sh != '' && $sh == 'sh') + $query = "update vtiger_shippingtaxinfo set percentage=? where taxid=?"; + else + $query = "update vtiger_inventorytaxinfo set percentage =? where taxid=?"; + $adb->pquery($query, array($new_val, $taxid)); + } + } + + $log->debug("Exiting from the function updateTaxPercentages"); +} + +/** Function to update the list of Tax Labels for the taxes + * @param array $new_labels - array of tax types and the values like [taxid]=new label ie., [1]=aa, [2]=bb + * @param string $sh - sh or empty, if sh passed then update will be done in shipping and handling related table + * @return void + */ +function updateTaxLabels($new_labels, $sh='') +{ + global $adb, $log; + $log->debug("Entering into the function updateTaxPercentages"); + + foreach($new_labels as $taxid => $new_val) + { + if($new_val != '') + { + if($sh != '' && $sh == 'sh') + $query = "update vtiger_shippingtaxinfo set taxlabel= ? where taxid=?"; + else + $query = "update vtiger_inventorytaxinfo set taxlabel = ? where taxid=?"; + $adb->pquery($query, array($new_val, $taxid)); + } + } + + $log->debug("Exiting from the function updateTaxPercentages"); +} +/** Function used to add the tax type which will do database alterations + * @param string $taxlabel - tax label name to be added + * @param string $taxvalue - tax value to be added + * @param string $sh - sh or empty , if sh passed then the tax will be added in shipping and handling related table + * @return void + */ +function addTaxType($taxlabel, $taxvalue, $sh='') +{ + global $adb, $log; + $log->debug("Entering into function addTaxType($taxlabel, $taxvalue, $sh)"); + + //First we will check whether the tax is already available or not + if($sh != '' && $sh == 'sh') + $check_query = "select taxlabel from vtiger_shippingtaxinfo where taxlabel=?"; + else + $check_query = "select taxlabel from vtiger_inventorytaxinfo where taxlabel=?"; + $check_res = $adb->pquery($check_query, array($taxlabel)); + + if($adb->num_rows($check_res) > 0) + return "This tax is already available"; + + //if the tax is not available then add this tax. + //Add this tax as a column in related table + if($sh != '' && $sh == 'sh') + { + $taxid = $adb->getUniqueID("vtiger_shippingtaxinfo"); + $taxname = "shtax".$taxid; + $query = "alter table vtiger_inventoryshippingrel add column $taxname decimal(7,3) default NULL"; + } + else + { + $taxid = $adb->getUniqueID("vtiger_inventorytaxinfo"); + $taxname = "tax".$taxid; + $query = "alter table vtiger_inventoryproductrel add column $taxname decimal(7,3) default NULL"; + } + $res = $adb->pquery($query, array()); + + //if the tax is added as a column then we should add this tax in the list of taxes + if($res) + { + if($sh != '' && $sh == 'sh') + $query1 = "insert into vtiger_shippingtaxinfo values(?,?,?,?,?)"; + else + $query1 = "insert into vtiger_inventorytaxinfo values(?,?,?,?,?)"; + + $params1 = array($taxid, $taxname, $taxlabel, $taxvalue, 0); + $res1 = $adb->pquery($query1, $params1); + } + + $log->debug("Exit from function addTaxType($taxlabel, $taxvalue)"); + if($res1) + return ''; + else + return "There may be some problem in adding the Tax type. Please try again"; +} + +/** Function used to Enable or Disable the tax type + * @param string $taxname - taxname to enable or disble + * @param int $deleted - 0 or 1 where 0 to enable and 1 to disable + * @param string $sh - sh or empty, if sh passed then the enable/disable will be done in shipping and handling tax table ie.,vtiger_shippingtaxinfo else this enable/disable will be done in Product tax table ie., in vtiger_inventorytaxinfo + * @return void + */ +function changeDeleted($taxname, $deleted, $sh='') +{ + global $log, $adb; + $log->debug("Entering into function changeDeleted($taxname, $deleted, $sh)"); + + if($sh == 'sh') + $adb->pquery("update vtiger_shippingtaxinfo set deleted=? where taxname=?", array($deleted, $taxname)); + else + $adb->pquery("update vtiger_inventorytaxinfo set deleted=? where taxname=?", array($deleted, $taxname)); + $log->debug("Exit from function changeDeleted($taxname, $deleted, $sh)"); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/UpdateComboValues.php b/oss/vtiger/trunk/modules/Settings/UpdateComboValues.php new file mode 100644 index 00000000..891a869e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/UpdateComboValues.php @@ -0,0 +1,110 @@ +query_result($adb->pquery($sql, array($tableName)),0,'picklistid'); + +//Deleting the already existing values + +$qry="select roleid,picklistvalueid from vtiger_role2picklist left join vtiger_$tableName on vtiger_$tableName.picklist_valueid=vtiger_role2picklist.picklistvalueid where roleid=? and picklistid=? and presence=1"; +$res = $adb->pquery($qry, array($roleid, $picklistid)); +$num_row = $adb->num_rows($res); +for($s=0;$s < $num_row; $s++) +{ + $valid = $adb->query_result($res,$s,'picklistvalueid'); + $sql="delete from vtiger_role2picklist where roleid=? and picklistvalueid=?"; + $adb->pquery($sql, array($roleid, $valid)); +} + +$pickArray = explode("\n",$fldPickList); +$count = count($pickArray); + +$tabname=explode('cf_',$tableName); + +if($tabname[1]!='') + $custom=true; + +/* ticket2369 fixed */ +$columnName = $tableName; + for($i = 0; $i < $count; $i++) + { + $pickArray[$i] = trim(from_html($pickArray[$i])); + + //if UTF-8 character input given, when configuration is latin1, then avoid the entry which will cause mysql empty object exception in line 101 + $stringConvert = function_exists(iconv) ? @iconv("UTF-8",$default_charset,$pickArray[$i]) : $pickArray[$i]; + $pickArray[$i] = trim($stringConvert); + + if($pickArray[$i] != '') + { + $picklistcount=0; + //This uitype is for non-editable picklist + $sql ="select $tableName from vtiger_$tableName"; + $res = $adb->pquery($sql, array()); + $numrow = $adb->num_rows($res); + for($x=0;$x < $numrow ; $x++) + { + $picklistvalues = decode_html($adb->query_result($res,$x,$tableName)); + + // Fix For: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/5129 + global $current_language; + if($current_language != 'en_us') { + // Translate the value in database and compare with input. + if($fld_module == 'Events') $temp_module_strings = return_module_language($current_language, 'Calendar'); + else $temp_module_strings = return_module_language($current_language, $fld_module); + + $mod_picklistvalue = trim($temp_module_strings[$picklistvalues]); + if($mod_picklistvalue == $pickArray[$i]) { + $pickArray[$i] = $picklistvalues; + } + } + // End + + if($pickArray[$i] == $picklistvalues) + { + $picklistcount++; + } + + } + + if($picklistcount == 0) + { //Inserting a new pick list value to the corresponding picklist table + $picklistvalue_id = getUniquePicklistID(); + $picklist_id = $adb->getUniqueID("vtiger_".$tableName); + $query = "insert into vtiger_".$tableName." values(?,?,?,?)"; + $params = array($picklist_id, $pickArray[$i], 1, $picklistvalue_id); + + $adb->pquery($query, $params); + + } + $picklistcount =0; + $sql = "select picklist_valueid from vtiger_$tableName where $tableName=?"; + $pick_valueid = $adb->query_result($adb->pquery($sql, array($pickArray[$i])),0,'picklist_valueid'); + + //To get the max sortid for the non editable picklist and the inserting by increasing the sortid for editable values.... + $sql ="select max(sortid)+1 as sortid from vtiger_role2picklist left join vtiger_$tableName on vtiger_$tableName.picklist_valueid=vtiger_role2picklist.picklistvalueid where roleid=? and picklistid=? and presence=0"; + $sortid = $adb->query_result($adb->pquery($sql, array($roleid, $picklistid)),0,'sortid'); + + $sql = "insert into vtiger_role2picklist values(?,?,?,?)"; + $adb->pquery($sql, array($roleid, $pick_valueid, $picklistid, $sortid)); + } +} + +header("Location:index.php?action=SettingsAjax&module=Settings&directmode=ajax&file=PickList&fld_module=".$fld_module."&roleid=".$roleid); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/UpdateDefaultFieldLevelAccess.php b/oss/vtiger/trunk/modules/Settings/UpdateDefaultFieldLevelAccess.php new file mode 100644 index 00000000..fbf52328 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/UpdateDefaultFieldLevelAccess.php @@ -0,0 +1,53 @@ +$fld_name) +{ + $fieldListResult = getDefOrgFieldList($fld_module); + $noofrows = $adb->num_rows($fieldListResult); + for($i=0; $i<$noofrows; $i++) + { + $fieldid = $adb->query_result($fieldListResult,$i,"fieldid"); + $displaytype = $adb->query_result($fieldListResult,$i,"displaytype"); + $tab_id = $adb->query_result($fieldListResult,$i,"tabid"); + $visible = vtlib_purify($_REQUEST[$fieldid]); + if($visible == 'on') + { + $visible_value = 0; + } + else + { + $visible_value = 1; + } + //Updating the Mandatory vtiger_fields + $uitype = $adb->query_result($fieldListResult,$i,"uitype"); + $fieldname = $adb->query_result($fieldListResult,$i,"fieldname"); + $typeofdata = $adb->query_result($fieldListResult,$i,"typeofdata"); + $fieldtype = explode("~",$typeofdata); + if(($fieldname == "salutationtype" && $uitype == 55) || $fieldtype[1] == "M" || $uitype == 111 || $displaytype == 3|| $fieldname == "activitytype") + { + $visible_value = 0; + } + //Updating the database + $update_query = "update vtiger_def_org_field set visible=? where fieldid=? and tabid=?"; + $update_params = array($visible_value, $fieldid, $tab_id); + $adb->pquery($update_query, $update_params); + + } +} +$loc = "Location: index.php?action=DefaultFieldPermissions&module=Settings&parenttab=Settings&fld_module=".vtlib_purify($_REQUEST['fld_module']); +header($loc); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/add2db.php b/oss/vtiger/trunk/modules/Settings/add2db.php new file mode 100644 index 00000000..b71e6c3b --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/add2db.php @@ -0,0 +1,161 @@ +pquery($sql, array($org_name)); + $org_name = decode_html($adb->query_result($result,0,'organizationname')); + $org_logo = $adb->query_result($result,0,'logoname'); + + + if($org_name=='') + { + $sql="INSERT INTO vtiger_organizationdetails + (organizationname, address, city, state, code, country, phone, fax, website, logoname) values (?,?,?,?,?,?,?,?,?,?)"; + $params = array($organization_name, $organization_address, $organization_city, $organization_state, $organization_code, + $organization_country, $organization_phone, $organization_fax, $organization_website, $organization_logoname); + } + else + { + if($savelogo=="true") + { + $organization_logoname=$filename; + } + elseif($savelogo=="false" && $error_flag=="") + { + $savelogo="true"; + $organization_logoname=$_REQUEST['PREV_FILE']; + } + else + { + $organization_logoname=$_REQUEST['PREV_FILE']; + } + if($nologo_specified=="true") + { + $savelogo="true"; + $organization_logoname=$org_logo; + } + + $sql = "UPDATE vtiger_organizationdetails + SET organizationname = ?, address = ?, city = ?, state = ?, code = ?, country = ?, + phone = ?, fax = ?, website = ?, logoname = ? WHERE organizationname = ?"; + $params = array($organization_name, $organization_address, $organization_city, $organization_state, $organization_code, + $organization_country, $organization_phone, $organization_fax, $organization_website, decode_html($organization_logoname), $org_name); + } + $adb->pquery($sql, $params); + + if($savelogo=="true") + { + header("Location: index.php?parenttab=Settings&module=Settings&action=OrganizationConfig"); + } + elseif($savelogo=="false") + { + + header("Location: index.php?parenttab=Settings&module=Settings&action=EditCompanyDetails&flag=".$error_flag); + } + + + } +?> + diff --git a/oss/vtiger/trunk/modules/Settings/createemailtemplate.php b/oss/vtiger/trunk/modules/Settings/createemailtemplate.php new file mode 100644 index 00000000..0093e4f2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/createemailtemplate.php @@ -0,0 +1,44 @@ +assign("APP", $app_strings); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("THEME", $theme); +$smarty->assign("THEME_PATH", $theme_path); +$smarty->assign("UMOD", $mod_strings); +$smarty->assign("PARENTTAB", getParentTab()); +$smarty->assign("ALL_VARIABLES", $allOptions); + +$smarty->assign("MOD", $smod_strings); +$smarty->assign("MODULE", 'Settings'); + +$smarty->display("CreateEmailTemplate.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/createnewgroup.php b/oss/vtiger/trunk/modules/Settings/createnewgroup.php new file mode 100644 index 00000000..ac1ee9f1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/createnewgroup.php @@ -0,0 +1,161 @@ +parent_groups[]=$groupId; + $parGroups->getAllParentGroups($groupId); + $parentGroupArray=$parGroups->parent_groups; + + +} +else +{ + $mode = 'create'; + if(isset($_REQUEST['error']) && ($_REQUEST['error']=='true')) + { + $Err_msg = "
    ".$mod_strings['LBL_GROUP_NAME_ERROR']."
    "; + $groupInfo[] = vtlib_purify($_REQUEST['groupname']); + $groupInfo[] = vtlib_purify($_REQUEST['desc']); + } +} + + +//Constructing the Role Array +$roleDetails=getAllRoleDetails(); +$i=0; +$roleIdStr=""; +$roleNameStr=""; +$userIdStr=""; +$userNameStr=""; +$grpIdStr=""; +$grpNameStr=""; + +foreach($roleDetails as $roleId=>$roleInfo) +{ + if($i !=0) + { + if($i !=1) + { + $roleIdStr .= ", "; + $roleNameStr .= ", "; + } + + $roleName=$roleInfo[0]; + $roleIdStr .= "'".$roleId."'"; + $roleNameStr .= "'".addslashes(decode_html($roleName))."'"; + } + + $i++; +} + +//Constructing the User Array +$l=0; +$userDetails=getAllUserName(); +foreach($userDetails as $userId=>$userInfo) +{ + if($l !=0) + { + $userIdStr .= ", "; + $userNameStr .= ", "; + } + + $userIdStr .= "'".$userId."'"; + $userNameStr .= "'".$userInfo."'"; + + $l++; +} + +//Constructing the Group Array +$m=0; +$grpDetails=getAllGroupName(); +foreach($grpDetails as $grpId=>$grpName) +{ + if(! in_array($grpId,$parentGroupArray)) + { + if($m !=0) + { + $grpIdStr .= ", "; + $grpNameStr .= ", "; + } + + $grpIdStr .= "'".$grpId."'"; + $grpNameStr .= "'".addslashes(decode_html($grpName))."'"; + + $m++; + } +} +if($mode == 'edit') +{ + $member=array(); + $groupMemberArr=$groupInfo[2]; + foreach($groupMemberArr as $memberType=>$memberValue) + { + foreach($memberValue as $memberId) + { + if($memberType == 'groups') + { + $memberName=fetchGroupName($memberId); + $memberDisplay="Group::"; + } + elseif($memberType == 'roles') + { + $memberName=getRoleName($memberId); + $memberDisplay="Roles::"; + } + elseif($memberType == 'rs') + { + $memberName=getRoleName($memberId); + $memberDisplay="RoleAndSubordinates::"; + } + elseif($memberType == 'users') + { + $memberName=getUserName($memberId); + $memberDisplay="User::"; + } + $member[]=$memberType.'::'.$memberId; + $member[]=$memberDisplay.$memberName; + } + } + $smarty->assign("MEMBER", array_chunk($member,2)); +} +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("ROLEIDSTR",$roleIdStr); +$smarty->assign("ROLENAMESTR",$roleNameStr); +$smarty->assign("USERIDSTR",$userIdStr); +$smarty->assign("USERNAMESTR",$userNameStr); +$smarty->assign("GROUPIDSTR",$grpIdStr); +$smarty->assign("GROUPNAMESTR",$grpNameStr); +$smarty->assign("RETURN_ACTION",vtlib_purify($_REQUEST['returnaction'])); +$smarty->assign("GROUPID",$groupId); +$smarty->assign("MODE",$mode); +$smarty->assign("GROUPNAME",$groupInfo[0]); +$smarty->assign("DESCRIPTION",$groupInfo[1]); + +$smarty->display("GroupEditView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/createrole.php b/oss/vtiger/trunk/modules/Settings/createrole.php new file mode 100644 index 00000000..a63b1c62 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/createrole.php @@ -0,0 +1,72 @@ +assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("THEME", $theme); + +$parentname=getRoleName($parent); +$smarty->assign("RETURN_ACTION",vtlib_purify($_REQUEST['returnaction'])); +$smarty->assign("ROLEID",$roleid); +$smarty->assign("MODE",$mode); +$smarty->assign("PARENT",$parent); +$smarty->assign("PARENTNAME",$parentname); +$smarty->assign("ROLENAME",$rolename); + +$profile_entries=array(); +foreach($profDetails as $profId=>$profName) +{ + $profile_entries[]=$profId; + $profile_entries[]=$profName; +} +$profile_entries=array_chunk($profile_entries,2); +$smarty->assign("PROFILELISTS",$profile_entries); + +if($mode == 'edit') +{ + $selected_profiles = array(); + foreach($roleRelatedProfiles as $relProfId => $relProfName) + { + $selected_profiles[]=$relProfId; + $selected_profiles[]=$relProfName; + } + $selected_profiles=array_chunk($selected_profiles,2); + $smarty->assign("SELPROFILELISTS",$selected_profiles); +} + +$smarty->display("RoleEditView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/deleteemailtemplate.php b/oss/vtiger/trunk/modules/Settings/deleteemailtemplate.php new file mode 100644 index 00000000..4fb5504b --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/deleteemailtemplate.php @@ -0,0 +1,21 @@ +pquery($sql, array($id_array[$i])); +} + +header("Location:index.php?module=Settings&action=listemailtemplates"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/deletewordtemplate.php b/oss/vtiger/trunk/modules/Settings/deletewordtemplate.php new file mode 100644 index 00000000..3df8fe9a --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/deletewordtemplate.php @@ -0,0 +1,21 @@ +pquery($sql, array($id_array[$i])); +} + +header("Location:index.php?module=Settings&action=listwordtemplates&parenttab=Settings"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/detailviewemailtemplate.php b/oss/vtiger/trunk/modules/Settings/detailviewemailtemplate.php new file mode 100644 index 00000000..7fd22b3d --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/detailviewemailtemplate.php @@ -0,0 +1,61 @@ +info("Inside Email Template Detail View"); + +$smarty = new vtigerCRM_smarty; + +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("UMOD", $mod_strings); +$smod_strings = return_module_language($current_language,'Settings'); +$smarty->assign("MOD", $smod_strings); +$smarty->assign("MODULE", 'Settings'); +$smarty->assign("IMAGE_PATH", $image_path); + +if(isset($_REQUEST['templateid']) && $_REQUEST['templateid']!='') +{ + $log->info("The templateid is set"); + $tempid = $_REQUEST['templateid']; + $sql = "select * from vtiger_emailtemplates where templateid=?"; + $result = $adb->pquery($sql, array($tempid)); + $emailtemplateResult = $adb->fetch_array($result); +} +$smarty->assign("FOLDERNAME", $emailtemplateResult["foldername"]); + +$smarty->assign("TEMPLATENAME", $emailtemplateResult["templatename"]); +$smarty->assign("DESCRIPTION", $emailtemplateResult["description"]); +$smarty->assign("TEMPLATEID", $emailtemplateResult["templateid"]); + +$smarty->assign("SUBJECT", $emailtemplateResult["subject"]); +$smarty->assign("BODY", decode_html($emailtemplateResult["body"])); + +$smarty->display("DetailViewEmailTemplate.tpl"); + +?> + + + + + + diff --git a/oss/vtiger/trunk/modules/Settings/downloadfile.php b/oss/vtiger/trunk/modules/Settings/downloadfile.php new file mode 100644 index 00000000..ad77e54e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/downloadfile.php @@ -0,0 +1,32 @@ +pquery($dbQuery, array()) or die("Couldn't get file list"); +if($adb->num_rows($result) == 1) +{ + $name = @$adb->query_result($result, 0, "logoname"); + $fileContent = @$adb->query_result($result, 0, "logo"); + $name = html_entity_decode($name, ENT_QUOTES, $default_charset); + header("Cache-Control: private"); + header("Content-Disposition: attachment; filename=$name"); + header("Content-Description: PHP Generated Data"); + echo base64_decode($fileContent); +} else { + echo $mod_strings['LBL.RECORD_NOEXIST']; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/editemailtemplate.php b/oss/vtiger/trunk/modules/Settings/editemailtemplate.php new file mode 100644 index 00000000..c9c73c1a --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/editemailtemplate.php @@ -0,0 +1,60 @@ +debug("the templateid is set to the value ".$templateid); +} +$sql = "select * from vtiger_emailtemplates where templateid=?"; +$result = $adb->pquery($sql, array($templateid)); +$emailtemplateResult = str_replace('"','"',$adb->fetch_array($result)); +$smod_strings = return_module_language($current_language,'Settings'); + +//To get Email Template variables -- Pavani +$allOptions=getEmailTemplateVariables(); +$smarty = new vtigerCRM_smarty; + +$smarty->assign("UMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme_path); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("MOD", $smod_strings); +$smarty->assign("FOLDERNAME", $emailtemplateResult["foldername"]); +$smarty->assign("TEMPLATENAME", $emailtemplateResult["templatename"]); +$smarty->assign("TEMPLATEID", $emailtemplateResult["templateid"]); +$smarty->assign("DESCRIPTION", $emailtemplateResult["description"]); +$smarty->assign("SUBJECT", $emailtemplateResult["subject"]); +$smarty->assign("BODY", $emailtemplateResult["body"]); +$smarty->assign("MODULE", 'Settings'); +$smarty->assign("PARENTTAB", getParentTab()); +$smarty->assign("EMODE", $mode); +$smarty->assign("ALL_VARIABLES", $allOptions); + +$smarty->display("CreateEmailTemplate.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/index.php b/oss/vtiger/trunk/modules/Settings/index.php new file mode 100644 index 00000000..bc449175 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/index.php @@ -0,0 +1,34 @@ +assign("APP", $app_strings); +$smarty->assign("MODULE", 'Settings'); +$smarty->assign("CATEGORY", 'Settings'); +$smarty->assign("MOD", $mod_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("IMAGES", "themes/images/"); +$smarty->assign("BLOCKS", getSettingsBlocks()); +$smarty->assign("FIELDS", getSettingsFields()); +$smarty->assign("NUMBER_OF_COLUMNS", 4); //this is the number of columns in the settings page + +$smarty->display("Settings.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/language/en_us.lang.php b/oss/vtiger/trunk/modules/Settings/language/en_us.lang.php new file mode 100644 index 00000000..687fc2fe --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/language/en_us.lang.php @@ -0,0 +1,1204 @@ +'Settings', + +'LBL_MODULE_TITLE'=>'Settings: Home', + +'LBL_LIST_CONTACT_ROLE'=>'Role', + + + +'LBL_LIST_LAST_NAME'=>'Last Name', + +'LBL_FIRST_NAME'=>'First Name:', + +'LBL_LAST_NAME'=>'Last Name:', + +'LBL_PHONE'=>'Phone:', + +'LBL_EMAIL_ADDRESS'=>'Email', + +'LBL_TRANSCURR'=>'Transfer currency to', + +'LBL_CURRDEL'=>'Currency to be Deleted', + +'LBL_NEW_FORM_TITLE'=>'New Contact', + +'LBL_NEW_CURRENCY'=>'New Currency', + +'LBL_VIEWING'=>'Viewing', + +'LBL_CURRENCY_NAME'=>'Currency Name', + +'LBL_CURRENCY_CODE'=>'Currency Code', + +'LBL_CURRENCY_SYMBOL'=>'Symbol', + +'LBL_CURRENCY_CRATE'=>'Conversion Rate', + +'LBL_CURRENCY_STATUS'=>'Status', + +'LBL_CURRENCY_TOOL'=>'Tools', + +'LBL_CURRENCY_LIST'=>'Currencies List', + + +'NTC_DELETE_CONFIRMATION'=>'Are you sure you want to delete this record?', + +'LEADCUSTOMFIELDS'=>'Lead Custom Fields', + +'ACCOUNTCUSTOMFIELDS'=>'Account Custom Fields', + +'CONTACTCUSTOMFIELDS'=>'Contact Custom Fields', + +'OPPORTUNITYCUSTOMFIELDS'=>'Potential Custom Fields', + +'HELPDESKCUSTOMFIELDS'=>'Helpdesk Custom Fields', + +'PRODUCTCUSTOMFIELDS'=>'Product Custom Fields', + +'VENDORCUSTOMFIELDS'=>'Vendor Custom Fields', + +'PRICEBOOKCUSTOMFIELDS'=>'PriceBook Custom Fields', + +'POCUSTOMFIELDS'=>'Purchase Order Custom Fields', +'SOCUSTOMFIELDS'=>'Sales Order Custom Fields', +'QUOTESCUSTOMFIELDS'=>'Quotes Custom Fields', +'INVOICECUSTOMFIELDS'=>'Invoice Custom Fields', + +'EDITLEADPICKLISTVALUES'=>'Edit Lead Picklist ', + +'EDITACCOUNTPICKLISTVALUES'=>'Edit Account Picklist ', + +'EDITCONTACTPICKLISTVALUES'=>'Edit Contact Picklist ', + +'EDITOPPORTUNITYPICKLISTVALUES'=>'Edit Potential Picklist ', + +'EDITHELPDESKPICKLISTVALUES'=>'Edit HelpDesk Picklist ', + +'EDITPRODUCTPICKLISTVALUES'=>'Edit Product Picklist ', + +'EDITEVENTPICKLISTVALUES'=>'Edit Event Picklist ', + +'EDITTASKPICKLISTVALUES'=>'Edit Task Picklist ', + +'EDITRSSPICKLISTVALUES'=>'Edit Rss Picklist', +'EDITVENDORPICKLISTVALUES'=>'Edit Vendor Picklist', +'EDITPBPICKLISTVALUES'=>'Edit PriceBook Picklist', +'EDITPOPICKLISTVALUES'=>'Edit Purchase Order Picklist', +'EDITSOPICKLISTVALUES'=>'Edit Sales Order Picklist', +'EDITQUOTEPICKLISTVALUES'=>'Edit Quote Picklist', +'EDITINVOICEPICKLISTVALUES'=>'Edit Invoice Picklist', + + +// Added for Release vtigerCRM 3.2 PATCH 1.0 + +//Settings/index.php + + +'LBL_PICKLIST_FIELD_SETTINGS'=>'Picklist Field Settings:', + + + +//SETTINGS/CustomFieldList.php,ComboFieldList.php,CreateCustomField.php + +'Leads'=>'Lead', + +'Accounts'=>'Account', + +'Contacts'=>'Contact', + +'Potentials'=>'Potential', + +'HelpDesk'=>'HelpDesk', + +'Products'=>'Product', + +'Events'=>'Event', + +'Activities'=>'Task', + + + + + +'CustomFields'=>' Custom Fields', + +'NewCustomField'=>'New Custom Field', + +'NewCustomFieldAltC'=>'New Custom Field [Alt+c]:', + +'FieldName'=>'Field Name', + +'FieldType'=>'Field Type', + +'FieldLabel'=>'Field Label', + +'Delete'=>'Del', + +'NEW'=>'New', + +'CUSTOMFIELD'=>'Custom Field', + +'LBL_CUSTOM_FIELDS'=>'Custom Fields', + +'LBL_ADD_FIELD'=>'Create Custom Field', + +'LBL_CUSTM_MSG'=>'allows you to ....', + +'PicklistFields'=>' Picklist Fields', + + +'Edit'=>'Edit', + +'LBL_EDIT_FIELD_TYPE'=>'Edit Field Type', + +//Settings/CustomField.html + +'LBL_PROVIDE_FIELD_INFORMATION'=>'Provide Field Information: ', + +'LBL_SELECT_FIELD_TYPE'=>'Select Field Type: ', + +'LBL_PROVIDE_FIELD_DETAILS'=>'Provide Field Details: ', + +'LBL_LABEL'=>'Label: ', + +'LBL_LENGTH'=>'Length: ', + +'LBL_DECIMAL_PLACES'=>'Decimal Places: ', + +'LBL_PICK_LIST_VALUES'=>'Pick list Values: ', + + + +//Settings/EditComboField.php + +'EditPickListValues'=>'Picklist Edit ', + + + +//Settings/EditField.html + +'LBL_FIELD_INFORMATION'=>'Field Information:', + +'Values'=>'Values', + +'EnterListOfValues'=>'Please enter the list of values below. Each value should be in its own line.', + + + +//Settings/fieldtypes.php + +'Text'=>'Text', + +'Number'=>'Number', + +'Percent'=>'Percent', + +'Currency'=>'Currency', + +'Date'=>'Date', + +'Email'=>'Email', + +'Phone'=>'Phone', + +'PickList'=>'Pick List', + +'LBL_MULTISELECT_COMBO'=>'Multi-Select Combo Box', + +'Skype'=>'Skype', + + + +//added for patch2 + +'USERGROUPLIST'=>'Groups', + +'EMAILTEMPLATES'=>'E-mail Templates', + +'WORDINTEGRATION'=>'Mail Merge Templates', + +'LBL_MAIL_MERGE'=>'Mail Merge', + +'NOTIFICATIONSCHEDULERS'=>'Notification Schedulers', +//currency status +'LBL_ACTIVE'=>'Active', + +'LBL_INACTIVE'=>'Inactive', + +'LBL_NOTIFICATION'=>'Notification', +'LBL_DESCRIPTION'=>'Description', +'LBL_TOOL'=>'Tool', + + +//Added fields for Title Informations -- after 4 Beta + +'LBL_EMAIL_CONFIG'=>'Outgoing Mail Server Configuration', + +'LBL_WORD_INTEGRATION'=>'Word Integration:', + +'LBL_GROUP_SETTINGS'=>'Group Settings:', + +'LBL_TEMPLATE_SETTINGS'=>'Template Settings:', + +'LBL_NOTIFICATION_SETTINGS'=>'Notification Settings:', + +'LBL_EMAIL_SETTINGS'=>'Email Settings:', + +'LBL_SECURITY_SETTINGS'=>'Security Settings:', + + + +//Added fields after RC1 - Release + +'LBL_MAIL_SERVER_INFO'=>'Outgoing Mail Server Information', + +'LBL_OUTGOING_MAIL_SERVER'=>'Server Name', + +'LBL_OUTGOING_MAIL_SERVER_LOGIN_USER_NAME'=>'Outgoing Mail Server Login User Name', + +'LBL_OUTGOING_MAIL_SERVER_PASSWORD'=>'Outgoing Mail Server Password', + +'LBL_MAIL_SERVER_SMTP'=>'Mail Server Settings (SMTP)', + +'LBL_BACKUP_SERVER_CONFIG'=>'Backup Server Configuration', + +'LBL_SERVER_ADDRESS'=>'Server Address', + +'LBL_FTP_SERVER_NAME'=>'FTP Server Name', + +'LBL_FTP_USER_NAME'=>'FTP User Name', + +'LBL_FTP_PASSWORD'=>'FTP Password', + +'LBL_FTP'=>'FTP', + +'LBL_SYSTEM_CONFIG'=>'System Configuration', +'LBL_SYSTEM_INFO'=>'System Details', +'LBL_PROXY_SETTINGS'=>'Proxy Server', +'LBL_AUDIT_TRAIL'=>'Audit Trails', +'LBL_ENABLE_AUDIT_TRAIL'=>'Enable Audit Trail', +'LBL_USER_AUDIT'=>'Select User', +'LBL_VIEW_AUDIT_TRAIL'=>'View Audit Trail', +'LBL_AUDIT_TRAIL_DESC'=>'Display Audit Trail of Users who access CRM', +'LBL_NO_DATA'=>'No Data', + +'LBL_CURRENCY_CONFIGURATION'=>'- Currency Information', + +'LBL_CURRENCY_CONFIG'=>'Currency Configuration', + +'LBL_CURRENCY_INFO'=>'Currency Information', + +'LBL_CURRENCY_TITLE'=>'Currency', + +'LBL_CURRENCY_SETTINGS'=>'Currencies', + + +'LBL_USERNAME'=>'User Name', +'LBL_PASWRD'=>'Password', +'LBL_REQUIRES_AUTHENT'=>'Requires Authentication?', + +//Fields for Settings + +'LBL_USER_MANAGEMENT'=>'Users & Access Management', + +'LBL_USERS'=>'Users', + +'LBL_USERS_LIST'=>'Users List', +'LBL_GROUP_LIST'=>'Groups List', + +'LBL_CREATE_AND_MANAGE_USERS'=>'- Create and Manage Users (e.g., admin)', + + +'LBL_CREATE_AND_MANAGE_USER_ROLES'=>'- Create and Manage user roles (e.g., Administrator, Standard User, etc.)', + +'LBL_PROFILES'=>'Profiles', + +'LBL_PROFILES_LIST'=>'Profiles List', + +'LBL_CREATE_AND_MANAGE_USER_PROFILES'=>'- Create and Manage user profiles (e.g., CEO, Sales Manager, etc.)', + +'LBL_CREATE_AND_MANAGE_USER_GROUPS'=>'- Create and Manage user groups', + +'LBL_SHARING_ACCESS'=>'Sharing Access', + +'LBL_FIELDS_ACCESS'=>'Fields Access', + +'LBL_DEFAULT_ORGANIZATION_FIELDS'=>'Default Organization Fields Access', + +'LBL_SETTING_DEFAULT_ORGANIZATION_FIELDS'=>' - Setting Default Field Access within the Organization', + +'LBL_SETTING_DEFAULT_SHARING_ACCESS'=>'- Setting Default Sharing Access within the Organization', + +'LBL_FIELD_ACCESSIBILITY'=>'Field Accessibility', + +'LBL_SETTING_FIELD_ACCESSIBILITY'=>' - Setting Field Accessibility for each profiles', +//<<<<<<<>>>>> +'LBL_FIELD_ORDERING_DESC'=>' - Edit Field Order', + +'LBL_FIELD_ORDERING'=>'Edit Field Blocks', +//<<<<<<<<<>>>>>>>>>>>> +'LBL_LEAD_FIELD_ACCESS'=>'Lead Field Access', + +'LBL_ACCOUNT_FIELD_ACCESS'=>'Account Field Access', + +'LBL_CONTACT_FIELD_ACCESS'=>'Contact Field Access', + +'LBL_OPPORTUNITY_FIELD_ACCESS'=>'Potential Field Access', + +'LBL_HELPDESK_FIELD_ACCESS'=>'HelpDesk Field Access', + +'LBL_PRODUCT_FIELD_ACCESS'=>'Product Field Access', + +'LBL_NOTE_FIELD_ACCESS'=>'Document Field Access', + +'LBL_EMAIL_FIELD_ACCESS'=>'Email Field Access', + +'LBL_TASK_FIELD_ACCESS'=>'Task Field Access', + +'LBL_EVENT_FIELD_ACCESS'=>'Event Field Access', + +'LBL_DELETE_DEMO_DATA'=>'Delete Demo Data', + +'LBL_DELETE_DEMO_DATA_INFO'=>'- Delete the Demo Data which is created at the time of installation', + + + +'LBL_STUDIO'=>'Studio', + +'LBL_CUSTOM_FIELD_SETTINGS'=>'Custom Field Settings', + +'LBL_CREATE_AND_MANAGE_USER_DEFINED_FIELDS'=>'Manage your company-wide custom fields.', + +'LBL_SELECT_MODULE'=>'Select Module', + +'LBL_SELECT_CF_TEXT'=>'Select Module:', + + + +'LBL_PICKLIST_SETTINGS'=>'Picklist Settings', + +'LBL_EDIT_PICKLIST_VALUES'=>' - Edit values of Picklist fields', + +'LBL_EDIT'=>'Editing', + +'LBL_COMMUNICATION_TEMPLATES'=>'Communication Templates', + +'LBL_CREATE_EMAIL_TEMPLATES'=>'New Email Template', + +'LBL_UPLOAD_MSWORD_TEMPLATES'=>' - Upload MS Word Templates for Mail Merge', + +'LBL_SCHEDULE_EMAIL_NOTIFICATION'=>' - Schedule Email Notifications', + +'LBL_EXPAND_CLOSE_MENU'=>'Expand/Close Menu', + +'LBL_CONFIGURATION'=>'Configuration', + +'LBL_CONFIGURE_MAIL_SERVER'=>' - Configure Outgoing Mail Server', + +'LBL_BACKUP_SERVER_CONFIGURATION'=>'Backup Server Configuration', + +'LBL_BACKUP_SERVER_INFO'=>'Backup Server Information', + +'LBL_BACKUP_SERVER_SETTINGS'=>'Backup Server', + +'LBL_CONFIGURE_BACKUP_SERVER'=>' - Configure Backup Server', + +'LBL_SYSTEM_CONFIGURATION'=>' - System Configuration', + +'LBL_PROXY_SERVER_CONFIGURATION'=>'Proxy Server Configuration', + +'LBL_PROXY_SERVER_INFO'=>'Proxy Server Information', + +'LBL_PROXY_SERVER_SETTINGS'=>'Proxy Server', + +'LBL_CONFIGURE_PROXY_SERVER'=>' - Configure Proxy Server', + +'LBL_PROXY_PORT'=>'Port Number', + + + +//Field Types for custom fields + +'LBL_URL'=>'URL', + +'LBL_CHECK_BOX'=>'Checkbox', + + + +//PickList Settings + +'LBL_STANDARD_FIELDS'=>'Standard Fields', + +'LBL_LEAD_SOURCE'=>'Lead Source', + +'LBL_SALUTATION'=>'Salutation', + +'LBL_LEAD_STATUS'=>'Lead Status', + +'LBL_INDUSTRY'=>'Industry', + +'LBL_RATING'=>'Rating', + +'LBL_ACCOUNT_TYPE'=>'Account Type', + +'LBL_BUSINESS_TYPE'=>'Business Type', + +'LBL_CURRENCY_TYPE'=>'Currency Type', + +'LBL_SALES_STAGE'=>'Sales Stage', + +'LBL_PRIORITY'=>'Priority', + +'LBL_STATUS'=>'Status', + +'LBL_CATEGORY'=>'Ticket Category', + +'LBL_MANUFACTURER'=>'Manufacturer', + +'LBL_PRODUCT_CATEGORY'=>'Product Category', + +'LBL_RSS_CATEGORY'=>'Rss Category', + +//Added for Web based Email client integration (post 4.0.1 release) + +'LBL_ADD_MAIL_ACCOUNT'=>'Add Mail Account', +'LBL_NEW_MAIL_ACCOUNT_TITLE'=>'New Mail Account [Alt+M]', +'LBL_NEW_MAIL_ACCOUNT_KEY'=>'M', +'LBL_NEW_MAIL_ACCOUNT_LABEL'=>'New Mail Account', +'LBL_GENERAL_INFO'=>'General Information', +'LBL_DISPLAY_NAME'=>'Display Name', +'LBL_MAIL_PROTOCOL'=>'Mail Protocol', +'LBL_LIST_PASSWORD'=>'Password', +'LBL_MAIL_SERVER_NAME'=>'Mail Server Name or IP', +'LBL_MAIL_SERVER_SETTINGS'=>'Outgoing Server', +'LBL_INCOME_SERVER_SETTINGS'=>'Incoming Server', +'LBL_TEST_SETTINGS'=>'Test my account setting immediately', +'LBL_TEST_BUTTON_TITLE'=>'Test my account now! [Alt+T]', +'LBL_TEST_BUTTON_KEY'=>'T', +'LBL_TEST_BUTTON_LABEL'=>'Test my account now!', +'LBL_DEFAULT'=>'Default', +'LBL_IMAP2'=>'IMAP2', +'LBL_IMAP4'=>'IMAP4', +'LBL_POP'=>'POP', +'LBL_IMAP'=>'IMAP', +'LBL_MAIL_DISCLAIM'=>'Items marked with * are required
    Items marked with * * are not fully supported', +'LBL_SSL_OPTIONS'=>'SSL Options', +'LBL_TLS'=>'TLS', +'LBL_NO_TLS'=>'No TLS', +'LBL_CERT_VAL'=>'Certificate Validations', +'LBL_INT_MAILER'=>'Use Internal Mailer?', +'LBL_INT_MAILER_USE'=>'Yes', +'LBL_INT_MAILER_NOUSE'=>'No', +'LBL_VAL_SSL_CERT'=>'Validate SSL Cert', +'LBL_DONOT_VAL_SSL_CERT'=>'Do Not Validate SSL Cert', +'LBL_WEB_MAIL_CONFIG'=>'Web Mail Configuration', +'LBL_CONFIGURE_WEB_MAIL'=>' - Configure Web Mail', +'LBL_LIST_MAIL_ACCOUNT'=>' List Mail Account', +'LBL_USAGEUNIT'=>'Usage Unit', +'LBL_GLACCT'=>'GL Account', +'LBL_QUOTE_STAGE'=>'Quote Stage', +'LBL_CARRIER'=>'Carrier', +'LBL_TAXCLASS'=>'Tax Class', +'LBL_MY_DETAILS'=>'My Details', +'LBL_MY_MAIL_SERVER_DET'=>'My Incoming Mail Server Details', +'LBL_EMAIL_ID'=>'Email ID', +'LBL_NAME_EXAMPLE'=>'(example : John Fenner)', +'LBL_EMAIL_EXAMPLE'=>'(example : johnfenner@xyz.com)', +'LBL_REFRESH_TIMEOUT'=>'Refresh Timeout', +'LBL_1_MIN'=>'1 minute', +'LBL_2_MIN'=>'2 minutes', +'LBL_3_MIN'=>'3 minutes', +'LBL_4_MIN'=>'4 minutes', +'LBL_5_MIN'=>'5 minutes', +'LBL_EMAILS_PER_PAGE'=>'Email per Page', + +//Added for Organization Details (4.2 release) +'LBL_ORGANIZATION_NAME'=>'Company Name', +'LBL_ORGANIZATION_ADDRESS'=>'Address', +'LBL_ORGANIZATION_CITY'=>'City', +'LBL_ORGANIZATION_STATE'=>'State', +'LBL_ORGANIZATION_CODE'=>'Postal Code', +'LBL_ORGANIZATION_COUNTRY'=>'Country', +'LBL_ORGANIZATION_PHONE'=>'Phone', +'LBL_ORGANIZATION_FAX'=>'Fax', +'LBL_ORGANIZATION_WEBSITE'=>'Website', +'LBL_ORGANIZATION_DETAILS'=>'Company Information', +'LBL_SPECIFY_COMPANY_DETAILS'=>' - Specify Company Information', +'LBL_ORGANIZATION_LOGO'=>'Company Logo', +'LBL_UPLOAD'=>'Upload', +'LBL_FILENAME'=>'File Name', +'LBL_SETTINGS'=>'Settings', +'LBL_COMPANY_DETAILS'=>'Company Details', + +'LBL_SEVERITY'=>'Severity', +'LBL_FAQ_CATEGORY'=>'FAQ Category', +'LBL_VENDOR_FIELD_ACCESS'=>'Vendor Field Access', +'LBL_PB_FIELD_ACCESS'=>'PriceBook Field Access', +'LBL_QUOTE_FIELD_ACCESS'=>'Quote Field Access', +'LBL_PO_FIELD_ACCESS'=>'Purchase Order Field Access', +'LBL_SO_FIELD_ACCESS'=>'Sales Order Access', +'LBL_INVOICE_FIELD_ACCESS'=>'Invoice Field Access', +'INVENTORYNOTIFICATION'=>'Inventory Notifications', +'LBL_INVENTORY_NOTIFICATIONS'=>' - Edit Inventory Email Notifications', +'INVENTORYTERMSANDCONDITIONS'=>'Inventory : Terms & Conditions',//newly added for Inventory terms and conditions +'LBL_INVENTORY_TERMSANDCONDITIONS'=>' - Edit Terms & Conditions',//newly added +'LBL_TANDC_TEXT'=>'Terms & Conditions Text', +'LBL_INVENTORY_TANDC'=>'Inventory Terms & Conditions', + +'LBL_OTHER_SETTINGS'=>'Other Settings', +'LBL_SCROLL'=>'[Scroll to Top]', + +'LBL_INV_NOT_DESC'=>'The following is the list of notifications that are sent to the product handler regarding the demand and the current quantity in hand during the creation of a Quote, SalesOrder and Invoice.', + +'InvoiceNotification'=>'Product Stock Notification during Invoice Generation', +'InvoiceNotificationDescription'=>'When the product stock level goes below the re-order level, notification will be sent to the product handler', +'Vendor'=>'Vendor', +'PriceBook'=>'PriceBook', +'Quotes'=>'Quote', +'PurchaseOrder'=>'Purchase Order', +'SalesOrder'=>'SalesOrder', +'Invoice'=>'Invoice', + +//For Custom Fields +'LBL_LEAD_MAP_CUSTOM_FIELD'=>'Mapping Lead Custom Fields', +'leadCustomFieldDescription'=>'Map each of your organizations lead custom fields to each of your custom account +,contact, or potential fields. These mappings will be used when you convert leads', +'LBL_MAPPING_INFO'=>'Mapping Information', +'LBL_ACCOUNT_FIELD'=>'Account Custom Field', +'LBL_CONTACT_FIELD'=>'Contact Custom Field', +'LBL_POTENTIAL_FIELD'=>'Potential Custom Field', +'CUSTOMFIELDMAPPING'=>'Custom Field Mapping', +'LBL_FIELD_MAPPING'=>'Field Mapping', +'LBL_LEAD_FIELD'=>'Lead Custom Field', +//After 4.2 GA +'LBL_TEXT_AREA'=>'Text Area', +//for Edit ordering the blocks +'NOTESCUSTOMFIELDS'=>'Documents Custom Fields', + +//Added fields after 4.2 ptach 2 +'LBL_ASSIGN_MODULE_OWNERS'=>'Assign Module Owners', +'LBL_MODULE_OWNERS'=>'Module Owners', +'LBL_ASSIGN_MODULE_OWNERS_INFO'=>' - Assign Owners for each modules', +'LBL_MODULE'=>'CRM Module', +'LBL_OWNER'=>'Assigned Owner', +'LBL_MIGRATION'=>'Migration Wizard', +'LBL_MIGRATION_INFO'=>'Migrate your existing vtiger CRM data to latest version', + +//Added for 5 GA - Description of Settings UI + +'LBL_USER_DESCRIPTION'=>'Manage users who can access vtiger CRM', +'LBL_ROLE_DESCRIPTION'=>'Set up hierarchy of roles and assign to the users', +'LBL_PROFILE_DESCRIPTION'=>'Manage user-specific modules access to different Roles', +'LBL_GROUP_DESCRIPTION'=>'Manage different types of teams based on roles, users, and profiles', +'LBL_SHARING_ACCESS_DESCRIPTION'=>'Manage module sharing rules & custom sharing rules', +'LBL_SHARING_FIELDS_DESCRIPTION'=>'Define global field-level access in each module', +'LBL_MODULE_OWNERS_DESCRIPTION'=>'Assign Customer Support owners to CRM module', +'LBL_ANNOUNCEMENT_DESCRIPTION'=>'Manage company wide announcements', +'LBL_CUSTOM_FIELDS_DESCRIPTION'=>'Manage different types of user-defined fields', +'LBL_PICKLIST_DESCRIPTION'=>'Customize Picklist values in each module', +'LBL_EMAIL_TEMPLATE_DESCRIPTION'=>'Manage templates for E-Mail module', +'LBL_MAIL_MERGE_DESCRIPTION'=>'Manage templates for Mail Merging', +'LBL_NOTIF_SCHED_DESCRIPTION'=>'Manage Notifications that will alert in case of important actions', +'LBL_INV_NOTIF_DESCRIPTION'=>'Change Settings of Inventory related Notifications', +'LBL_INV_TANDC_DESCRIPTION'=>'Specify Terms and Conditions for quotes, orders, and invoices', +'LBL_COMPANY_DESCRIPTION'=>'Specify business address of company', +'LBL_MAIL_SERVER_DESCRIPTION'=>'Configure Outgoing Mail Server details', +'LBL_BACKUP_SERVER_DESCRIPTION'=>'Specify database backup server details', +'LBL_CURRENCY_DESCRIPTION'=>'Manage international currencies and exchange rates', +'LBL_TAX_DESCRIPTION'=>'Manage taxes and the corresponding tax rates', +'LBL_SYSTEM_DESCRIPTION'=>'View vtiger CRM Server details', +'LBL_PROXY_DESCRIPTION'=>'Configure proxies to access RSS feeds through Internet', +'LBL_AUDIT_DESCRIPTION'=>'Display data opertions performed by users', +'LBL_TAX_DESC'=>'Manage different types of tax rates for taxes, such as Sales Tax, VAT etc.,', +'LBL_COMPANY_DESC'=>'Specify business address of your company', +'LBL_SELECT_LOGO'=>'Select new logo:', +'LBL_INVEN_TANDC_DESC'=>'Specify text for the Terms & Conditions section of Quotes, Orders, and Invoices modules', +'LBL_MAIL_SERVER_DESC'=>'Configure your Outgoing Mail Server details', +'LBL_BACKUP_SERVER_DESC'=>'Manage your Backup Server', +'LBL_MODULES_AND_OWNERS'=>'Modules & Owners', +'LBL_GROUP_DESC'=>'Manage different types of user groups within your organization', +'LBL_MAIL_MERGE_DESC'=>'Manage Mail Merge templates used in CRM modules', + + +//Added fields after 5.0 Alpha +'LBL_REQUIRE_SMTP_AUTHENTICATION'=>'Require SMTP Authentication?', +'LBL_ANNOUNCEMENT'=>'Announcements', +'LBL_SETTING_ANNOUNCEMENT'=>'Announcement', +'LBL_ANNOUNCE_TEXT'=>'Announcement Text', +'LBL_UPDATE_BUTTON'=>'Update', +'LBL_ANNOUNCEMENT_INFO'=>'Type the announcement text below, and click the Update button.', +'LBL_ANNOUNCEMENT_DESC'=>'Change the text that appears in the announcement display on top of each page', +'LBL_EMAIL_CONTENTS'=>'Email Contents', +'LBL_SUBJECT'=>'Subject', +'LBL_MESSAGE'=>'Message', +'LBL_PICKLIST_EDITOR'=>'Picklist Editor', +'LBL_PICKLIST_AVAIL'=>'Picklists Available in', +'LBL_PICKLIST_AVAILINFO1'=>'The picklists available in', +'LBL_PICKLIST_AVAILINFO2'=>'are shown below. Click Edit to modify the contents of the list.', +'LBL_EDIT_PICKLIST'=>'Edit Pick List', +'LBL_PICKLIST_SAVEINFO'=>'Type the entries one - by - one below and click the Save button to save the list.', +'LBL_SELECT_CRM_MODULE'=>'Select CRM Module', +'LBL_TAX_SETTINGS'=>'Tax Calculations', +'LBL_INVENTORY_TAX_CONFIG'=>'Inventory Tax Configuration', +'LBL_CUSTOM_MAPP_INFO'=>'Only in Leads module you can map the fields with Accounts, Contacts, and Potentials.', +'LBL_MAPPING_OTHER_MODULES'=>'Mapping with other Modules', +'LBL_CUSTOM_FILED_IN'=>'Custom Fields in ', +'LBL_ROLE_HIERARCHY_TREE'=>'Roles & Hierarchy Tree', +'LBL_EDIT_FIELD_MAPPING'=>'Editing Field Mapping', +'LBL_LOGIN_HISTORY_DETAILS'=>'User Login History', +'LBL_LOGIN_HISTORY_DESCRIPTION'=>'Display login history of users', +'LBL_NON_EDITABLE_PICKLIST_ENTRIES'=>'Non Editable Picklist Entries', + +//Added for Tax settings +'LBL_PRODUCT_TAX_SETTINGS'=>'Product & Service Taxes', +'LBL_SHIPPING_HANDLING_TAX_SETTINGS'=>'Shipping & Handling Taxes', +'LBL_PROXY_SERVER_DESC'=>'Configure proxies to access RSS feeds through Internet', + +'LBL_NEW_CURRENCTY'=>'New Currency', +'LBL_BASE_CURRENCY'=>'Base Currency - ', +'LBL_DELETE_CURRENCY'=>'Delete Currency', + +//Added for singlepane view in modules + +'LBL_DEFAULT_DETAIL_VIEW'=>'Default Detail View', +'LBL_DEFAULT_MODULE_VIEW'=>'Default Module View', +'LBL_DEFAULT_MODULE_VIEW_DESC'=>'Set Default Detail View for All Modules', +'LBL_ENABLE_SINGLEPANE_VIEW'=>'Enable Singlepane View', + +'LBL_CLEAR_DATA'=>'Clear Data', +'LBL_ENABLE'=>'Enable', +'LBL_FAQ_FIELD_ACCESS'=>'Faq Field Access', +'LBL_ADD_TAX_BUTTON'=>'Add Tax', +'LBL_NO_TAXES_AVAILABLE'=>'No taxes available', +'LBL_PLEASE'=>'Please', +//Added while moving role file from User to Setting Module +'LBL_ROLES'=>'Roles', +'LBL_CREATE_NEW_ROLE'=>'Create New Role', +'LBL_PROPERTIES'=>'Properties of', +'LBL_NEW_ROLE'=>'New Role', +'LBL_ROLE_NAME'=>'Role Name', +'LBL_REPORTS_TO'=>'Reports to', +'LBL_PROFILE_M'=>'Profile', +'LBL_PROFILES_AVLBL'=>'Profiles Available', +'LBL_ASSIGN_PROFILES'=>'Assigned Profiles', +'LBL_MEMBER'=>'Members', +'LBL_DELETE_ROLE'=>'Delete Role', +'LBL_ROLE_TO_BE_DELETED'=>'Role to be Deleted', +'LBL_TRANSFER_USER_ROLE'=>'Transfer Users to Role', +'LBL_ASSOCIATED_PROFILES'=>'Associated Profiles :', +'LBL_ASSOCIATED_USERS'=>'Associated Users :', +//Added while moving email templates from Users to Settings +'LBL_EMAIL_TEMPLATES'=>'Email Templates', +'LBL_EMAIL_TEMPLATE_DESC'=>'Manage email templates used for Campaigns and Mass mailing', +'LBL_LIST_SELECT'=>'Select', +'LBL_EMAIL_TEMPLATE'=>'Email Template', +'LBL_TEMPLATE_TOOLS'=>'Tools', +'LBL_NEW_TEMPLATE' =>'New Template', +'LBL_FOLDER'=>'Folder', +'LBL_NAME'=>'Name', +'LBL_PERSONAL'=>'Personal', +'LBL_PUBLIC'=>'Public', +'LBL_ACCOUNT_FIELDS'=>'Account Fields', +'LBL_CONTACT_FIELDS'=>'Contact Fields', +'LBL_LEAD_FIELDS'=>'Lead Fields', +'LBL_USER_FIELDS'=>'User Fields', +'LNK_SAMPLE_EMAIL'=>'View Sample Email', +//Added while moving Mail Merge templates from Users to Settings +'LBL_TEMPLATE_FILE'=>'Template File', +'LBL_MODULENAMES'=>'Module', +'LBL_DOWNLOAD'=>'Download', +'LBL_ADD_TEMPLATE'=>'Add Template', +'LBL_WORD_TEMPLATES'=>'Mail Merge Templates', +//Added while moving Notification Schedulers from Users to Settings +'LBL_TASK_NOTIFICATION'=>'Delayed Task Notification', +'LBL_BIG_DEAL'=>'Big Deal Notification', +'LBL_PENDING_TICKETS'=>'Pending Tickets Notification', +'LBL_MANY_TICKETS'=>'Too many tickets Notification', +'LBL_START_NOTIFICATION'=>'Support Start Notification', +'LBL_ACTIVITY_NOTIFICATION'=>'Event Reminder Notification', + +'LBL_TASK_NOTIFICATION_DESCRITPION'=>'Notify when a task is delayed beyond 24 hrs', +'LBL_BIG_DEAL_DESCRIPTION'=>'Notify on completion of big deal', +'LBL_TICKETS_DESCRIPTION'=>'Notify for getting attention to status of tickets which are pending', +'LBL_MANY_TICKETS_DESCRIPTION'=>'Notify when a particular entity is allocated too many tickets, might reflect Service Level commitments', +'LBL_START_DESCRIPTION'=>'Notifiy stating the start of support/service', +'LBL_ACTIVITY_REMINDER_DESCRIPTION'=>'Notify before an event to occur based on the reminder set', +//Added while moving Inventory Notifications from Users to Settings +'QuoteNotificationDescription'=>'During quote generation if the product stock in warehouse is lesser than the quantity mentioned in quote then this notification will be sent to the product handler', +'SalesOrderNotificationDescription'=>'During sales order generation if the product stock in warehouse is lesser than the quantity mentioned in sales order then this notification will be sent to the product handler', +'Tools'=>'Tools', +'QuoteNotification'=>'Product Stock Notification during Quote Generation', +'SalesOrderNotification'=>'Product Stock Notification during Sales Order Generation', +'LBL_NOTE_DO_NOT_REMOVE_INFO'=>'Note: Donot remove or alter the values within { }', + +//Added while moving Profile file from User to Setting Module +'LBL_TOTAL'=>'Total :', +'LBL_NEW_PROFILE'=>'New Profile', +'LBL_LIST_NO'=>'#', +'LBL_NEW_PROFILE_NAME'=>'Profile Name', +'LBL_LIST_TOOLS'=>'Tools', +'LBL_PROFILE_MESG'=>'Viewing access privileges for', +'LBL_PROFILE_PRIVILEGES'=>'Profile Privileges', +'LBL_DEFINE_PRIV_FOR'=>' Define Privileges for ', +'LBL_USE_OPTION_TO_SET_PRIV'=>'Use the options below to set privileges', +'LBL_SUPER_USER_PRIV'=>'Global Privileges', +'LBL_SET_PRIV_FOR_EACH_MODULE'=>'Set Privileges for each Module ', +'LBL_FIELDS_AND_TOOLS_SETTINGS'=>'Fields & Tools Settings', +'LBL_VIEW_ALL'=>'View all', +'LBL_EDIT_ALL'=>'Edit all', +'LBL_ALLOW'=>'Allows', +'LBL_MESG_VIEW'=>'to view all information / modules of vtiger CRM', +'LBL_MESG_EDIT'=>'to edit all information / modules of vtiger CRM', +'LBL_TAB_MESG_OPTION'=>'modules to be shown', +'LBL_CREATE_EDIT'=>'Create/Edit', +'LBL_VIEW'=>'View', +'LBL_MANDATORY_MSG'=>'Mandatory Fields', +'LBL_DISABLE_FIELD_MSG'=>'Fields Disabled from Global Field Access Settings', +'LBL_DELETE'=>'Delete', + +'LBL_STEP_2_2'=>'Step 2 of 2', +'LBL_FINISH_BUTTON'=>'Finish', + +//Added while moving Groups file from User to Setting Module +'LBL_NEW_GROUP'=>'New Group', +'LBL_GROUPS'=>'Groups', +'LBL_GROUP_NAME'=>'Group Name', +'LBL_ROLES_SUBORDINATES'=>'Roles and Subordinates', +'LBL_MEMBER_AVLBL'=>'Available Entities & Members', +'LBL_MEMBER_SELECTED'=>'Selected Members', +'LBL_ENTITY'=>'Entity', +'LBL_OF'=>'of', +'LBL_CREATE_NEW_GROUP'=>'Create New Group', +'LBL_ADD_GROUP_BUTTON'=>'Add Group', +'LBL_GROUP_MESG1'=>'Groups are a flexible way to assign access rights, when complex access rights has to be defined. You can combine multiple entities like Roles, Users, profiles etc into a single group.', +'LBL_GROUP_MESG2'=>'To add, select the Entity members from left and click the ">>" button.', +'LBL_GROUP_MESG3'=>'To remove, select the group members from the right and click the "<<" button.', + +//Sharing Privileges +'LBL_GLOBAL_ACCESS_PRIVILEGES'=>'Organization-level Sharing Rules', +'LBL_RECALCULATE_BUTTON'=>'Recalculate', +'LBL_CHANGE'=>'Change', +'LBL_PRIVILEGES'=>'Privileges', +'LBL_CUSTOM_ACCESS_PRIVILEGES'=>'Custom Sharing Rules', +'LBL_ADD_PRIVILEGES_BUTTON'=>'Add Privileges', +'LBL_RULE_NO'=>'Rule No.', +'LBL_CAN_BE_ACCESSED'=>'can be accessed by', +'LBL_CUSTOM_ACCESS_MESG'=>'No Custom Access Rules defined .', +'LNK_CLICK_HERE'=>'Click here', +'LBL_CREATE_RULE_MESG'=>'to create a new Rule', +'LBL_RECALC_MSG'=>'Are you sure, you wish to Recalculate Sharing Access?', +'LBL_YES'=>'Yes', +'LBL_NO'=>'No', +'LBL_IN_PERMISSION'=>'in the permission', +'LBL_RELATED_MODULE_RIGHTS'=>'Related Module Rights', +'LBL_USR_CAN_ACCESS'=>'Users can ', +'LBL_USR_OTHERS'=>' other users ', +'LBL_USR_CANNOT_ACCESS'=>'Users cannot access other users ', + +'LBL_ORG_SHARING_PRIVILEGES'=>'Organisation Sharing Privileges', +'LBL_EDIT_PERMISSIONS'=>'Edit Permissions', +'LBL_SAVE_PERMISSIONS'=>'Save Permissions', +'LBL_READ_ONLY'=>'Public: Read Only', +'LBL_EDIT_CREATE_ONLY'=>'Public: Read, Create/Edit', +'LBL_READ_CREATE_EDIT_DEL'=>'Public: Read, Create/Edit, Delete', +'LBL_PRIVATE'=>'Private', + +'Public: Read Only'=>'Public: Read Only', +'Public: Read, Create/Edit'=>'Public: Read, Create/Edit', +'Public: Read, Create/Edit, Delete'=>'Public: Read, Create/Edit, Delete', +'Private'=>'Private', +'Hide Details'=>'Hide Details', +'Hide Details and Add Events'=>'Hide Details and Add Events', +'Show Details'=>'Show Details', +'Show Details and Add Events'=>'Show Details and Add Events', + +//Added for User Login History While moving from User to Settings +'LBL_LOGIN_HISTORY'=>'Login History', +//Sharing Access module moved to Setting +'Read/Write'=>'Read/Write', +'Read Only '=>'Read Only ', +'LBL_GROUP'=>'Group', +'LBL_ACCESS_RIGHTS_FOR_MODULES'=>'Access rights for relative modules', +'LBL_ADD_RULE'=>'Add Rule', +'LBL_ADD_CUSTOM_RULE'=>'Add Custom Privilege Rule', +'LBL_RULE_CONSTRUCTION'=>'Rule Construction Display', +'LBL_STEP'=>'Step', +'LBL_SELECT_ENTITY'=>'Select an entity below', +'LBL_CAN_BE_ACCESSED_BY'=>'Can be accessed by', +'LBL_PERMISSIONS'=>'Permissions', +'LBL_DOC_MSWORD'=>'File has to be a Document of type doc/msword', +'LBL_NODOC'=>'No doc File in this directory.Please try again!', + +//Added for error messages on Company Info. +'LOGO_ERROR'=>'Logo has to be an Image of type jpeg/png', +'Error_Message'=>'Error Message', +'Invalid_file'=>'Invalid file OR', +'File_has_no_data'=>'File has no data', +'Sorry'=>'Sorry', +'uploaded_file_exceeds_maximum_limit'=>'the uploaded file exceeds the maximum vtiger_filesize limit', +'try_file_smaller'=>'Please try a file smaller than 800000 bytes', +'Problems_in_upload'=>'Problems in file upload', +'Please_try_again'=>'Please try again!', +//5.0.3 fixes +'LBL_TESTMAILSTATUS'=>'Test Mail Status : ', +'LBL_CHECK_ASSIGNEDTO_MAILID'=>'Please check the assigned-to emailid', +'LBL_MAILSENDERROR'=>'Mail could not be sent to the admin user. Please check the admin emailid/Server settings', +'LBL_RECORD_NOEXIST'=>'Record not present', +'LBL_ENTER_PROFILE'=>'Enter Profile Name', +'LBL_ENABLE'=>'Enable', +'LBL_DISABLE'=>'Disable', +'LBL_PROXY'=>'proxy', +'LBL_FIELDS_TO_BE_SHOWN'=>'Fields to be shown', +//Added for alerts +'SPECIFY_FILE_TO_MERGE' => 'Please Specify a File to Merge', +'FILESIZE_EXCEEDS_INFO_CONFIG_INC' => 'Sorry, the uploaded file exceeds the maximum file size limit in config.inc.php. Please try a smaller file', +'FILESIZE_EXCEEDS_INFO_PHP_INI' => 'Sorry, the uploaded file exceeds the maximum file size limit in php.ini. Please try a smaller file', +'PROBLEMS_IN_FILEUPLOAD' => 'Problems in file upload. Please try again!', + +//Added fields for Invoice Number labels +'LBL_CUSTOMIZE_INVOICE_NUMBER'=>'Customize Invoice Number', +'LBL_CUSTOMIZE_INVOICE_NUMBER_DESCRIPTION'=>'Invoice Number Customization', +'LBL_CUSTOM_INVOICE_NUMBER_VIEW'=>'Invoice Number Customization', +'LBL_CUSTOMINVOICE_STRING'=>'Custom Invoice String', +'LBL_CUSTOMINVOICE_NUMBER'=>'Custom Invoice Number', +'LBL_INVOICE_NUMBER_PREVIEW'=>'Preview', +'LBL_INVOICE_NUMBER_BUTTON'=>'Update Invoice Number', +'LBL_PROXY_AUTHENTICATION_REQUIRED'=>'Proxy Authentication Required', +'LBL_ENABLE_FTP' => 'You must have FTP support enabled in php', + +//Added for Role Labels +'LBL_ADD_ROLE'=>'Add Role', +'LBL_EDIT_ROLE'=>'Edit Role', +'LBL_MOVE_ROLE'=>'Move Role', +'LBL_BACKUP_DESC'=>' The CRM system allows you to make a backup of the database to your FTP server. The CRM will take backup of all data whenever an admin user logs out. Make sure you have enough disk space available on your FTP server. The created backup file will be in the following format: "backup_date_time.sql".', + +// Added/Updated for vtiger CRM 5.0.4 +'LBL_SUPPORT_NOTICIATION'=>'Support End Notification before a week', +'LBL_SUPPORT_NOTICIATION_MONTH'=>'Support End Notification before a month' , +'LBL_SUPPORT_DESCRIPTION'=>'Notify before one week when support is about to end', +'LBL_SUPPORT_DESCRIPTION_MONTH'=>'Notify before one month when support is about to end', +'LBL_SELECT_ROLE'=>'Select Role', +'LBL_TEMPLATE'=>'Template', +'LBL_SELECT_EMAIL_TEMPLATE_FOR'=>'Select the Email Template for', + +'ERR_CUSTOM_FIELD_WITH_NAME'=>'Custom Field with the Name ', +'ERR_ALREADY_EXISTS'=>' already exists.', +'ERR_SPECIFY_DIFFERENT_LABEL'=>'Please specify a different Label', +'LBL_TOOLS_TO_BE_SHOWN'=>'Tools to be shown', +'LBL_PICKLIST_GLOBAL_CHANGE'=>'Global Change', +'LBL_PICKLIST_TRANSFER'=>'Transfering the values Of ', +'LBL_REPLACE_VALUE_WITH'=>'Replace value with ', +'LBL_EDIT_CUSTOM_RULE'=>'Edit Custom Privilege Rule', + +/*for global add/delete in picklist*/ +'DELETE_PICKLIST_VALUES'=>'Delete PickList Values', +'EDIT_PICKLIST_VALUE'=>'Edit PickList Value', +'ADD_PICKLIST_VALUES'=>'Add PickList Values', +'LBL_PICKLIST_ADDINFO'=>'Type the new entries one-by-one below', +'LBL_SELECT_ROLES'=> 'Select the Roles to which entries have to be added', +'LBL_EXISTING_PICKLIST_VALUES'=>'Existing Picklist Values', +'LBL_SELECT_PICKLIST'=>'Select picklist', + +// Added after 5.0.4 GA + +'LBL_GENERAL_FIELDS'=>'General Fields', + +'LBL_CANCEL_BUTTON'=>'Cancel', + +//Added fields for Inventory Number labels +'LBL_CUSTOMIZE_INVENTORY_NUMBER'=>'Customize Inventory Sequence', +'LBL_CUSTOMIZE_INVENTORY_NUMBER_DESCRIPTION'=>'Inventory Sequence Customization', +'LBL_CUSTOM_QUOTE_NUMBER_VIEW'=>'Quote Number Customization', +'LBL_CUSTOMQUOTE_STRING'=>'Custom Quote String', +'LBL_CUSTOMQUOTE_NUMBER'=>'Custom Quote Number', +'LBL_QUOTE_NUMBER_PREVIEW'=>'Preview', +'LBL_QUOTE_NUMBER_BUTTON'=>'Update Quote Number', +'LBL_CUSTOM_SO_NUMBER_VIEW'=>'SalesOrder Number Customization', +'LBL_CUSTOMSO_STRING'=>'Custom SalesOrder String', +'LBL_CUSTOMSO_NUMBER'=>'Custom SalesOrder Number', +'LBL_SO_NUMBER_PREVIEW'=>'Preview', +'LBL_SO_NUMBER_BUTTON'=>'Update SalesOrder Number', +'LBL_CUSTOM_PO_NUMBER_VIEW'=>'PurchaseOrder Number Customization', +'LBL_CUSTOMPO_STRING'=>'Custom PurchaseOrder String', +'LBL_CUSTOMPO_NUMBER'=>'Custom PurchaseOrder Number', +'LBL_PO_NUMBER_PREVIEW'=>'Preview', +'LBL_PO_NUMBER_BUTTON'=>'Update PurchaseOrder Number', + +// Added after 5.0.4 GA + +// Added for Multi-Currency Support +'LBL_TRANSFER_CURRENCY'=>'Transfer Currency', +'LBL_CURRENT_CURRENCY'=>'Current Currency', + +//Added for new backup labels +'LBL_LOCAL'=>'Local', +'LBL_BACKUP'=>'Backup', +'LBL_BACKUP_LOCATION'=>'Backup Location', + +'LBL_LAYOUT_EDITOR'=>'Layout Editor', +'LBL_LAYOUT_EDITOR_DESCRIPTION'=>'Designing and Modifying the layout in each of the modules', +'LBL_Show'=>'Show', +'LBL_Hide'=>'Hide', + +// vtlib customization: Language Stings +'VTLIB_LBL_MODULE_MANAGER'=>'Module Manager', +'VTLIB_LBL_MODULE_MANAGER_DESCRIPTION'=>'Manage module behavior inside vtiger CRM', +'VTLIB_LBL_MODULE_MANAGER_CUSTOMMOD'=>'Custom Modules', +'VTLIB_LBL_MODULE_MANAGER_STANDARDMOD'=>'Standard Modules', +'VTLIB_LBL_MODULE_MANAGER_NOMODULES'=>'No custom modules found! Create one or Import New ...', + +// vtmailscanner START +'LBL_MAIL_SCANNER'=>'Mail Scanner', +'LBL_MAIL_SCANNER_DESCRIPTION'=>'Configure mailbox for scanning', +'LBL_SCAN_NOW'=>'Scan Now', +'LBL_RULE'=>'Rule', +'LBL_SETUP'=>'Setup', +'LBL_CONFIGURE'=>'Configure', +'LBL_MAILBOX' => 'Mailbox', +'LBL_INFORMATION' => 'Information', +'LBL_SCANNER' => 'Scanner', +'LBL_SERVER' => 'Server', +'LBL_PROTOCOL'=> 'Protocol', +'LBL_PASSWORD'=> 'Password', +'LBL_TYPE' => 'Type', +'LBL_SSL' => 'SSL', +'LBL_METHOD'=> 'Method', +'LBL_VAL_SSL_CERT'=>'Validate SSL Certificate', +'LBL_DONOT_VAL_SSL_CERT'=>'Do Not Validate SSL Certificate', +'LBL_STATUS'=>'Status', +'LBL_ENABLE'=>'Enable', +'LBL_DISABLE'=>'Disable', +'LBL_CONNECT'=>'Connect', +'LBL_URL_CAPS'=>'URL', +'LBL_ENABLED'=>'Enabled', +'LBL_DISABLED'=>'Disabled', +'LBL_RULES'=>'Rules', +'LBL_FOR'=>'For', + +'LBL_FROM'=>'From', +'LBL_TO'=>'To', + +'LBL_ACTION'=>'Action', +'LBL_CREATE'=>'Create', +'LBL_TICKET'=>'Ticket', +'LBL_ADD'=>'Add', + +'LBL_CONTACT'=>'Contact', +'LBL_ACCOUNT'=>'Account', + +'LBL_FROM_CAPS'=>'FROM', +'LBL_TO_CAPS'=>'TO', +'LBL_TO_SMALL'=>'to', + +'LBL_CONTAINS'=>'Contains', +'LBL_EQUALS'=>'Equals', + +'LBL_BEGINS'=>'Begins', + +'LBL_REGEX'=>'Regex', +'LBL_ENDS'=>'Ends', +'LBL_BODY'=>'Body', + +'LBL_NOT'=>'Not', + +'LBL_ALL' => 'All', +'LBL_ANY'=>'Any', +'LBL_CONDITION'=>'Condition', +'LBL_ACTION'=>'Action', +'LBL_MOVE'=>'Move', +'LBL_UP'=>'Up', +'LBL_DOWN'=>'Down', +'LBL_PRIORITY'=>'Priority', +'LBL_UPDATE'=>'Update', +'LBL_SELECT'=>'Select', +'LBL_FOLDERS'=>'Folders', +'LBL_UNSELECT'=>'Unselect', +'LBL_MATCH'=>'Match', +'LBL_SCANNING'=>'Scanning', +'LBL_LOOKFOR'=>'Look for', +'LBL_UNREAD'=>'Unread', +'LBL_READ'=>'Read', +'LBL_AFTER_SCAN'=>'After scan', +'LBL_MESSAGES_FROM_LASTSCAN'=>'Messages from lastscan', +'LBL_MARK_MESSAGE_AS'=>'Mark message as', + +//Added for the workflow module +'LBL_LIST_WORKFLOWS'=>'Workflows', +'LBL_LIST_WORKFLOWS_DESCRIPTION' => 'Create and edit workflows for vtiger', +'LBL_TASK_TITLE'=>'Task Title', +'LBL_PARENT_WORKFLOW'=>'Parent Workflow', +'MSG_EXECUTE_TASK_DELAY'=>'Execute the task after some delay', +'LBL_AFTER'=>'After', +'LBL_BEFORE'=>'Before', +'LBL_TASK_OPERATIONS'=>'Task Operations', +'LBL_CREATE_TASK'=>'Create Task', +'LBL_CREATE_TASK_OF_TYPE'=>'Create a new task of type', +'LBL_SUMMARY'=>'Summary', +'LBL_WHEN_TO_RUN_WORKFLOW'=>'When to run the workflow', +'LBL_ONLY_ON_FIRST_SAVE'=>'Only on the first save', +'LBL_UNTIL_FIRST_TIME_CONDITION_TRUE'=>'Until the first time the condition is true', +'LBL_EVERYTIME_RECORD_SAVED'=>'Every time the the record is saved', +'LBL_CONDITIONS'=>'Conditions', +'LBL_NEW_CONDITION_BUTTON_LABEL'=>'New Condition', +'LBL_TASKS'=>'Tasks', +'LBL_NEW_TASK_BUTTON_LABEL'=>'New Task', +'LBL_TASK'=>'Task', +// END +//Added for vantage customization (Mandatory fields) -- Pavani +'LBL_MANDATORY_FIELDS'=>'Mandatory Fields', +'LBL_MANDATORY_FIELDS_DESCRIPTION'=>'Manage mandatory fields of all modules', +// Module Sequence Numbering +'LBL_CUSTOMIZE_MODENT_NUMBER'=>'Customize Record Numbering', +'LBL_CUSTOMIZE_MODENT_NUMBER_DESCRIPTION'=>'Module Entity Number customization', +// END + +//added for softphone integration +'LBL_SOFTPHONE_SERVER_SETTINGS'=>'SoftPhone Server Settings', +'LBL_SOFTPHONE_SERVER_SETTINGS_DESCRIPTION'=>'Configure your softphone here', +'ASTERISK_SERVER_IP'=>'Asterisk server IP ', +'ASTERISK_PORT'=>'Asterisk server port', +'ASTERISK_USERNAME'=>'Asterisk username', +'ASTERISK_PASSWORD'=>'Asterisk password', +'ASTERISK_SERVER_IP_TITLE'=>'The URL of the asterisk server', +'ASTERISK_PORT_TITLE'=>'The port where asterisk call manager API can connect to Asterisk (default 5038)', +'ASTERISK_USERNAME_TITLE'=>'The asterisk username (generally the admin username)', +'ASTERISK_PASSWORD_TITLE'=>'Password for the asterisk user', +'LBL_CANCEL_BUTTON'=>'Cancel', +'ASTERISK_VERSION' => 'Asterisk Version', +'ASTERISK_VERSION_TITLE'=>'Select your Asterisk version here; leave it as 1.4 if not sure', +'ASTERISK_CONFIGURATION'=>'Asterisk Configuration', +//softphone integration ends +'LBL_SELECT_FIELD_TO_MOVE' => 'Select Fields to move', +'VTLIB_LBL_SELECT_PACKAGE_FILE'=>'Select the Package File', +'VTLIB_LBL_FILE_LOCATION'=>'File location:', +'VTLIB_LBL_PACKAGE_FILE_HELP'=>'vtiger module is packaged as a zip file.', +'VTLIB_LBL_IMPORT_FAILURE'=>'Import Failure', +'VTLIB_LBL_INVALID_FILE'=>'Invalid file', +'VTLIB_LBL_INVALID_IMPORT_TRY_AGAIN'=>'provided for module import! Try Again.', +'VTLIB_LBL_UNABLE_TO_UPLOAD'=>'Unable to upload', +'VTLIB_LBL_UNABLE_TO_UPLOAD2'=>'the package on the server! Try Again.', +'VTLIB_LBL_VERIFY_IMPORT_DETAILS'=>'Verify Import Details', +'VTLIB_LBL_MODULE_NAME'=>'Module Name', +'VTLIB_LBL_MODULE_DIR'=>'Module Directory', +'VTLIB_LBL_REQ_VTIGER_VERSION'=>'Req. vtiger version', +'VTLIB_LBL_LICENSE'=>'License', +'VTLIB_LBL_LICENSE_ACCEPT_AGREEMENT'=>'I accept the license agreement.', +'VTLIB_LBL_PROCEED_WITH_IMPORT'=>'Do you want to proceed with the import?', +'VTLIB_LBL_IMPORTING_MODULE_START'=>'Importing Module ...', +'VTLIB_LBL_WARNING'=>'Warning', +'VTLIB_LBL_NOT_WRITEABLE'=>'not writeable', +'VTLIB_LBL_PACKAGE_VERSION'=>'Version', + +'LBL_UPGRADE'=>'Upgrade', +'VTLIB_LBL_UPDATE_FAILURE'=>'Upgrade Failure', +'VTLIB_LBL_MODULENAME_MISMATCH'=>'Module name mistmach', +'VTLIB_LBL_TRY_AGAIN'=>'Try Again', +'VTLIB_LBL_VERIFY_UPDATE_DETAILS'=>'Verify Upgrade Details', +'VTLIB_LBL_PROCEED_WITH_UPDATE'=>'Do you want to proceed with the upgrade?', +'VTLIB_LBL_UPDAING_MODULE_START'=>'Updating module...', +'VTLIB_LBL_EXISTS'=>'Exists', +'VTLIB_LBL_NOT_PRESENT'=>'Not Present', +'VTLIB_LBL_INST_VERSION'=>'Installed Version', +'VTLIB_LBL_MATCHES_PACKAGE_VERSION'=>'matches Package Version', +'VTLIB_LBL_CANNOT_UPGRADE'=>'Cannot updgrade!', +// END + +//User group fixes +'LBL_USERNAME_EXIST' => 'A User in the specified name Already Exists!', +'LBL_GROUPNAME_EXIST' => 'A Group in the specified name Already Exists!', +'LBL_ROLENAME_EXIST' => 'Role name already exists', + +//layout editor +'LBL_MOVE_FIELDS' => 'Move Fields', +'NO_HIDDEN_FIELDS' => 'No Hidden Fields', +'LBL_RELATED_LIST' => 'Related List', +'LBL_ADD_BLOCK' => 'Add Block', +'HIDDEN_FIELDS' => 'Hidden Fields', +'DOWN'=> 'Down', +'UP'=> 'Up', +'RIGHT' => 'Right', +'LEFT' => 'Left', +'LBL_EDIT_PROPERTIES' => 'Edit Properties', +'LBL_MANDATORY_FIELD' => 'Mandatory Field', +'LBL_ACTIVE' => 'Active', +'LBL_QUICK_CREATE' => 'Quick Create', +'LBL_MASS_EDIT' => 'Mass Edit', +'LBL_BLOCK_NAME' => 'Block name', +'AFTER' => 'After', +'ADD_BLOCK' => 'Add Block', +'ARRANGE_RELATEDLIST' => 'Arrange RelatedList', +'CUSTOMFIELD_MAPPING' => 'CustomField Mapping', +'LBL_MAPPED_FIELDS' => 'Mapped Fields', +'LEADS_CUSTOM_FIELD_MAPPING_DESCRIPTION' => 'Map Your Leads Customfields with Accounts,Contacts and Potentials', +'LEADS_CUSTOM_FIELD_MAPPING'=> 'Leads CustomField Mapping', +'LBL_CALENDER_CUSTOMFIELDS' => 'Calendar Custom Fields', +'LBL_CALENDER_CUSTOMFIELDS_DESCRIPTION' => 'You can Create Custom Fields for Calendar', +'LBL_GO_BACK'=>'Go Back', + +//Added fix for: 5418 +'LBL_USE_PREFIX' => 'Use Prefix', +'LBL_START_SEQ' => 'Start Sequence', +'LBL_MODULE_NUMBERING' => 'Module Numbering', +'LBL_FAILED' => 'Failed', +'LBL_DONE' => 'Done', +'LBL_IN_USE' => 'IN USE', +'LBL_MODULE_NUMBERING_FIX_MISSING' => 'Update Missing Record Sequence Now', + +//Added for: 5473 +'LBL_SHARING_ACCESS_HELPNOTE' => 'After making modifications, press Recalculate button to apply the changes.', + +//for customer portal extension module +'PORTAL_EXTENSION_DESCRIPTION'=>'Allows you to Configure Customer Portal Plugin', +'LBL_CUSTOMER_PORTAL'=> 'Customer Portal', + +//FieldFormulas +'LBL_FIELDFORMULAS' => 'Field Formulas', +'LBL_FIELDFORMULAS_DESCRIPTION' => 'Add custom equations to custom fields', +); +?> diff --git a/oss/vtiger/trunk/modules/Settings/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Settings/language/zh_cn.lang.php new file mode 100644 index 00000000..41c05cc1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/language/zh_cn.lang.php @@ -0,0 +1,1043 @@ + '设定', + 'LBL_MODULE_TITLE' => '设定: 首页', + 'LBL_LIST_CONTACT_ROLE' => '职位', + + + + 'LBL_LIST_LAST_NAME' => '姓氏', + 'LBL_FIRST_NAME' => '姓名:', + 'LBL_LAST_NAME' => '姓氏:', + 'LBL_PHONE' => '电话:', + 'LBL_EMAIL_ADDRESS' => '电子邮件', + + 'LBL_TRANSCURR' => '转换使用者货币为', + +'LBL_CURRDEL' => '要删除的货币', + 'LBL_NEW_FORM_TITLE' => '新增联系人', + 'LBL_NEW_CURRENCY' => '新货币', + 'LBL_VIEWING' => '检视中', + 'LBL_CURRENCY_NAME' => '货币名称', + 'LBL_CURRENCY_CODE' => '货币编码', + 'LBL_CURRENCY_SYMBOL' => '货币符号', + 'LBL_CURRENCY_CRATE' => '汇率', + 'LBL_CURRENCY_STATUS' => '状态', + 'LBL_CURRENCY_TOOL' => '工具', + 'LBL_CURRENCY_LIST' => '货币列表', + + + 'NTC_DELETE_CONFIRMATION' => '您确定要删除这笔记录?', + +'LEADCUSTOMFIELDS' => '潜在客户自订字段', + + 'ACCOUNTCUSTOMFIELDS' => '客户自订字段', + +'CONTACTCUSTOMFIELDS' => '联系人自订字段', + + 'OPPORTUNITYCUSTOMFIELDS' => '潜在机会自订字段', + +'HELPDESKCUSTOMFIELDS' => '服务台自订字段', + + 'PRODUCTCUSTOMFIELDS' => '业务类型自订字段', + + 'VENDORCUSTOMFIELDS' => '厂商自订字段', + + 'PRICEBOOKCUSTOMFIELDS' => '价目表自订字段', + +'POCUSTOMFIELDS' => '采购订单自订字段', +'SOCUSTOMFIELDS' => '销售订单自订字段', +'QUOTESCUSTOMFIELDS' => '报价单自订字段', +'INVOICECUSTOMFIELDS' => '发票自订字段', + + 'EDITLEADPICKLISTVALUES' => '编辑潜在客户列表 ', + 'EDITACCOUNTPICKLISTVALUES' => '编辑客户列表 ', + 'EDITCONTACTPICKLISTVALUES' => '编辑联系人列表 ', + 'EDITOPPORTUNITYPICKLISTVALUES' => '编辑潜在机会列表 ', + 'EDITHELPDESKPICKLISTVALUES' => '编辑服务台列表 ', + + 'EDITPRODUCTPICKLISTVALUES' => '编辑业务类型列表 ', + 'EDITEVENTPICKLISTVALUES' => '编辑事件列表 ', + 'EDITTASKPICKLISTVALUES' => '编辑任务列表 ', + 'EDITRSSPICKLISTVALUES' => '编辑RSS列表', + 'EDITVENDORPICKLISTVALUES' => '编辑厂商列表', + 'EDITPBPICKLISTVALUES' => '编辑价目表列表', + 'EDITPOPICKLISTVALUES' => '编辑采购订单列表', + 'EDITSOPICKLISTVALUES' => '编辑销售订单列表', + 'EDITQUOTEPICKLISTVALUES' => '编辑报价单列表', + 'EDITINVOICEPICKLISTVALUES' => '编辑发票列表', + + +// Added for Release vtigerCRM 3.2 PATCH 1.0 + +//Settings/index.php + + + 'LBL_PICKLIST_FIELD_SETTINGS' => '列表字段设定:', + + +//SETTINGS/CustomFieldList.php,ComboFieldList.php,CreateCustomField.php + + 'Leads' => '潜在客户', + 'Accounts' => '客户', + 'Contacts' => '联系人', + 'Potentials' => '潜在机会', + 'HelpDesk' => '服务台', + 'Products' => '业务类型', + 'Events' => '事件', + 'Activities' => '任务', + + + + + + 'CustomFields' => ' 自订字段', + + 'NewCustomField' => '新增自订字段', + 'NewCustomFieldAltC' => '新增自订字段 [Alt+c]:', + 'FieldName' => '文件名称', + 'FieldType' => '字段类型', + 'FieldLabel' => '字段标签', + 'Delete' => '删除', + 'NEW' => '新增', + 'CUSTOMFIELD' => '自订字段', + 'LBL_CUSTOM_FIELDS' => '自订字段', + 'LBL_ADD_FIELD' => '新增字段', + 'LBL_CUSTM_MSG' => '允许您...', + +'PicklistFields' => ' 选择列表字段', + 'Edit' => '编辑', + 'LBL_EDIT_FIELD_TYPE' => '编辑字段类型', + +//Settings/CustomField.html + +'LBL_PROVIDE_FIELD_INFORMATION' => '提供字段信息: ', + 'LBL_SELECT_FIELD_TYPE' => '选择字段类别: ', + 'LBL_PROVIDE_FIELD_DETAILS' => '提供字段细节: ', + 'LBL_LABEL' => '标签: ', + 'LBL_LENGTH' => '长度: ', + 'LBL_DECIMAL_PLACES' => '小数点: ', + 'LBL_PICK_LIST_VALUES' => '选择列表值: ', + + + +//Settings/EditComboField.php + + 'EditPickListValues' => '编辑选择列表 ', + + + +//Settings/EditField.html + +'LBL_FIELD_INFORMATION' => '字段信息:', + 'Values' => '值', + +'EnterListOfValues' => '请输入列表值.', + + +//Settings/fieldtypes.php + +'Text' => '文字', + 'Number' => '数值', + 'Percent' => '百分比', + 'Currency' => '货币', + 'Date' => '日期', + 'Email' => '电子邮件', + 'Phone' => '电话', + 'PickList' => '选择列表', + 'LBL_MULTISELECT_COMBO' => '多选区块', + 'Skype' => 'Skype', + + +//added for patch2 + + 'USERGROUPLIST' => '用户组', + + 'EMAILTEMPLATES' => '电子邮件模板', + 'WORDINTEGRATION' => '邮件合并模板', + 'LBL_MAIL_MERGE' => '邮件合并', + 'NOTIFICATIONSCHEDULERS' => '通知列表', +//currency status + 'LBL_ACTIVE' => '启用', + 'LBL_INACTIVE' => '停用', + 'LBL_NOTIFICATION' => '提醒', + 'LBL_DESCRIPTION' => '说明', + 'LBL_TOOL' => '工具', + + +//Added fields for Title Informations -- after 4 Beta + + 'LBL_EMAIL_CONFIG' => '电子邮件环境设定', + 'LBL_WORD_INTEGRATION' => '完成文字:', + 'LBL_GROUP_SETTINGS' => '用户组设定:', + 'LBL_TEMPLATE_SETTINGS' => '模板设定:', + 'LBL_NOTIFICATION_SETTINGS' => '通知设定:', + +'LBL_EMAIL_SETTINGS' => '电子邮件设定:', + 'LBL_SECURITY_SETTINGS' => '安全设定:', + + + +//Added fields after RC1 - Release + + 'LBL_MAIL_SERVER_INFO' => '邮件服务器信息', + 'LBL_OUTGOING_MAIL_SERVER' => '邮件服务器', + 'LBL_OUTGOING_MAIL_SERVER_LOGIN_USER_NAME' => '邮件服务器登入使用者名称', + 'LBL_OUTGOING_MAIL_SERVER_PASSWORD' => '邮件服务器登入密码', + 'LBL_MAIL_SERVER_SMTP' => '邮件服务器 (SMTP)', + 'LBL_BACKUP_SERVER_CONFIG' => '备份服务器环境设定', + 'LBL_SERVER_ADDRESS' => '服务器地址', + 'LBL_FTP_SERVER_NAME' => '档案服务器名称', + 'LBL_FTP_USER_NAME' => '档案服务器登入使用者名称', + 'LBL_FTP_PASSWORD' => '档案服务器登入密码', + 'LBL_FTP' => 'FTP', + 'LBL_SYSTEM_CONFIG' => '系统环境设定', + 'LBL_SYSTEM_INFO' => '系统信息', + 'LBL_PROXY_SETTINGS' => '代理服务器设定', + 'LBL_AUDIT_TRAIL' => '稽核追踪信息', + 'LBL_ENABLE_AUDIT_TRAIL' => '启用稽核追踪', + 'LBL_USER_AUDIT' => '选择使用者', + 'LBL_VIEW_AUDIT_TRAIL' => '检视稽核追踪', + 'LBL_AUDIT_TRAIL_DESC' => '显示存取 CRM 使用者的稽核追踪', + 'LBL_NO_DATA' => '没有资料', + 'LBL_CURRENCY_CONFIGURATION' => '- 货币信息', + 'LBL_CURRENCY_CONFIG' => '货币设定', + 'LBL_CURRENCY_INFO' => '货币信息', + 'LBL_CURRENCY_TITLE' => '货币', + 'LBL_CURRENCY_SETTINGS' => '货币设定', + 'LBL_USERNAME' => '账号', + 'LBL_PASWRD' => '密码', + 'LBL_REQUIRES_AUTHENT' => '需要验证?', + +//Fields for Settings + + 'LBL_USER_MANAGEMENT' => '使用者管理', + 'LBL_USERS' => '使用者', + 'LBL_USERS_LIST' => '使用者列表', + 'LBL_GROUP_LIST' => '用户组列表', + 'LBL_CREATE_AND_MANAGE_USERS' => '- 建立和管理使用者 (e.g., admin)', + 'LBL_CREATE_AND_MANAGE_USER_ROLES' => '- 建立和管理职位 (e.g., Administrator, Standard User, etc.)', + 'LBL_PROFILES' => '数据', + 'LBL_PROFILES_LIST' => '资料列表', + 'LBL_CREATE_AND_MANAGE_USER_PROFILES' => '- 建立和管理使用者数据 (e.g., CEO, Sales Manager, etc.)', + 'LBL_CREATE_AND_MANAGE_USER_GROUPS' => '- 建立和管理使用者用户组', + 'LBL_SHARING_ACCESS' => '分享权限', + 'LBL_FIELDS_ACCESS' => '字段权限', + 'LBL_DEFAULT_ORGANIZATION_FIELDS' => '预设组织单位字段存取', + 'LBL_SETTING_DEFAULT_ORGANIZATION_FIELDS' => '设定组织单位的字段存取默认值', + 'LBL_SETTING_DEFAULT_SHARING_ACCESS' => '- 设定组织单位的分享存取默认值', + 'LBL_FIELD_ACCESSIBILITY' => '影响字段', + 'LBL_SETTING_FIELD_ACCESSIBILITY' => ' - 设定不同的数据之影响字段', +//<<<<<<<>>>>> +'LBL_FIELD_ORDERING_DESC' => ' - 编辑字段顺序', + 'LBL_FIELD_ORDERING' => '编辑字段区块', +//<<<<<<<<<>>>>>>>>>>>> + 'LBL_LEAD_FIELD_ACCESS' => '潜在客户字段存取', + 'LBL_ACCOUNT_FIELD_ACCESS' => '客户字段存取', + 'LBL_CONTACT_FIELD_ACCESS' => '联系人字段存取', + 'LBL_OPPORTUNITY_FIELD_ACCESS' => '潜在机会字段存取', + 'LBL_HELPDESK_FIELD_ACCESS' => '服务台字段存取', + 'LBL_PRODUCT_FIELD_ACCESS' => '业务类型字段存取', + 'LBL_NOTE_FIELD_ACCESS' => '备忘录字段存取', + 'LBL_EMAIL_FIELD_ACCESS' => '电子邮件字段存取', + 'LBL_TASK_FIELD_ACCESS' => '任务字段存取', + 'LBL_EVENT_FIELD_ACCESS' => '事件字段存取', + 'LBL_DELETE_DEMO_DATA' => '删除模板数据', + 'LBL_DELETE_DEMO_DATA_INFO' => '- 删除在安装时所建立的模板数据', + 'LBL_STUDIO' => '作业区', + 'LBL_CUSTOM_FIELD_SETTINGS' => '自订字段设定', + 'LBL_CREATE_AND_MANAGE_USER_DEFINED_FIELDS' => '- 建立和管理使用者定义字段', + 'LBL_SELECT_MODULE' => '选择模块', + + 'LBL_SELECT_CF_TEXT' => '选择模块:', + 'LBL_PICKLIST_SETTINGS' => '选择列表设定', + 'LBL_EDIT_PICKLIST_VALUES' => ' - 编辑选择列表字段设定值', + 'LBL_EDIT' => '编辑中', + 'LBL_COMMUNICATION_TEMPLATES' => '沟通模板', + 'LBL_CREATE_EMAIL_TEMPLATES' => ' - 建立电子邮件模板', + 'LBL_UPLOAD_MSWORD_TEMPLATES' => ' - 上传 MS Word 模板供合并邮件使用', + 'LBL_SCHEDULE_EMAIL_NOTIFICATION' => ' - 电子邮件通知列表', + 'LBL_EXPAND_CLOSE_MENU' => '展开/关闭选单', + 'LBL_CONFIGURATION' => '环境列表', + 'LBL_CONFIGURE_MAIL_SERVER' => ' - 设定邮件服务器', + 'LBL_BACKUP_SERVER_CONFIGURATION' => '备份服务器环境设定', + 'LBL_BACKUP_SERVER_INFO' => '备份服务器信息', + 'LBL_BACKUP_SERVER_SETTINGS' => '备份服务器设定', + 'LBL_CONFIGURE_BACKUP_SERVER' => ' - 设定备份服务器', + 'LBL_SYSTEM_CONFIGURATION' => ' - 系统环境设定', + 'LBL_PROXY_SERVER_CONFIGURATION' => '代理服务器设定', + 'LBL_PROXY_SERVER_INFO' => '代理服务器信息', + 'LBL_PROXY_SERVER_SETTINGS' => '代理服务器设定', + 'LBL_CONFIGURE_PROXY_SERVER' => ' - 设定代理服务器', + 'LBL_PROXY_PORT' => '连接埠', + + + +//Field Types for custom fields + + 'LBL_URL' => '网址', + 'LBL_CHECK_BOX' => '复选框', + + + +//PickList Settings + +'LBL_STANDARD_FIELDS' => '标准字段', + 'LBL_LEAD_SOURCE' => '接触来源', + 'LBL_SALUTATION' => '问候', + 'LBL_LEAD_STATUS' => '潜在客户身份', + 'LBL_INDUSTRY' => '企业', + 'LBL_RATING' => '评价', + 'LBL_ACCOUNT_TYPE' => '客户类型', + 'LBL_BUSINESS_TYPE' => '商业类型', + 'LBL_CURRENCY_TYPE' => '货币类型', + 'LBL_SALES_STAGE' => '客服场景', + 'LBL_PRIORITY' => '前置', + 'LBL_STATUS' => '身份', + 'LBL_CATEGORY' => '分类', + 'LBL_MANUFACTURER' => '厂商', + 'LBL_PRODUCT_CATEGORY' => '业务类型分类', + 'LBL_RSS_CATEGORY' => 'Rss类别', + +//Added for Web based Email client integration (post 4.0.1 release) + + 'LBL_ADD_MAIL_ACCOUNT' => '新增邮件账号', + 'LBL_NEW_MAIL_ACCOUNT_TITLE' => '新增邮件账号 [Alt+M]', + 'LBL_NEW_MAIL_ACCOUNT_KEY' => 'M', + 'LBL_NEW_MAIL_ACCOUNT_LABEL' => '新增邮件账号', + 'LBL_GENERAL_INFO' => '一般信息', + 'LBL_DISPLAY_NAME' => '显示名称', + 'LBL_MAIL_PROTOCOL' => '邮件协定', + 'LBL_LIST_PASSWORD' => '密码', + 'LBL_MAIL_SERVER_NAME' => '邮件服务器名称', + 'LBL_MAIL_SERVER_SETTINGS' => '外寄服务器', + 'LBL_INCOME_SERVER_SETTINGS' => '收件服务器', + 'LBL_TEST_SETTINGS' => '立刻测试我的设定', + 'LBL_TEST_BUTTON_TITLE' => '测试我的设定![Alt+T]', + 'LBL_TEST_BUTTON_KEY' => 'T', + 'LBL_TEST_BUTTON_LABEL' => '测试我的设定!', + 'LBL_DEFAULT' => '预设', + 'LBL_IMAP2' => 'IMAP2', + 'LBL_IMAP4' => 'IMAP4', + 'LBL_POP' => 'POP', + 'LBL_IMAP' => 'IMAP', + 'LBL_MAIL_DISCLAIM' => '有 * 符号表示必填,有 * * 表示完全支持', + 'LBL_SSL_OPTIONS' => 'SSL 选项', + 'LBL_TLS' => 'TLS', + 'LBL_NO_TLS' => 'No TLS', + 'LBL_CERT_VAL' => '验证执照', + 'LBL_INT_MAILER' => '使用内部邮件服务器?', + 'LBL_INT_MAILER_USE' => '是', + 'LBL_INT_MAILER_NOUSE' => '否', + 'LBL_VAL_SSL_CERT' => '验证 SSL 执照', + 'LBL_DONOT_VAL_SSL_CERT' => '不去验证 SSL 执照', + 'LBL_WEB_MAIL_CONFIG' => '网页邮件设定', + 'LBL_CONFIGURE_WEB_MAIL' => ' - 设定网页邮件', + 'LBL_LIST_MAIL_ACCOUNT' => '邮件账号列表', + 'LBL_USAGEUNIT' => '使用单位', + 'LBL_GLACCT' => '会计科目', + 'LBL_QUOTE_STAGE' => '报价策略', + 'LBL_CARRIER' => '运送单位', + 'LBL_TAXCLASS' => '税别', + 'LBL_MY_DETAILS' => '我的细节', + 'LBL_MY_MAIL_SERVER_DET' => '我的邮件服务器细节', + 'LBL_EMAIL_ID' => '信箱代号', + 'LBL_NAME_EXAMPLE' => '(例: John Fenner)', + 'LBL_EMAIL_EXAMPLE' => '(例: johnfenner@mailserver.com)', + 'LBL_REFRESH_TIMEOUT' => '重新整理频率', + 'LBL_1_MIN' => '1 分钟', + 'LBL_2_MIN' => '2 分钟', + 'LBL_3_MIN' => '3 分钟', + 'LBL_4_MIN' => '4 分钟', + 'LBL_5_MIN' => '5 分钟', + 'LBL_EMAILS_PER_PAGE' => '每页显示邮件数量', + +//Added for Organization Details (4.2 release) + 'LBL_ORGANIZATION_NAME' => '公司名称', + 'LBL_ORGANIZATION_ADDRESS' => '街道巷弄', + 'LBL_ORGANIZATION_CITY' => '乡镇市区', + 'LBL_ORGANIZATION_STATE' => '市(县)', + 'LBL_ORGANIZATION_CODE' => '邮政编码', + 'LBL_ORGANIZATION_COUNTRY' => '省(市/自治区)', + 'LBL_ORGANIZATION_PHONE' => '电话', + 'LBL_ORGANIZATION_FAX' => '传真', + 'LBL_ORGANIZATION_WEBSITE' => '网站', + 'LBL_ORGANIZATION_DETAILS' => '公司信息', + 'LBL_SPECIFY_COMPANY_DETAILS' => ' - 指定公司信息', + 'LBL_ORGANIZATION_LOGO' => 'Logo 名称', + 'LBL_UPLOAD' => '上传', + 'LBL_FILENAME' => '文件名称', + 'LBL_SETTINGS' => '设定', + 'LBL_COMPANY_DETAILS' => '公司细节', + 'LBL_SEVERITY' => '俭朴', + 'LBL_FAQ_CATEGORY' => '常见问答类别', + 'LBL_VENDOR_FIELD_ACCESS' => '厂商字段存取权限', + 'LBL_PB_FIELD_ACCESS' => '价目表字段存取权限', + 'LBL_QUOTE_FIELD_ACCESS' => '报价单字段存取权限', + 'LBL_PO_FIELD_ACCESS' => '采购订单字段存取权限', + 'LBL_SO_FIELD_ACCESS' => '销售订单字段存取权限', + 'LBL_INVOICE_FIELD_ACCESS' => '发票字段存取权限', + 'INVENTORYNOTIFICATION' => '库存提醒通知', + 'LBL_INVENTORY_NOTIFICATIONS' => '编辑库存邮件通知', + 'INVENTORYTERMSANDCONDITIONS' => '库存期间与条件',//newly added for Inventory terms and conditions + 'LBL_INVENTORY_TERMSANDCONDITIONS' => ' - 编辑库存期间与条件',//newly added + 'LBL_TANDC_TEXT' => '期间与条件内容', + 'LBL_INVENTORY_TANDC' => '库存期间与条件', + 'LBL_OTHER_SETTINGS' => '其它设定', + 'LBL_SCROLL' => '[回到顶部]', + 'LBL_INV_NOT_DESC' => '下面是提醒通知的列表,用来在手动建立报价单、销售订单与发票时寄送给产品处理者,包括需求与目前数量等信息', + 'InvoiceNotification' => '在建立发票时提醒产品库存', + 'InvoiceNotificationDescription' => '当产品库存低于安全存量时,提醒通知会发送给产品处理者', + 'Vendor' => '厂商', + 'PriceBook' => '价目表', + 'Quotes' => '报价单', + 'PurchaseOrder' => '采购订单', + 'SalesOrder' => '销售订单', + 'Invoice' => '发票', + +//For Custom Fields + 'LBL_LEAD_MAP_CUSTOM_FIELD' => '对应潜在客户字段', + 'leadCustomFieldDescription' => '将您的组织潜在客户字段对应到客户、联系人或潜在机会字段,在转换潜在客户时会使用到这些对应。', + 'LBL_MAPPING_INFO' => '对应信息', + 'LBL_ACCOUNT_FIELD' => '客户字段', + 'LBL_CONTACT_FIELD' => '联系人字段', + 'LBL_POTENTIAL_FIELD' => '潜在机会字段', + 'CUSTOMFIELDMAPPING' => '自订字段对应', + 'LBL_FIELD_MAPPING' => '字段对应', + 'LBL_LEAD_FIELD' => '潜在客户字段', +//After 4.2 GA + 'LBL_TEXT_AREA' => '文字区域', +//for Edit ordering the blocks + 'NOTESCUSTOMFIELDS' => '自订记事字段', + +//Added fields after 4.2 ptach 2 +'LBL_ASSIGN_MODULE_OWNERS' => '指定模块拥有者', + 'LBL_MODULE_OWNERS' => '模块拥有者', + 'LBL_ASSIGN_MODULE_OWNERS_INFO' => ' - 指定每个模块的拥有者', + 'LBL_MODULE' => '模块', + 'LBL_OWNER' => '拥有者', + 'LBL_MIGRATION' => '从上一个版本升级', + 'LBL_MIGRATION_INFO' => ' - 从上一个版本升级', + +//Added for 5 GA - Description of Settings UI + +'LBL_USER_DESCRIPTION' => '管理CRM的使用者', + 'LBL_ROLE_DESCRIPTION' => '定义角色阶层并且指派给使用者', + 'LBL_PROFILE_DESCRIPTION' => '定义每个角色存取数据权限', + 'LBL_GROUP_DESCRIPTION' => '基于角色、使用者、数据等自定义用户组', + 'LBL_SHARING_ACCESS_DESCRIPTION' => '定义每个角色存取CRM 模块的权限', + 'LBL_SHARING_FIELDS_DESCRIPTION' => '在每个CRM模块显示或隐藏字段', + 'LBL_MODULE_OWNERS_DESCRIPTION' => '指派每个CRM模块的拥有者', + 'LBL_ANNOUNCEMENT_DESCRIPTION' => '编辑公告显示的文字', + 'LBL_CUSTOM_FIELDS_DESCRIPTION' => '建立与管理使用者自订字段', + 'LBL_PICKLIST_DESCRIPTION' => '管理所有CRM 模块下拉选单的内容', + 'LBL_EMAIL_TEMPLATE_DESCRIPTION' => '管理邮件模块的模板', + 'LBL_MAIL_MERGE_DESCRIPTION' => '管理邮件合并的模板', + 'LBL_NOTIF_SCHED_DESCRIPTION' => '管理重要操作的警示通知', + 'LBL_INV_NOTIF_DESCRIPTION' => '修改库存相关提醒的设定', + 'LBL_INV_TANDC_DESCRIPTION' => '管理期间与条件文字内容', + 'LBL_COMPANY_DESCRIPTION' => '管理公司数据', + 'LBL_MAIL_SERVER_DESCRIPTION' => '编辑寄件邮件服务器设定', + 'LBL_BACKUP_SERVER_DESCRIPTION' => '编辑备份服务器设定', + 'LBL_CURRENCY_DESCRIPTION' => '管理货币与汇率', + 'LBL_TAX_DESCRIPTION' => '管理税务', + 'LBL_SYSTEM_DESCRIPTION' => '显示系统设定', + 'LBL_PROXY_DESCRIPTION' => '编辑联机设定', + 'LBL_AUDIT_DESCRIPTION' => '显示稽核追踪设定', + 'LBL_TAX_DESC' => '管理税务设定', + 'LBL_COMPANY_DESC' => '公司的信息与联络方式', + 'LBL_SELECT_LOGO' => '选择新的代表图示:', + 'LBL_INVEN_TANDC_DESC' => '修改在库存模块中显示的期间与限制区域文字', + 'LBL_MAIL_SERVER_DESC' => '管理邮件服务器设定', + 'LBL_BACKUP_SERVER_DESC' => '管理备份服务器设定', + 'LBL_MODULES_AND_OWNERS' => '模块与拥有者', + 'LBL_GROUP_DESC' => '管理使用者用户组', + 'LBL_MAIL_MERGE_DESC' => '管理 CRM 模块使用的邮件合并样板', + + +//Added fields after 5.0 Alpha + 'LBL_REQUIRE_SMTP_AUTHENTICATION' => '使用 SMTP 认证?', + 'LBL_ANNOUNCEMENT' => '新闻', + 'LBL_SETTING_ANNOUNCEMENT' => '新闻', + 'LBL_ANNOUNCE_TEXT' => '公告文字', + 'LBL_UPDATE_BUTTON' => '更新', + 'LBL_ANNOUNCEMENT_INFO' => '请在下面输入新闻内容,完成后点选储存按钮。', + 'LBL_ANNOUNCEMENT_DESC' => '修改所有页面上方显示的公告文字', + 'LBL_EMAIL_CONTENTS' => '邮件内容', + 'LBL_SUBJECT' => '主旨', + 'LBL_MESSAGE' => '内容', + 'LBL_PICKLIST_EDITOR' => '选择清单编辑器', + 'LBL_PICKLIST_AVAIL' => '选择清单可用于', + 'LBL_PICKLIST_AVAILINFO1' => '这个选择清单可用于', + 'LBL_PICKLIST_AVAILINFO2' => '显示在下方,点选编辑来调整清单的内容。', + 'LBL_EDIT_PICKLIST' => '编辑选择清单', + 'LBL_PICKLIST_SAVEINFO' => '逐笔输入数据,接着点选储存按钮。', + 'LBL_SELECT_CRM_MODULE' => '选择 CRM 模块', + 'LBL_TAX_SETTINGS' => '税务设定', + 'LBL_INVENTORY_TAX_CONFIG' => '库存税率设定', + 'LBL_CUSTOM_MAPP_INFO' => '只有潜在客户模块支持对应其它模块字段', + 'LBL_MAPPING_OTHER_MODULES' => '对应其它模块', + 'LBL_CUSTOM_FILED_IN' => '自订字段于', + 'LBL_ROLE_HIERARCHY_TREE' => '角色与树状阶层', + 'LBL_EDIT_FIELD_MAPPING' => '编辑字段对应', + 'LBL_LOGIN_HISTORY_DETAILS' => '使用者登入记录', + 'LBL_LOGIN_HISTORY_DESCRIPTION' => '显示使用者的登入记录', + 'LBL_NON_EDITABLE_PICKLIST_ENTRIES' => '没有选择可以编辑的数据', + +//Added for Tax settings + 'LBL_PRODUCT_TAX_SETTINGS' => '产品与服务税率', + 'LBL_SHIPPING_HANDLING_TAX_SETTINGS' => '货运与处理税率', + 'LBL_PROXY_SERVER_DESC' => '设定存取 RSS 来源的代理服务器', + +'LBL_NEW_CURRENCTY' => '新增货币', + 'LBL_BASE_CURRENCY' => '基础货币 - ', + 'LBL_DELETE_CURRENCY' => '删除货币', + +//Added for singlepane view in modules + +'LBL_DEFAULT_DETAIL_VIEW' => '预设细节检视', + 'LBL_DEFAULT_MODULE_VIEW' => '预设模块检视', + 'LBL_DEFAULT_MODULE_VIEW_DESC' => '设定所有模块的预设细节检视', + 'LBL_ENABLE_SINGLEPANE_VIEW' => '启用单一检视', + + 'LBL_CLEAR_DATA' => '清除资料', + 'LBL_LENGTHALERT' => '抱歉,您不能够对应不同字符长度的字段,请修正。', + 'LBL_DECIMALALERT' => '抱歉,您不能够对应不同位数的数字,请修正。', + 'LBL_TYPEALERT_1' => '抱歉,您不能对应', +'LBL_WITH' => '于', + 'LBL_TYPEALERT_2' => '数据类型,请修正。', + 'LBL_ENABLE' => '启用', +'LBL_FAQ_FIELD_ACCESS' => '常见问答字段权限', + 'LBL_ADD_TAX_BUTTON' => '新增税额', +'LBL_NO_TAXES_AVAILABLE'=>'无税', +'LBL_PLEASE'=>'请', +//Added while moving role file from User to Setting Module + 'LBL_ROLES' => '职位', + 'LBL_CREATE_NEW_ROLE' => '建立新角色', + 'LBL_PROPERTIES' => '属性于', + 'LBL_NEW_ROLE' => '新角色', + 'LBL_ROLE_NAME' => '角色名称', + 'LBL_REPORTS_TO' => '汇报给', + 'LBL_PROFILE_M' => '资料', + 'LBL_PROFILES_AVLBL' => '可用资料', + 'LBL_ASSIGN_PROFILES' => '指定的数据', + 'LBL_MEMBER' => '成员', + 'LBL_DELETE_ROLE' => '删除角色', + 'LBL_ROLE_TO_BE_DELETED' => '要删除的角色', + 'LBL_TRANSFER_USER_ROLE' => '转换使用者到角色', + 'LBL_ASSOCIATED_PROFILES' => '相关资料:', + 'LBL_ASSOCIATED_USERS' => '相关使用者:', +//Added while moving email templates from Users to Settings + 'LBL_EMAIL_TEMPLATES' => '邮件样板', + 'LBL_EMAIL_TEMPLATE_DESC' => '管理在活动与大量邮件中使用的邮件样板', + 'LBL_LIST_SELECT' => '选择', + 'LBL_EMAIL_TEMPLATE' => '邮件样板', + 'LBL_TEMPLATE_TOOLS' => '工具', + 'LBL_NEW_TEMPLATE' => '新增样板', +'LBL_FOLDER' => '资料夹', + 'LBL_NAME' => '名称', + 'LBL_PERSONAL' => '个人', + 'LBL_PUBLIC' => '公开', + 'LBL_ACCOUNT_FIELDS' => '客户字段', + 'LBL_CONTACT_FIELDS' => '联系人字段', + 'LBL_LEAD_FIELDS' => '潜在客户字段', + 'LBL_USER_FIELDS' => '使用者字段', + 'LNK_SAMPLE_EMAIL' => '检视范例邮件', +//Added while moving Mail Merge templates from Users to Settings + 'LBL_TEMPLATE_FILE' => '样板档案', + 'LBL_MODULENAMES' => '模块', + 'LBL_DOWNLOAD' => '下载', + 'LBL_ADD_TEMPLATE' => '新增样板', + 'LBL_WORD_TEMPLATES' => '邮件合并样板', +//Added while moving Notification Schedulers from Users to Settings + 'LBL_TASK_NOTIFICATION' => '任务延迟提醒', + 'LBL_BIG_DEAL' => '高额订单提醒', + 'LBL_PENDING_TICKETS' => '等待中传票提醒', + 'LBL_MANY_TICKETS' => '问题过多提醒', + 'LBL_START_NOTIFICATION' => '支持开始提醒', + 'LBL_SUPPORT_NOTICIATION' => '支援结束提醒', +'LBL_SUPPORT_NOTICIATION_MONTH'=>'提前一个月提醒支援结束' , +'LBL_ACTIVITY_NOTIFICATION'=>'行程提醒', + +'LBL_TASK_NOTIFICATION_DESCRITPION' => '当一个任务延迟超过 24 小时提醒', + 'LBL_BIG_DEAL_DESCRIPTION' => '当高额订单成交时提醒', + 'LBL_TICKETS_DESCRIPTION' => '提醒注意等待处理的传票', + 'LBL_MANY_TICKETS_DESCRIPTION' => '当同一个人或单位接手太多传票时发出提醒,也许需要委托其它服务层级', + 'LBL_START_DESCRIPTION' => '在支持或服务开始时提醒', + 'LBL_SUPPORT_DESCRIPTION' => '在支持或服务快结束时提醒', +'LBL_SUPPORT_DESCRIPTION_MONTH'=>'在支持或服务快结束时(提前一个月)提醒', +'LBL_ACTIVITY_REMINDER_DESCRIPTION' => '在行程开始前,依据设定的时间发出提醒', +//Added while moving Inventory Notifications from Users to Settings +'QuoteNotificationDescription' => '在报价单产生时,如果库存数量低于报价单数量,系统会发出通知给产品处理单位', + 'SalesOrderNotificationDescription' => '在销售订单产生时,如果库存数量低于报价单数量,系统会发出通知给产品处理单位', + 'Tools' => '工具', + 'QuoteNotification' => '在报价单产生时发出产品库存提醒', + 'SalesOrderNotification' => '在销售订单产生时发出产品库存提醒', + 'LBL_NOTE_DO_NOT_REMOVE_INFO' => '注意:不要移除或取代 { } 中的数值', + +//Added while moving Profile file from User to Setting Module + 'LBL_TOTAL' => '总计:', + 'LBL_NEW_PROFILE' => '新增资料', + 'LBL_LIST_NO' => '#', + 'LBL_NEW_PROFILE_NAME' => '数据名称', + 'LBL_LIST_TOOLS' => '工具', + 'LBL_PROFILE_MESG' => '检视存取权限 - ', + 'LBL_PROFILE_PRIVILEGES' => '数据权限', + 'LBL_DEFINE_PRIV_FOR' => '定义权限 -', + 'LBL_USE_OPTION_TO_SET_PRIV' => '使用下面选项设定权限', + 'LBL_SUPER_USER_PRIV' => '全域权限', + 'LBL_SET_PRIV_FOR_EACH_MODULE' => '设定每个模块的权限', + 'LBL_FIELDS_AND_TOOLS_SETTINGS' => '字段与工具设定', + 'LBL_VIEW_ALL' => '检视全部', + 'LBL_EDIT_ALL' => '编辑全部', + 'LBL_ALLOW' => '允许', + 'LBL_MESG_VIEW' => '检视所有信息与模块', + 'LBL_MESG_EDIT' => '编辑所有信息与模块', + 'LBL_TAB_MESG_OPTION' => '要显示的模块', + 'LBL_CREATE_EDIT' => '建立/编辑', + 'LBL_VIEW' => '检视', + 'LBL_MANDATORY_MSG' => '必填字段', + 'LBL_DISABLE_FIELD_MSG' => '全域字段存取设定停用的字段', + 'LBL_STEP_2_2' => '步骤 2 / 2', + 'LBL_FINISH_BUTTON' => '完成', + +//Added while moving Groups file from User to Setting Module + 'LBL_NEW_GROUP' => '新增用户组', + 'LBL_GROUPS' => '用户组', + 'LBL_GROUP_NAME' => '用户组名称', + 'LBL_ROLES_SUBORDINATES' => '角色与下属', + 'LBL_MEMBER_AVLBL' => '可用资料与成员', + 'LBL_MEMBER_SELECTED' => '选择的成员', + 'LBL_ENTITY' => '资料', + 'LBL_OF' => '于', + 'LBL_CREATE_NEW_GROUP' => '建立新用户组', + 'LBL_ADD_GROUP_BUTTON' => '新增用户组', + 'LBL_GROUP_MESG1' => '用户组是比较具有弹性的存取权限指派方式,当需要定义复杂的存取全现实,您可以合并像是角色、使用者、数据等项目到单一用户组中。', + 'LBL_GROUP_MESG2' => '要新增数据时,从左边窗体选择项目后点选 ">>" 按钮。', + 'LBL_GROUP_MESG3' => '要移除数据时,从右边窗体选择项目后点选 "<<" 按钮。', + +//Sharing Privileges + 'LBL_GLOBAL_ACCESS_PRIVILEGES' => '组织层级共享角色', + 'LBL_RECALCULATE_BUTTON' => '重新计算', + 'LBL_CHANGE' => '修改', + 'LBL_PRIVILEGES' => '权限', + 'LBL_CUSTOM_ACCESS_PRIVILEGES' => '自订共享规则', + 'LBL_ADD_PRIVILEGES_BUTTON' => '新增权限', + 'LBL_RULE_NO' => '角色编号', + 'LBL_CAN_BE_ACCESSED' => '可以存取于', + 'LBL_CUSTOM_ACCESS_MESG' => '没有定义自订权限规则', + 'LNK_CLICK_HERE' => '点选这里', + 'LBL_CREATE_RULE_MESG' => '建立新规则', + 'LBL_RECALC_MSG' => '您确定要重新计算共享权限?', + 'LBL_YES' => '是', + 'LBL_NO' => '否', + 'LBL_IN_PERMISSION' => '在权限', + 'LBL_RELATED_MODULE_RIGHTS' => '相关模块权限', + 'LBL_USR_CAN_ACCESS' => '使用者可以', + 'LBL_USR_OTHERS' => '其它使用者', + 'LBL_USR_CANNOT_ACCESS' => '使用者不能存取其它使用者', + + 'LBL_ORG_SHARING_PRIVILEGES' => '组织共享权限', + 'LBL_EDIT_PERMISSIONS' => '编辑权限', + 'LBL_SAVE_PERMISSIONS' => '储存权限', + 'LBL_READ_ONLY' => '公开:只读', + 'LBL_EDIT_CREATE_ONLY' => '公开:读取、建立/编辑', + 'LBL_READ_CREATE_EDIT_DEL' => '公开:读取、建立/编辑、删除', + 'LBL_PRIVATE' => '个人', + + 'Public: Read Only' => '公开:只读', + 'Public: Read, Create/Edit' => '公开:读取、建立/编辑', + 'Public: Read, Create/Edit, Delete' => '公开:读取、建立/编辑、删除', + 'Private' => '个人', + 'Hide Details' => '隐藏细节', + 'Hide Details and Add Events' => '隐藏细节并且新增行程', + 'Show Details' => '显示细节', + 'Show Details and Add Events' => '显示细节并且新增行程', + +//Added for User Login History While moving from User to Settings + 'LBL_LOGIN_HISTORY' => '登入记录', +//Sharing Access module moved to Setting + 'Read/Write' => '读/写', + 'Read Only ' => '只读', + 'LBL_GROUP' => '用户组', + 'LBL_ACCESS_RIGHTS_FOR_MODULES' => '相关模块的存取权限', + 'LBL_ADD_RULE' => '新增规则', + 'LBL_ADD_CUSTOM_RULE' => '新增自订权限角色', + 'LBL_RULE_CONSTRUCTION' => '显示角色架构', + 'LBL_STEP' => '步骤', + 'LBL_SELECT_ENTITY' => '从下面选择一个数据', + 'LBL_CAN_BE_ACCESSED_BY' => '可以存取于', + 'LBL_PERMISSIONS' => '权限', + 'LBL_DOC_MSWORD' => '档案必须是 doc/msword 格式', + 'LBL_NODOC' => '数据夹中没有档案,请重试!', + +//Added for error messages on Company Info. +'LOGO_ERROR'=>'标识只能使用 jpeg/png格式', +'Error_Message'=>'错误信息', +'Invalid_file'=>'无效文件或', +'File_has_no_data'=>'档案已经没有数据', +'Sorry'=>'抱歉', +'uploaded_file_exceeds_maximum_limit'=>'上传文件的大小超过最高限额', +'try_file_smaller'=>'请尝试一个文件小于800000字节', +'Problems_in_upload'=>'上传出现问题', +'Please_try_again'=>'请重试!', +//5.0.3 fixes +'LBL_TESTMAILSTATUS'=>'测试邮件地位 : ', +'LBL_CHECK_ASSIGNEDTO_MAILID'=>'请检查指派的邮件ID', +'LBL_MAILSENDERROR'=>'电子邮件不能被发送到管理员用户。请检查管理员邮件帐号 /服务器设置', +'LBL_RECORD_NOEXIST'=>'记录不存在', +'LBL_ENTER_PROFILE'=>'输入配置名称', +'LBL_ENABLE'=>'开启', +'LBL_DISABLE'=>'关闭', +'LBL_PROXY'=>'代理', +'LBL_FIELDS_TO_BE_SHOWN'=>'各领域表现', +//Added for alerts +'SPECIFY_FILE_TO_MERGE' => '请注明文件合并', +'FILESIZE_EXCEEDS_INFO_CONFIG_INC' => '对不起,上传的文件超过了最大文件大小限制在config.inc.php 。请尽量为较小的文件', +'FILESIZE_EXCEEDS_INFO_PHP_INI' => '对不起,上传的文件超过了最大文件大小限制在php.ini。请尽量为较小的文件', +'PROBLEMS_IN_FILEUPLOAD' => '上传出现问题,请重试!', + +//Added fields for Invoice Number labels +'LBL_CUSTOMIZE_INVOICE_NUMBER'=>'自选发票数量', +'LBL_CUSTOMIZE_INVOICE_NUMBER_DESCRIPTION'=>'发票编号定制', +'LBL_CUSTOM_INVOICE_NUMBER_VIEW'=>'发票编号定制', +'LBL_CUSTOMINVOICE_STRING'=>'定制发票字符串', +'LBL_CUSTOMINVOICE_NUMBER'=>'定制发票字符串', +'LBL_INVOICE_NUMBER_PREVIEW'=>'预览', +'LBL_INVOICE_NUMBER_BUTTON'=>'更新发票数量', +'LBL_PROXY_AUTHENTICATION_REQUIRED'=>'代理认证要求', +'LBL_ENABLE_FTP' => '你一定要开通PHP中的ftp支持功能,', + +//Added for Role Labels +'LBL_ADD_ROLE'=>'添加职位', +'LBL_EDIT_ROLE'=>'编辑职位', +'LBL_MOVE_ROLE'=>'移除职位', +'LBL_BACKUP_DESC'=>' 客户关系管理系统允许你在ftp服务器上作一个备份的数据库,。每当一个管理员用户登录,客户关系管理将采取备份所有的数据,。要确定你的FTP服务器有足够的磁盘空间。创建备份文件的格式为: "backup-date-time.sql".', +// Added/Updated for vtiger CRM 5.0.4 +'LBL_SUPPORT_NOTICIATION'=>'支持结束前一个星期通知', +'LBL_SUPPORT_NOTICIATION_MONTH'=>'支持结束前一个月通知' , +'LBL_SUPPORT_DESCRIPTION'=>'支持即将结束,提前一个星期通知!', +'LBL_SUPPORT_DESCRIPTION_MONTH'=>'支持即将结束,提前一个月通知!', +'LBL_SELECT_ROLE'=>'选择职位', +'LBL_TEMPLATE'=>'模板', +'LBL_SELECT_EMAIL_TEMPLATE_FOR'=>'选择邮件模板', + +'ERR_CUSTOM_FIELD_WITH_NAME'=>'Custom Field with the Name ', +'ERR_ALREADY_EXISTS'=>' already exists.', +'ERR_SPECIFY_DIFFERENT_LABEL'=>'Please specify a different Label', +'LBL_TOOLS_TO_BE_SHOWN'=>'Tools to be shown', +'LBL_PICKLIST_GLOBAL_CHANGE'=>'Global Change', +'LBL_PICKLIST_TRANSFER'=>'Transfering the values Of ', +'LBL_REPLACE_VALUE_WITH'=>'Replace value with ', +'LBL_EDIT_CUSTOM_RULE'=>'Edit Custom Privilege Rule', + +/*for global add/delete in picklist*/ +'DELETE_PICKLIST_VALUES'=>'Delete PickList Values', +'EDIT_PICKLIST_VALUE'=>'Edit PickList Value', +'ADD_PICKLIST_VALUES'=>'Add PickList Values', +'LBL_PICKLIST_ADDINFO'=>'Type the new entries one-by-one below', +'LBL_SELECT_ROLES'=> 'Select the Roles to which entries have to be added', +'LBL_EXISTING_PICKLIST_VALUES'=>'Existing Picklist Values', +'LBL_SELECT_PICKLIST'=>'Select picklist', + +// Added after 5.0.4 GA + +'LBL_GENERAL_FIELDS'=>'General Fields', + +'LBL_CANCEL_BUTTON'=>'Cancel', + +//Added fields for Inventory Number labels +'LBL_CUSTOMIZE_INVENTORY_NUMBER'=>'Customize Inventory Sequence', +'LBL_CUSTOMIZE_INVENTORY_NUMBER_DESCRIPTION'=>'Inventory Sequence Customization', +'LBL_CUSTOM_QUOTE_NUMBER_VIEW'=>'Quote Number Customization', +'LBL_CUSTOMQUOTE_STRING'=>'Custom Quote String', +'LBL_CUSTOMQUOTE_NUMBER'=>'Custom Quote Number', +'LBL_QUOTE_NUMBER_PREVIEW'=>'Preview', +'LBL_QUOTE_NUMBER_BUTTON'=>'更新发票号码', +'LBL_CUSTOM_SO_NUMBER_VIEW'=>'SalesOrder Number Customization', +'LBL_CUSTOMSO_STRING'=>'Custom SalesOrder String', +'LBL_CUSTOMSO_NUMBER'=>'Custom SalesOrder Number', +'LBL_SO_NUMBER_PREVIEW'=>'Preview', +'LBL_SO_NUMBER_BUTTON'=>'更新订单号码', +'LBL_CUSTOM_PO_NUMBER_VIEW'=>'PurchaseOrder Number Customization', +'LBL_CUSTOMPO_STRING'=>'Custom PurchaseOrder String', +'LBL_CUSTOMPO_NUMBER'=>'Custom PurchaseOrder Number', +'LBL_PO_NUMBER_PREVIEW'=>'Preview', +'LBL_PO_NUMBER_BUTTON'=>'更新采购订单号码', + +// Added after 5.0.4 GA + +// Added for Multi-Currency Support +'LBL_TRANSFER_CURRENCY'=>'Transfer Currency', +'LBL_CURRENT_CURRENCY'=>'Current Currency', + +//Added for new backup labels +'LBL_LOCAL'=>'Local', +'LBL_BACKUP'=>'Backup', +'LBL_BACKUP_LOCATION'=>'Backup Location', + +'LBL_LAYOUT_EDITOR'=>'布局设计', +'LBL_LAYOUT_EDITOR_DESCRIPTION'=>'设计和修改各个模块的布局', +'LBL_Show'=>'显示', +'LBL_Hide'=>'隐藏', + +// vtlib customization: Language Stings +'VTLIB_LBL_MODULE_MANAGER'=>'模块管理', +'VTLIB_LBL_MODULE_MANAGER_DESCRIPTION'=>'管理系统内部模块是否显示及方式', +'VTLIB_LBL_MODULE_MANAGER_CUSTOMMOD'=>'定制模块', +'VTLIB_LBL_MODULE_MANAGER_STANDARDMOD'=>'标准模块', +'VTLIB_LBL_MODULE_MANAGER_NOMODULES'=>'没有发现定制模块! 创建一个块导入一个新模块 ...', + +// vtmailscanner START +'LBL_MAIL_SCANNER'=>'邮件扫描', +'LBL_MAIL_SCANNER_DESCRIPTION'=>'配置邮箱扫描', +'LBL_SCAN_NOW'=>'现在扫描', +'LBL_RULE'=>'规则', +'LBL_SETUP'=>'安装', +'LBL_CONFIGURE'=>'设置', +'LBL_MAILBOX' => '邮箱', +'LBL_INFORMATION' => '信息', +'LBL_SCANNER' => '扫描器', +'LBL_SERVER' => '服务器', +'LBL_PROTOCOL'=> '协议', +'LBL_PASSWORD'=> '密码', +'LBL_TYPE' => '类型', +'LBL_SSL' => 'SSL', +'LBL_METHOD'=> '方法', +'LBL_VAL_SSL_CERT'=>'验证SSL证书', +'LBL_DONOT_VAL_SSL_CERT'=>'不验证SSL证书', +'LBL_STATUS'=>'状态', +'LBL_ENABLE'=>'打开', +'LBL_DISABLE'=>'关闭', +'LBL_CONNECT'=>'链接', +'LBL_URL_CAPS'=>'URL', +'LBL_ENABLED'=>'Enabled', +'LBL_DISABLED'=>'Disabled', +'LBL_RULES'=>'规则', +'LBL_FOR'=>'-', + +'LBL_FROM'=>'From', +'LBL_TO'=>'To', + +'LBL_ACTION'=>'Action', +'LBL_CREATE'=>'Create', +'LBL_TICKET'=>'Ticket', +'LBL_ADD'=>'Add', + +'LBL_CONTACT'=>'Contact', +'LBL_ACCOUNT'=>'Account', + +'LBL_FROM_CAPS'=>'FROM', +'LBL_TO_CAPS'=>'TO', +'LBL_TO_SMALL'=>'to', + +'LBL_CONTAINS'=>'Contains', +'LBL_EQUALS'=>'Equals', + +'LBL_BEGINS'=>'Begins', + +'LBL_REGEX'=>'Regex', +'LBL_ENDS'=>'Ends', +'LBL_BODY'=>'Body', + +'LBL_NOT'=>'Not', + +'LBL_ALL' => 'All', +'LBL_ANY'=>'Any', +'LBL_CONDITION'=>'Condition', +'LBL_ACTION'=>'Action', +'LBL_MOVE'=>'Move', +'LBL_UP'=>'Up', +'LBL_DOWN'=>'Down', +'LBL_PRIORITY'=>'Priority', +'LBL_UPDATE'=>'更新', +'LBL_SELECT'=>'Select', +'LBL_FOLDERS'=>'Folders', +'LBL_UNSELECT'=>'Unselect', +'LBL_MATCH'=>'Match', +'LBL_SCANNING'=>'Scanning', +'LBL_LOOKFOR'=>'Look for', +'LBL_UNREAD'=>'未读', +'LBL_READ'=>'已读', +'LBL_AFTER_SCAN'=>'After scan', +'LBL_MESSAGES_FROM_LASTSCAN'=>'Messages from lastscan', +'LBL_MARK_MESSAGE_AS'=>'标记邮件为', + +//Added for the workflow module +'LBL_LIST_WORKFLOWS'=>'工作流', +'LBL_LIST_WORKFLOWS_DESCRIPTION' => '创建或修改工作流', +'LBL_TASK_TITLE'=>'任务标题', +'LBL_PARENT_WORKFLOW'=>'上一级工作流', +'MSG_EXECUTE_TASK_DELAY'=>'Execute the task after some delay', +'LBL_AFTER'=>'After', +'LBL_BEFORE'=>'Before', +'LBL_TASK_OPERATIONS'=>'Task Operations', +'LBL_CREATE_TASK'=>'Create Task', +'LBL_CREATE_TASK_OF_TYPE'=>'Create a new task of type', +'LBL_SUMMARY'=>'Summary', +'LBL_WHEN_TO_RUN_WORKFLOW'=>'When to run the workflow', +'LBL_ONLY_ON_FIRST_SAVE'=>'Only on the first save', +'LBL_UNTIL_FIRST_TIME_CONDITION_TRUE'=>'Until the first time the condition is true', +'LBL_EVERYTIME_RECORD_SAVED'=>'Every time the the record is saved', +'LBL_CONDITIONS'=>'Conditions', +'LBL_NEW_CONDITION_BUTTON_LABEL'=>'New Condition', +'LBL_TASKS'=>'Tasks', +'LBL_NEW_TASK_BUTTON_LABEL'=>'New Task', +'LBL_TASK'=>'Task', +// END +//Added for vantage customization (Mandatory fields) -- Pavani +'LBL_MANDATORY_FIELDS'=>'Mandatory Fields', +'LBL_MANDATORY_FIELDS_DESCRIPTION'=>'Manage mandatory fields of all modules', +// Module Sequence Numbering +'LBL_CUSTOMIZE_MODENT_NUMBER'=>'系统编号定制', +'LBL_CUSTOMIZE_MODENT_NUMBER_DESCRIPTION'=>'模块实体号码定制', +// END + +//added for softphone integration +'LBL_SOFTPHONE_SERVER_SETTINGS'=>'SoftPhone Server Settings', +'LBL_SOFTPHONE_SERVER_SETTINGS_DESCRIPTION'=>'Configure your softphone here', +'ASTERISK_SERVER_IP'=>'Asterisk server IP ', +'ASTERISK_PORT'=>'Asterisk server port', +'ASTERISK_USERNAME'=>'Asterisk username', +'ASTERISK_PASSWORD'=>'Asterisk password', +'ASTERISK_SERVER_IP_TITLE'=>'The URL of the asterisk server', +'ASTERISK_PORT_TITLE'=>'The port where asterisk call manager API can connect to Asterisk (default 5038)', +'ASTERISK_USERNAME_TITLE'=>'The asterisk username (generally the admin username)', +'ASTERISK_PASSWORD_TITLE'=>'Password for the asterisk user', +'LBL_CANCEL_BUTTON'=>'Cancel', +'ASTERISK_VERSION' => 'Asterisk Version', +'ASTERISK_VERSION_TITLE'=>'Select your Asterisk version here; leave it as 1.4 if not sure', +'ASTERISK_CONFIGURATION'=>'Asterisk Configuration', +//softphone integration ends +'LBL_SELECT_FIELD_TO_MOVE' => 'Select Fields to move', +'VTLIB_LBL_SELECT_PACKAGE_FILE'=>'选择一个打包文件', +'VTLIB_LBL_FILE_LOCATION'=>'文件位置:', +'VTLIB_LBL_PACKAGE_FILE_HELP'=>'要导入的系统模块必须为zip文件.', +'VTLIB_LBL_IMPORT_FAILURE'=>'导入失败', +'VTLIB_LBL_INVALID_FILE'=>'无效文件', +'VTLIB_LBL_INVALID_IMPORT_TRY_AGAIN'=>'provided for module import! Try Again.', +'VTLIB_LBL_UNABLE_TO_UPLOAD'=>'Unable to upload', +'VTLIB_LBL_UNABLE_TO_UPLOAD2'=>'the package on the server! Try Again.', +'VTLIB_LBL_VERIFY_IMPORT_DETAILS'=>'Verify Import Details', +'VTLIB_LBL_MODULE_NAME'=>'Module Name', +'VTLIB_LBL_MODULE_DIR'=>'Module Directory', +'VTLIB_LBL_REQ_VTIGER_VERSION'=>'Req. vtiger version', +'VTLIB_LBL_LICENSE'=>'License', +'VTLIB_LBL_LICENSE_ACCEPT_AGREEMENT'=>'I accept the license agreement.', +'VTLIB_LBL_PROCEED_WITH_IMPORT'=>'Do you want to proceed with the import?', +'VTLIB_LBL_IMPORTING_MODULE_START'=>'Importing Module ...', +'VTLIB_LBL_WARNING'=>'Warning', +'VTLIB_LBL_NOT_WRITEABLE'=>'not writeable', +'VTLIB_LBL_PACKAGE_VERSION'=>'Version', + +'LBL_UPGRADE'=>'Upgrade', +'VTLIB_LBL_UPDATE_FAILURE'=>'Upgrade Failure', +'VTLIB_LBL_MODULENAME_MISMATCH'=>'Module name mistmach', +'VTLIB_LBL_TRY_AGAIN'=>'Try Again', +'VTLIB_LBL_VERIFY_UPDATE_DETAILS'=>'Verify Upgrade Details', +'VTLIB_LBL_PROCEED_WITH_UPDATE'=>'Do you want to proceed with the upgrade?', +'VTLIB_LBL_UPDAING_MODULE_START'=>'Updating module...', +'VTLIB_LBL_EXISTS'=>'Exists', +'VTLIB_LBL_NOT_PRESENT'=>'Not Present', +'VTLIB_LBL_INST_VERSION'=>'Installed Version', +'VTLIB_LBL_MATCHES_PACKAGE_VERSION'=>'matches Package Version', +'VTLIB_LBL_CANNOT_UPGRADE'=>'Cannot updgrade!', +// END + +//User group fixes +'LBL_USERNAME_EXIST' => '指定名称的用户已经存在!', +'LBL_GROUPNAME_EXIST' => '指定名称的用户组已经存在!', +'LBL_ROLENAME_EXIST' => 'Role name already exists', + +//layout editor +'LBL_MOVE_FIELDS' => 'Move Fields', +'NO_HIDDEN_FIELDS' => 'No Hidden Fields', +'LBL_RELATED_LIST' => 'Related List', +'LBL_ADD_BLOCK' => 'Add Block', +'HIDDEN_FIELDS' => 'Hidden Fields', +'DOWN'=> 'Down', +'UP'=> 'Up', +'RIGHT' => 'Right', +'LEFT' => 'Left', +'LBL_EDIT_PROPERTIES' => 'Edit Properties', +'LBL_MANDATORY_FIELD' => 'Mandatory Field', +'LBL_ACTIVE' => 'Active', +'LBL_QUICK_CREATE' => 'Quick Create', +'LBL_MASS_EDIT' => 'Mass Edit', +'LBL_BLOCK_NAME' => 'Block name', +'AFTER' => 'After', +'ADD_BLOCK' => 'Add Block', +'ARRANGE_RELATEDLIST' => 'Arrange RelatedList', +'CUSTOMFIELD_MAPPING' => 'CustomField Mapping', +'LBL_MAPPED_FIELDS' => 'Mapped Fields', +'LEADS_CUSTOM_FIELD_MAPPING_DESCRIPTION' => 'Map Your Leads Customfields with Accounts,Contacts and Potentials', +'LEADS_CUSTOM_FIELD_MAPPING'=> 'Leads CustomField Mapping', +'LBL_CALENDER_CUSTOMFIELDS' => 'Calendar Custom Fields', +'LBL_CALENDER_CUSTOMFIELDS_DESCRIPTION' => 'You can Create Custom Fields for Calendar', +'LBL_GO_BACK'=>'Go Back', + +//Added fix for: 5418 +'LBL_USE_PREFIX' => '使用前缀', +'LBL_START_SEQ' => '起始数字', +'LBL_MODULE_NUMBERING' => '模块编号', +'LBL_FAILED' => '失败', +'LBL_DONE' => '执行完毕', +'LBL_IN_USE' => '使用中', +'LBL_MODULE_NUMBERING_FIX_MISSING' => '立刻更新丢失的编号', + +//Added for: 5473 +'LBL_SHARING_ACCESS_HELPNOTE' => '进行修改后,按重新计算按钮以应用更改.', + +//for customer portal extension module +'PORTAL_EXTENSION_DESCRIPTION'=>'允许您配置客户门户插件', +'LBL_CUSTOMER_PORTAL'=> '客户门户', + +//FieldFormulas +'LBL_FIELDFORMULAS' => '字段公式', +'LBL_FIELDFORMULAS_DESCRIPTION' => '为自定义字段添加公式 ', +); +?> diff --git a/oss/vtiger/trunk/modules/Settings/listemailtemplates.php b/oss/vtiger/trunk/modules/Settings/listemailtemplates.php new file mode 100644 index 00000000..d469cf7d --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/listemailtemplates.php @@ -0,0 +1,69 @@ +info("Inside Email Templates List View"); + + $sql = "select * from vtiger_emailtemplates order by templateid DESC"; + $result = $adb->pquery($sql, array()); + $temprow = $adb->fetch_array($result); + +$edit="Edit "; +$del="Del "; +$bar=" | "; +$cnt=1; + +require_once('include/utils/UserInfoUtil.php'); +global $app_strings; +global $app_list_strings; +global $mod_strings; +global $theme,$default_charset; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("UMOD", $mod_strings); +global $current_language; +$smod_strings = return_module_language($current_language,'Settings'); +$smarty->assign("APP", $app_strings); +$smarty->assign("MOD", $smod_strings); +$smarty->assign("MODULE", 'Settings'); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PARENTTAB", getParentTab()); + +$return_data=array(); +if ($temprow != null) +{ +do +{ + $templatearray=array(); + $templatearray['templatename'] = $temprow["templatename"]; + $templatearray['templateid'] = $temprow["templateid"]; + $templatearray['description'] = $temprow["description"]; + $templatearray['foldername'] = $temprow["foldername"]; + $return_data[]=$templatearray; + $cnt++; +}while($temprow = $adb->fetch_array($result)); +} + +$log->info("Exiting Email Templates List View"); + +$smarty->assign("TEMPLATES",$return_data); +$smarty->display("ListEmailTemplates.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/listgroups.php b/oss/vtiger/trunk/modules/Settings/listgroups.php new file mode 100644 index 00000000..2bd5a45f --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/listgroups.php @@ -0,0 +1,49 @@ +$groupInfo) +{ + + $standCustFld = array(); + $standCustFld['groupid']= $groupId; + $standCustFld['groupname']= $groupInfo[0]; + $standCustFld['description']= $groupInfo[1]; + $return_data[]=$standCustFld; + $cnt++; +} + +$smarty->assign("LIST_HEADER",$list_header); +$smarty->assign("LIST_ENTRIES",$return_data); +$smarty->assign("PROFILES", $standCustFld); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign('GRPCNT', count($return_data)); + +$smarty->display("ListGroup.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/listinventorynotifications.php b/oss/vtiger/trunk/modules/Settings/listinventorynotifications.php new file mode 100644 index 00000000..efc21afb --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/listinventorynotifications.php @@ -0,0 +1,47 @@ +pquery($query, array()); +$num_rows = $adb->num_rows($result); +$output = Array(); +for($i=0; $i<$num_rows; $i++) +{ + $out = Array(); + $not_id = $adb->query_result($result,$i,'notificationid'); + $not_mod = $adb->query_result($result,$i,'notificationname'); + $not_des = $adb->query_result($result,$i,'label'); + $out ['notificationname'] = $mod_strings[$not_mod]; + $out ['label'] = $mod_strings[$not_des]; + $out ['id'] = $not_id; + $output [] = $out; +} +$smarty->assign("NOTIFICATION",$output); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +if($_REQUEST['directmode'] != '') + $smarty->display("Settings/InventoryNotifyContents.tpl"); +else + $smarty->display("Settings/InventoryNotify.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/listnotificationschedulers.php b/oss/vtiger/trunk/modules/Settings/listnotificationschedulers.php new file mode 100644 index 00000000..64c13401 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/listnotificationschedulers.php @@ -0,0 +1,52 @@ +pquery($query, array()); +if($adb->num_rows($result) >=1) +{ + $notifiy_array = Array(); + while($result_row = $adb->fetch_array($result)) + { + $result_data = Array(); + $result_data['active'] = $result_row['active']; + $result_data['schedulename'] = $mod_strings[$result_row['schedulednotificationname']]; + $result_data['id'] = $result_row['schedulednotificationid']; + + if($result_data['active'] != 1) + $result_data['active'] = $mod_strings['LBL_INACTIVE']; + else + $result_data['active'] = $mod_strings['LBL_ACTIVE']; + + $result_data['label'] = $mod_strings[$result_row['label']]; + $notifiy_array []= $result_data; + } + $smarty->assign("NOTIFICATION",$notifiy_array); +} + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +if($_REQUEST['directmode'] != '') + $smarty->display("Settings/EmailNotificationContents.tpl"); +else + $smarty->display("Settings/EmailNotification.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Settings/listroles.php b/oss/vtiger/trunk/modules/Settings/listroles.php new file mode 100644 index 00000000..e79c4680 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/listroles.php @@ -0,0 +1,174 @@ +pquery($hquery, array()); +$num_rows = $adb->num_rows($hr_res); +$hrarray= Array(); + +for($l=0; $l<$num_rows; $l++) +{ + $roleid = $adb->query_result($hr_res,$l,'roleid'); + $parent = $adb->query_result($hr_res,$l,'parentrole'); + $temp_list = explode('::',$parent); + $size = sizeof($temp_list); + $i=0; + $k= Array(); + $y=$hrarray; + if(sizeof($hrarray) == 0) + { + $hrarray[$temp_list[0]]= Array(); + } + else + { + while($i<$size-1) + { + $y=$y[$temp_list[$i]]; + $k[$temp_list[$i]] = $y; + $i++; + + } + $y[$roleid] = Array(); + $k[$roleid] = Array(); + + //Reversing the Array + $rev_temp_list=array_reverse($temp_list); + $j=0; + //Now adding this into the main array + foreach($rev_temp_list as $value) + { + if($j == $size-1) + { + $hrarray[$value]=$k[$value]; + } + else + { + $k[$rev_temp_list[$j+1]][$value]=$k[$value]; + } + $j++; + } + } + +} +//Constructing the Roledetails array +$role_det = getAllRoleDetails(); +$query = "select * from vtiger_role"; +$result = $adb->pquery($query, array()); +$num_rows=$adb->num_rows($result); + +$roleout =''; +$roleout .= indent($hrarray,$roleout,$role_det); + +/** recursive function to construct the role tree ui + * @param $hrarray -- Hierarchial role tree array with only the roleid:: Type array + * @param $roleout -- html string ouput of the constucted role tree ui:: Type varchar + * @param $role_det -- Roledetails array got from calling getAllRoleDetails():: Type array + * @returns $role_out -- html string ouput of the constucted role tree ui:: Type string + * + */ + +function indent($hrarray,$roleout,$role_det) +{ + global $theme,$mod_strings,$app_strings; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + foreach($hrarray as $roleid => $value) + { + + //retreiving the vtiger_role details + $role_det_arr=$role_det[$roleid]; + $roleid_arr=$role_det_arr[2]; + $rolename = $role_det_arr[0]; + $roledepth = $role_det_arr[1]; + $roleout .= '
      '; + $roleout .= '
    • '; + $roleout.= ''; + $roleout .= '
      '; + if(sizeof($value) >0 && $roledepth != 0) + { + $roleout.=''; + $roleout .= ''.$app_strings['LBL_EXPAND_COLLAPSE'].''; + } + else if($roledepth != 0){ + $roleout .= ''.$app_strings['LBL_EXPAND_COLLAPSE'].''; + } + else{ + $roleout .= ''.$app_strings['LBL_ROOT'].''; + } + if($roledepth == 0 ){ + $roleout .= ' '.$rolename.'
      '.$mod_strings['LBL_ADD_ROLE'].'
      '; + } + else{ + $roleout .= ' '.$rolename.''; + + $roleout.='
      + '.$mod_strings['LBL_ADD_ROLE'].' + '.$mod_strings['LBL_EDIT_ROLE'].''; + + if($roleid != 'H1' && $roleid != 'H2') + { + + $roleout .= ''.$mod_strings['LBL_DELETE_ROLE'].''; + } + + $roleout .=''.$mod_strings['LBL_MOVE_ROLE'].' +
      '; +// $roleout .= ' Add | Edit | Delete | View'; + + + } + $roleout .= '
    • '; + if(sizeof($value) > 0 ) + { + $roleout = indent($value,$roleout,$role_det); + } + + $roleout .= '
    '; + + } + + return $roleout; +} +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("ROLETREE", $roleout); + +if($_REQUEST['ajax'] == 'true') +{ + $smarty->display("RoleTree.tpl"); +} +else +{ + $smarty->display("ListRoles.tpl"); +} +?> diff --git a/oss/vtiger/trunk/modules/Settings/listwordtemplates.php b/oss/vtiger/trunk/modules/Settings/listwordtemplates.php new file mode 100644 index 00000000..56a4bd3d --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/listwordtemplates.php @@ -0,0 +1,58 @@ +pquery($sql, array()); + +$edit="Edit "; +$del="Del "; +$bar=" | "; +$cnt=1; + +$return_data = Array(); +$num_rows = $adb->num_rows($result); + + +for($i=0;$i < $num_rows; $i++) +{ + $wordtemplatearray=array(); + $wordtemplatearray['templateid'] = $adb->query_result($result,$i,'templateid'); + $wordtemplatearray['description'] = $adb->query_result($result,$i,'description'); + $wordtemplatearray['module'] = $adb->query_result($result,$i,'module'); + $wordtemplatearray['filename'] = $adb->query_result($result,$i,'filename'); + $wordtemplatearray['filetype'] = $adb->query_result($result,$i,'filetype'); + $wordtemplatearray['filesize'] = $adb->query_result($result,$i,'filesize'); + $return_data []= $wordtemplatearray; +} +require_once('include/utils/UserInfoUtil.php'); +global $app_strings; +global $mod_strings; +global $theme,$default_charset; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$smarty = new vtigerCRM_Smarty; +global $current_language; +$smod_strings = return_module_language($current_language,'Settings'); +$smarty->assign("MOD", $smod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("UMOD", $mod_strings); +$smarty->assign("PARENTTAB", getParentTab()); +$smarty->assign("IMAGE_PATH",$image_path); + +$smarty->assign("WORDTEMPLATES",$return_data); +$smarty->display("ListWordTemplates.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/mailmergedownloadfile.php b/oss/vtiger/trunk/modules/Settings/mailmergedownloadfile.php new file mode 100644 index 00000000..5228a474 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/mailmergedownloadfile.php @@ -0,0 +1,43 @@ +pquery($dbQuery, array($templateid)) or die("Couldn't get file list"); +if($adb->num_rows($result) == 1) +{ +$fileType = $adb->query_result($result, 0, "filetype"); +$name = $adb->query_result($result, 0, "filename"); +//echo 'filetype is ' .$fileType; +$fileContent = $adb->query_result($result, 0, "data"); +$size = $adb->query_result($result, 0, "filesize"); +$name = html_entity_decode($name, ENT_QUOTES, $default_charset); +header("Content-type: $fileType"); +//header("Content-length: $size"); +header("Cache-Control: private"); +header("Content-Disposition: attachment; filename=$name"); +header("Content-Description: PHP Generated Data"); +echo base64_decode($fileContent); +} +else +{ +echo "Record doesn't exist."; +} +?> + diff --git a/oss/vtiger/trunk/modules/Settings/profilePrivileges.php b/oss/vtiger/trunk/modules/Settings/profilePrivileges.php new file mode 100644 index 00000000..4d59c6de --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/profilePrivileges.php @@ -0,0 +1,767 @@ +assign("SELECTED_TAB", vtlib_purify($_REQUEST['selected_tab'])); +else + $smarty->assign("SELECTED_TAB", "global_privileges"); + +if(isset($_REQUEST['selected_module']) && $_REQUEST['selected_module']!='') + $smarty->assign("SELECTED_MODULE", vtlib_purify($_REQUEST['selected_module'])); +else + $smarty->assign("SELECTED_MODULE", "field_Leads"); + +$smarty->assign("PARENTPROFILEID", $parentProfileId); +$smarty->assign("RADIOBUTTON", vtlib_purify($_REQUEST['radiobutton'])); + +$secondaryModule=''; +$mode=''; +$output =''; +$output1 =''; +$smarty->assign("PROFILEID", $profileId); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("CMOD", $mod_strings); +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != '') + $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); + + +if(isset($_REQUEST['profile_name']) && $_REQUEST['profile_name'] != '' && $_REQUEST['mode'] == 'create') +{ + $profileName=$_REQUEST['profile_name']; + $smarty->assign("PROFILE_NAME", to_html($profileName)); +} +else +{ + $profileName=getProfileName($profileId); + $smarty->assign("PROFILE_NAME", $profileName); + +} + +//$smarty->assign("PROFILE_NAME", to_html($profileName)); + +if(isset($_REQUEST['profile_description']) && $_REQUEST['profile_description'] != '' && $_REQUEST['mode'] == 'create') + + $profileDescription = vtlib_purify($_REQUEST['profile_description']); +else +{ + if($profileId != null) + { + $profileDescription = getProfileDescription($profileId); + } +} + +$smarty->assign("PROFILE_DESCRIPTION", $profileDescription); + +if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != '') + $smarty->assign("MODE",vtlib_purify($_REQUEST['mode'])); + + +//Initially setting the secondary selected vtiger_tab +$mode=$_REQUEST['mode']; +if($mode == 'create') +{ + $smarty->assign("ACTION",'SaveProfile'); +} +elseif($mode == 'edit') +{ + $smarty->assign("ACTION",'UpdateProfileChanges'); +} + + +//Global Privileges + +if($mode == 'view') +{ + $global_per_arry = getProfileGlobalPermission($profileId); + $view_all_per = $global_per_arry[1]; + $edit_all_per = $global_per_arry[2]; + $privileges_global[]=getGlobalDisplayValue($view_all_per,1); + $privileges_global[]=getGlobalDisplayValue($edit_all_per,2); +} +elseif($mode == 'edit') +{ + $global_per_arry = getProfileGlobalPermission($profileId); + $view_all_per = $global_per_arry[1]; + $edit_all_per = $global_per_arry[2]; + $privileges_global[]=getGlobalDisplayOutput($view_all_per,1); + $privileges_global[]=getGlobalDisplayOutput($edit_all_per,2); +} +elseif($mode == 'create') +{ + if($parentProfileId != '') + { + $global_per_arry = getProfileGlobalPermission($parentProfileId); + $view_all_per = $global_per_arry[1]; + $edit_all_per = $global_per_arry[2]; + $privileges_global[]=getGlobalDisplayOutput($view_all_per,1); + $privileges_global[]=getGlobalDisplayOutput($edit_all_per,2); + } + else + { + $privileges_global[]=getGlobalDisplayOutput(0,1); + $privileges_global[]=getGlobalDisplayOutput(0,2); + } + +} + +$smarty->assign("GLOBAL_PRIV",$privileges_global); + +//standard privileges +if($mode == 'view') +{ + $act_perr_arry = getTabsActionPermission($profileId); + foreach($act_perr_arry as $tabid=>$action_array) + { + $stand = array(); + $entity_name = getTabname($tabid); + //Create/Edit Permission + $tab_create_per_id = $action_array['1']; + $tab_create_per = getDisplayValue($tab_create_per_id,$tabid,'1'); + //Delete Permission + $tab_delete_per_id = $action_array['2']; + $tab_delete_per = getDisplayValue($tab_delete_per_id,$tabid,'2'); + //View Permission + $tab_view_per_id = $action_array['4']; + $tab_view_per = getDisplayValue($tab_view_per_id,$tabid,'4'); + + $stand[]=$entity_name; + $stand[]=$tab_create_per; + $stand[]=$tab_delete_per; + $stand[]=$tab_view_per; + $privileges_stand[$tabid]=$stand; + } +} +if($mode == 'edit') +{ + $act_perr_arry = getTabsActionPermission($profileId); + foreach($act_perr_arry as $tabid=>$action_array) + { + $stand = array(); + $entity_name = getTabname($tabid); + //Create/Edit Permission + $tab_create_per_id = $action_array['1']; + $tab_create_per = getDisplayOutput($tab_create_per_id,$tabid,'1'); + //Delete Permission + $tab_delete_per_id = $action_array['2']; + $tab_delete_per = getDisplayOutput($tab_delete_per_id,$tabid,'2'); + //View Permission + $tab_view_per_id = $action_array['4']; + $tab_view_per = getDisplayOutput($tab_view_per_id,$tabid,'4'); + + $stand[]=$entity_name; + $stand[]=$tab_create_per; + $stand[]=$tab_delete_per; + $stand[]=$tab_view_per; + $privileges_stand[$tabid]=$stand; + } +} +if($mode == 'create') +{ + if($parentProfileId != '') + { + $act_perr_arry = getTabsActionPermission($parentProfileId); + foreach($act_perr_arry as $tabid=>$action_array) + { + $stand = array(); + $entity_name = getTabname($tabid); + //Create/Edit Permission + $tab_create_per_id = $action_array['1']; + $tab_create_per = getDisplayOutput($tab_create_per_id,$tabid,'1'); + //Delete Permission + $tab_delete_per_id = $action_array['2']; + $tab_delete_per = getDisplayOutput($tab_delete_per_id,$tabid,'2'); + //View Permission + $tab_view_per_id = $action_array['4']; + $tab_view_per = getDisplayOutput($tab_view_per_id,$tabid,'4'); + + $stand[]=$entity_name; + $stand[]=$tab_create_per; + $stand[]=$tab_delete_per; + $stand[]=$tab_view_per; + $privileges_stand[$tabid]=$stand; + } + } + else + { + $act_perr_arry = getTabsActionPermission(1); + foreach($act_perr_arry as $tabid=>$action_array) + { + $stand = array(); + $entity_name = getTabname($tabid); + //Create/Edit Permission + $tab_create_per_id = $action_array['1']; + $tab_create_per = getDisplayOutput(0,$tabid,'1'); + //Delete Permission + $tab_delete_per_id = $action_array['2']; + $tab_delete_per = getDisplayOutput(0,$tabid,'2'); + //View Permission + $tab_view_per_id = $action_array['4']; + $tab_view_per = getDisplayOutput(0,$tabid,'4'); + + $stand[]=$entity_name; + $stand[]=$tab_create_per; + $stand[]=$tab_delete_per; + $stand[]=$tab_view_per; + $privileges_stand[$tabid]=$stand; + } + } + +} +$smarty->assign("STANDARD_PRIV",$privileges_stand); + +//tab Privileges + +if($mode == 'view') +{ + $tab_perr_array = getTabsPermission($profileId); + $no_of_tabs = sizeof($tab_perr_array); + foreach($tab_perr_array as $tabid=>$tab_perr) + { + $tab=array(); + $entity_name = getTabname($tabid); + $tab_allow_per_id = $tab_perr_array[$tabid]; + $tab_allow_per = getDisplayValue($tab_allow_per_id,$tabid,''); + $tab[]=$entity_name; + $tab[]=$tab_allow_per; + $privileges_tab[$tabid]=$tab; + } +} +if($mode == 'edit') +{ + $tab_perr_array = getTabsPermission($profileId); + $no_of_tabs = sizeof($tab_perr_array); + foreach($tab_perr_array as $tabid=>$tab_perr) + { + $tab=array(); + $entity_name = getTabname($tabid); + $tab_allow_per_id = $tab_perr_array[$tabid]; + $tab_allow_per = getDisplayOutput($tab_allow_per_id,$tabid,''); + $tab[]=$entity_name; + $tab[]=$tab_allow_per; + $privileges_tab[$tabid]=$tab; + } +} +if($mode == 'create') +{ + if($parentProfileId != '') + { + $tab_perr_array = getTabsPermission($parentProfileId); + $no_of_tabs = sizeof($tab_perr_array); + foreach($tab_perr_array as $tabid=>$tab_perr) + { + $tab=array(); + $entity_name = getTabname($tabid); + $tab_allow_per_id = $tab_perr_array[$tabid]; + $tab_allow_per = getDisplayOutput($tab_allow_per_id,$tabid,''); + $tab[]=$entity_name; + $tab[]=$tab_allow_per; + $privileges_tab[$tabid]=$tab; + } + } + else + { + $tab_perr_array = getTabsPermission(1); + $no_of_tabs = sizeof($tab_perr_array); + foreach($tab_perr_array as $tabid=>$tab_perr) + { + $tab=array(); + $entity_name = getTabname($tabid); + $tab_allow_per_id = $tab_perr_array[$tabid]; + $tab_allow_per = getDisplayOutput(0,$tabid,''); + $tab[]=$entity_name; + $tab[]=$tab_allow_per; + $privileges_tab[$tabid]=$tab; + } + } + +} +$smarty->assign("TAB_PRIV",$privileges_tab); +//utilities privileges + +if($mode == 'view') +{ + $act_utility_arry = getTabsUtilityActionPermission($profileId); + foreach($act_utility_arry as $tabid=>$action_array) + { + $util=array(); + $entity_name = getTabname($tabid); + $no_of_actions=sizeof($action_array); + foreach($action_array as $action_id=>$act_per) + { + $action_name = getActionname($action_id); + $tab_util_act_per = $action_array[$action_id]; + $tab_util_per = getDisplayValue($tab_util_act_per,$tabid,$action_id); + $util[]=$action_name; + $util[]=$tab_util_per; + } + $util=array_chunk($util,2); + $util=array_chunk($util,3); + $privilege_util[$tabid] = $util; + } +} +elseif($mode == 'edit') +{ + $act_utility_arry = getTabsUtilityActionPermission($profileId); + foreach($act_utility_arry as $tabid=>$action_array) + { + $util=array(); + $entity_name = getTabname($tabid); + $no_of_actions=sizeof($action_array); + foreach($action_array as $action_id=>$act_per) + { + $action_name = getActionname($action_id); + $tab_util_act_per = $action_array[$action_id]; + $tab_util_per = getDisplayOutput($tab_util_act_per,$tabid,$action_id); + $util[]=$action_name; + $util[]=$tab_util_per; + } + $util=array_chunk($util,2); + $util=array_chunk($util,3); + $privilege_util[$tabid] = $util; + } +} +elseif($mode == 'create') +{ + if($parentProfileId != '') + { + $act_utility_arry = getTabsUtilityActionPermission($parentProfileId); + foreach($act_utility_arry as $tabid=>$action_array) + { + $util=array(); + $entity_name = getTabname($tabid); + $no_of_actions=sizeof($action_array); + foreach($action_array as $action_id=>$act_per) + { + $action_name = getActionname($action_id); + $tab_util_act_per = $action_array[$action_id]; + $tab_util_per = getDisplayOutput($tab_util_act_per,$tabid,$action_id); + $util[]=$action_name; + $util[]=$tab_util_per; + } + $util=array_chunk($util,2); + $util=array_chunk($util,3); + $privilege_util[$tabid] = $util; + } + } + else + { + $act_utility_arry = getTabsUtilityActionPermission(1); + foreach($act_utility_arry as $tabid=>$action_array) + { + $util=array(); + $entity_name = getTabname($tabid); + $no_of_actions=sizeof($action_array); + foreach($action_array as $action_id=>$act_per) + { + $action_name = getActionname($action_id); + $tab_util_act_per = $action_array[$action_id]; + $tab_util_per = getDisplayOutput(0,$tabid,$action_id); + $util[]=$action_name; + $util[]=$tab_util_per; + } + $util=array_chunk($util,2); + $util=array_chunk($util,3); + $privilege_util[$tabid] = $util; + } + + } + +} +$smarty->assign("UTILITIES_PRIV",$privilege_util); + +//Field privileges +$modArr=getFieldModuleAccessArray(); + + +$no_of_mod=sizeof($modArr); +for($i=0;$i<$no_of_mod; $i++) +{ + $fldModule=key($modArr); + $lang_str=$modArr[$fldModule]; + $privilege_fld[]=$fldModule; + next($modArr); +} +$smarty->assign("PRI_FIELD_LIST",$privilege_fld); +$smarty->assign("MODE",$mode); + +$disable_field_array = Array(); +$sql_disablefield = "select * from vtiger_def_org_field"; +$result = $adb->pquery($sql_disablefield, array()); +$noofrows=$adb->num_rows($result); +for($i=0; $i<$noofrows; $i++) +{ + $FieldId = $adb->query_result($result,$i,'fieldid'); + $Visible = $adb->query_result($result,$i,'visible'); + $disable_field_array[$FieldId] = $Visible; +} + +if($mode=='view') +{ + $fieldListResult = getProfile2AllFieldList($modArr,$profileId); + for($i=0; $i"; + } + else + { + $visible = ""; + } + if($disable_field_array[$fieldListResult[$module_name][$j][4]] == 1) + { + $visible = ""; + } + if($language_strings[$fieldListResult[$module_name][$j][0]] != '') + $field[]=$language_strings[$fieldListResult[$module_name][$j][0]]; + else + $field[]=$fieldListResult[$module_name][$j][0]; + $field[]=$visible; + $field_module[]=$field; + } + $privilege_field[$module_id] = array_chunk($field_module,3); + next($fieldListResult); + } +} +elseif($mode=='edit') +{ + $fieldListResult = getProfile2AllFieldList($modArr,$profileId); + for($i=0; $i'; + $field_module[]=$field; + } + $privilege_field[$module_id] = array_chunk($field_module,3); + next($fieldListResult); + } +} +elseif($mode=='create') +{ + if($parentProfileId != '') + { + $fieldListResult = getProfile2AllFieldList($modArr,$parentProfileId); + for($i=0; $i'; + $field_module[]=$field; + } + $privilege_field[$module_id] = array_chunk($field_module,3); + next($fieldListResult); + } + } + else + { + $fieldListResult = getProfile2AllFieldList($modArr,1); + for($i=0; $i'; + $field_module[]=$field; + } + $privilege_field[$module_id] = array_chunk($field_module,3); + next($fieldListResult); + } + } +} + +$smarty->assign("FIELD_PRIVILEGES",$privilege_field); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +if($mode == 'view') + $smarty->display("ProfileDetailView.tpl"); +else + $smarty->display("EditProfile.tpl"); + +/** returns html image code based on the input id + * @param $id -- Role Name:: Type varchar + * @returns $value -- html image code:: Type varcha:w + * + */ +function getGlobalDisplayValue($id,$actionid) +{ + global $image_path; + if($id == '') + { + $value = ' '; + } + elseif($id == 0) + { + $value = ''; + } + elseif($id == 1) + { + $value = ''; + } + else + { + $value = ' '; + } + + return $value; + +} + + +/** returns html check box code based on the input id + * @param $id -- Role Name:: Type varchar + * @returns $value -- html check box code:: Type varcha:w + * + */ +function getGlobalDisplayOutput($id,$actionid) +{ + if($actionid == '1') + { + $name = 'view_all'; + } + elseif($actionid == '2') + { + + $name = 'edit_all'; + } + + if($id == '' && $id != 0) + { + $value = ''; + } + elseif($id == 0) + { + $value = ''; + } + elseif($id == 1) + { + $value = ''; + } + return $value; + +} + + +/** returns html image code based on the input id + * @param $id -- Role Name:: Type varchar + * @returns $value -- html image code:: Type varcha:w + * + */ +function getDisplayValue($id) +{ + global $image_path; + + if($id == '') + { + $value = ' '; + } + elseif($id == 0) + { + $value = ''; + } + elseif($id == 1) + { + $value = ''; + } + else + { + $value = ' '; + } + return $value; + +} + + +/** returns html check box code based on the input id + * @param $id -- Role Name:: Type varchar + * @returns $value -- html check box code:: Type varcha:w + * + */ +function getDisplayOutput($id,$tabid,$actionid) +{ + if($actionid == '') + { + $name = $tabid.'_tab'; + $ckbox_id = 'tab_chk_com_'.$tabid; + $jsfn = 'hideTab('.$tabid.')'; + } + else + { + $temp_name = getActionname($actionid); + $name = $tabid.'_'.$temp_name; + $ckbox_id = 'tab_chk_'.$actionid.'_'.$tabid; + if($actionid == 1) + $jsfn = 'unSelectCreate('.$tabid.')'; + elseif($actionid == 4) + $jsfn = 'unSelectView('.$tabid.')'; + elseif($actionid == 2) + $jsfn = 'unSelectDelete('.$tabid.')'; + else + { + $ckbox_id = $tabid.'_field_util_'.$actionid; + $jsfn = 'javascript:'; + } + } + + + + if($id == '' && $id != 0) + { + $value = ''; + } + elseif($id == 0) + { + $value = ''; + } + elseif($id == 1) + { + $value = ''; + } + return $value; + +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/saveemailtemplate.php b/oss/vtiger/trunk/modules/Settings/saveemailtemplate.php new file mode 100644 index 00000000..a3b611b3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/saveemailtemplate.php @@ -0,0 +1,41 @@ +info("the templateid is set"); + $sql = "update vtiger_emailtemplates set foldername =?, templatename =?, subject =?, description =?, body =? where templateid =?"; + $params = array($folderName, $templateName, $subject, $description, $body, $templateid); + $adb->pquery($sql, $params); + + $log->info("about to invoke the detailviewemailtemplate file"); + header("Location:index.php?module=Settings&action=detailviewemailtemplate&parenttab=Settings&templateid=".$templateid); +} +else +{ + $templateid = $db->getUniqueID('vtiger_emailtemplates'); + $sql = "insert into vtiger_emailtemplates values (?,?,?,?,?,?,?)"; + $params = array($folderName, $templateName, $subject, $description, $body, 0, $templateid); + $adb->pquery($sql, $params); + + $log->info("added to the db the emailtemplate"); + header("Location:index.php?module=Settings&action=detailviewemailtemplate&parenttab=Settings&templateid=".$templateid); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/savetermsandconditions.php b/oss/vtiger/trunk/modules/Settings/savetermsandconditions.php new file mode 100644 index 00000000..2e228b8e --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/savetermsandconditions.php @@ -0,0 +1,33 @@ +pquery($sql, array($inv_type)); +$inv_id = $adb->query_result($result,0,'id'); +if($inv_id == '') +{ + $inv_id=$adb->getUniqueID('vtiger_inventory_tandc'); + $sql="insert into vtiger_inventory_tandc values(?,?,?)"; + $params = array($inv_id, $inv_type, $inv_tandc); +} +else +{ + $sql="update vtiger_inventory_tandc set type = ?, tandc = ? where id = ?"; + $params = array($inv_type, $inv_tandc, $inv_id); +} +$adb->pquery($sql, $params); + +header("Location: index.php?module=Settings&action=OrganizationTermsandConditions&parenttab=Settings"); +?> diff --git a/oss/vtiger/trunk/modules/Settings/savewordtemplate.php b/oss/vtiger/trunk/modules/Settings/savewordtemplate.php new file mode 100644 index 00000000..e334fd51 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/savewordtemplate.php @@ -0,0 +1,144 @@ +getUniqueID("vtiger_wordtemplates"); + if($genQueryId != '') { + if($result!=false && $savefile=="true") { + $module = vtlib_purify($_REQUEST['target_module']); + $sql = "INSERT INTO vtiger_wordtemplates "; + $sql .= "(templateid,module,date_entered,parent_type,data,description,filename,filesize,filetype) values (?,?,?,?,?,?,?,?,?)"; + $params = array($genQueryId, $module, $adb->formatDate($date_entered, true), $parent_type, $adb->getEmptyBlob(false), $strDescription, $filename, $filesize, $filetype); + $result = $adb->pquery($sql, $params); + + $result = $adb->updateBlob('vtiger_wordtemplates','data'," filename='". $adb->sql_escape_string($filename) ."'",$data); + deleteFile($uploaddir,$filename); + header("Location: index.php?action=listwordtemplates&module=Settings&parenttab=Settings"); + } elseif($savefile=="false") { + $module = vtlib_purify($_REQUEST['target_module']); + header("Location: index.php?action=upload&module=Settings&parenttab=Settings&flag=".$error_flag."&description=".$strDescription."&tempModule=".$module); + } else { + include('themes/'.$theme.'/header.php'); + $errormessage = "Error Message
      +
    • Invalid file OR +
    • File has no data +

    " ; + echo $errormessage; + deleteFile($uploaddir,$filename); + include "upload.php"; + } + } + } + //Added for Invaild file path + else + { + $module = vtlib_purify($_REQUEST['target_module']); + header("Location: index.php?action=upload&module=Settings&parenttab=Settings&flag=2&description=".$strDescription."&tempModule=".$module); + + } + +} +else +{ + $errorCode = $_FILES['binFile']['error']; + if($errorCode == 4) + { + include('themes/'.$theme.'/header.php'); + include "upload.php"; + // $errormessage = "Kindly give a valid file for upload!
    " ; + echo ""; + } + else if($errorCode == 2) + { + include('themes/'.$theme.'/header.php'); + include "upload.php"; + //$errormessage = "Sorry, the uploaded file exceeds the maximum filesize limit. Please try a smaller file
    "; + echo ""; + //echo $errormessage; + //echo $errorCode; + } + elseif($errorCode == 1) + { + include('themes/'.$theme.'/header.php'); + include "upload.php"; + echo ""; + } + else if($errorCode == 3) + { + include('themes/'.$theme.'/header.php'); + include "upload.php"; + echo ""; + + } + +} + +function deleteFile($dir,$filename) +{ + unlink($dir.$filename); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/upload.php b/oss/vtiger/trunk/modules/Settings/upload.php new file mode 100644 index 00000000..016bd4d2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Settings/upload.php @@ -0,0 +1,65 @@ +';print_r($_REQUEST);echo ''; +if(isset($_REQUEST['flag']) && $_REQUEST['flag'] != '') +{ + $flag = $_REQUEST['flag']; + switch($flag) + { + case 1: + $smarty->assign("ERRORFLAG","".$mod_strings['LBL_DOC_MSWORD'].""); + break; + case 2: + $smarty->assign("ERRORFLAG","".$mod_strings['LBL_NODOC'].""); + break; + default: + $smarty->assign("ERRORFLAG",""); + break; + } +} + +$tempModule=$_REQUEST['tempModule']; +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("UMOD", $mod_strings); +$smarty->assign("PARENTTAB", getParentTab()); +$smarty->assign("MAX_FILE_SIZE", $upload_maxsize); + +$template = Array( + "Leads"=>"LEADS_SELECTED", + "Accounts"=>"ACCOUNTS_SELECTED", + "Contacts"=>"CONTACTS_SELECTED", + "HelpDesk"=>"HELPDESK_SELECTED" + ); + +$smarty->assign($template[$tempModule],"selected"); + +$smarty->display('CreateWordTemplate.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Settings/vtigerCRM.CAB b/oss/vtiger/trunk/modules/Settings/vtigerCRM.CAB new file mode 100644 index 00000000..0b569ecf Binary files /dev/null and b/oss/vtiger/trunk/modules/Settings/vtigerCRM.CAB differ diff --git a/oss/vtiger/trunk/modules/System/SystemAjax.php b/oss/vtiger/trunk/modules/System/SystemAjax.php new file mode 100644 index 00000000..de74ef2f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/SystemAjax.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/System/config.php b/oss/vtiger/trunk/modules/System/config.php new file mode 100644 index 00000000..ff475243 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/config.php @@ -0,0 +1,96 @@ + diff --git a/oss/vtiger/trunk/modules/System/distros.ini b/oss/vtiger/trunk/modules/System/distros.ini new file mode 100644 index 00000000..890f71c3 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/distros.ini @@ -0,0 +1,60 @@ +; linux-distros.ini - Defines known linux distros for phpSysInfo. +; http://phpsysinfo.sourceforge.net/ +; $Id: distros.ini,v 1.1 2005/11/22 14:30:28 bigmichi1 Exp $ +; + +[Debian] +Name = "Debian" +Image = "Debian.png" +Files = "/etc/debian_release;/etc/debian_version" + +[Suse] +Image = "Suse.png" +Files = "/etc/SuSE-release;/etc/UnitedLinux-release" + +[Mandrage] +Image = "Mandrake.png" +Files = "/etc/mandrake-release" + +[Gentoo] +Image = "Gentoo.png" +Files = "/etc/gentoo-release" + +[RedHat] +Image = "Redhat.png" +Files = "/etc/redhat-release;/etc/redhat_version" + +[Fedora] +Image = "Fedora.png" +Files = "/etc/fedora-release" + +[Slackware] +Image = "Slackware.png" +Files = "/etc/slackware-release;/etc/slackware-version" + +[Trustix] +Image = "Trustix.gif" +Files = "/etc/trustix-release;/etc/trustix-version" + +[FreeEOS] +Image = "free-eos.png" +Files = "/etc/eos-version" + +[Arch] +Image = "Arch.gif" +Files = "/etc/gentoo-release" + +[Cobalt] +Image = "Cobalt.png" +Files = "/etc/cobalt-release" + +[LinuxFromScratch] +Image = "lsf.png" +Files = "/etc/lfs-release" + +[Rubix] +Image = "Rubix.png" +Files = "/etc/rubix-version" + +[Ubunto] +Files = "/etc/lsb-release" diff --git a/oss/vtiger/trunk/modules/System/images/Arch.gif b/oss/vtiger/trunk/modules/System/images/Arch.gif new file mode 100644 index 00000000..a643b2da Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Arch.gif differ diff --git a/oss/vtiger/trunk/modules/System/images/Cobalt.png b/oss/vtiger/trunk/modules/System/images/Cobalt.png new file mode 100644 index 00000000..b992ed24 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Cobalt.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Darwin.png b/oss/vtiger/trunk/modules/System/images/Darwin.png new file mode 100644 index 00000000..a4d8d2de Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Darwin.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Debian.png b/oss/vtiger/trunk/modules/System/images/Debian.png new file mode 100644 index 00000000..03ae2020 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Debian.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Fedora.png b/oss/vtiger/trunk/modules/System/images/Fedora.png new file mode 100644 index 00000000..b0aa8d09 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Fedora.png differ diff --git a/oss/vtiger/trunk/modules/System/images/FreeBSD.png b/oss/vtiger/trunk/modules/System/images/FreeBSD.png new file mode 100644 index 00000000..4c271fc5 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/FreeBSD.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Gentoo.png b/oss/vtiger/trunk/modules/System/images/Gentoo.png new file mode 100644 index 00000000..9b016305 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Gentoo.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Mandrake.png b/oss/vtiger/trunk/modules/System/images/Mandrake.png new file mode 100644 index 00000000..09ccd20a Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Mandrake.png differ diff --git a/oss/vtiger/trunk/modules/System/images/NetBSD.png b/oss/vtiger/trunk/modules/System/images/NetBSD.png new file mode 100644 index 00000000..306ce773 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/NetBSD.png differ diff --git a/oss/vtiger/trunk/modules/System/images/OpenBSD.png b/oss/vtiger/trunk/modules/System/images/OpenBSD.png new file mode 100644 index 00000000..84da5c78 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/OpenBSD.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Redhat.png b/oss/vtiger/trunk/modules/System/images/Redhat.png new file mode 100644 index 00000000..6dc74971 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Redhat.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Rubix.png b/oss/vtiger/trunk/modules/System/images/Rubix.png new file mode 100644 index 00000000..50cbcbf9 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Rubix.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Slackware.png b/oss/vtiger/trunk/modules/System/images/Slackware.png new file mode 100644 index 00000000..dd94b527 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Slackware.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Suse.png b/oss/vtiger/trunk/modules/System/images/Suse.png new file mode 100644 index 00000000..6baf76de Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Suse.png differ diff --git a/oss/vtiger/trunk/modules/System/images/Trustix.gif b/oss/vtiger/trunk/modules/System/images/Trustix.gif new file mode 100644 index 00000000..6cdc3efd Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/Trustix.gif differ diff --git a/oss/vtiger/trunk/modules/System/images/free-eos.png b/oss/vtiger/trunk/modules/System/images/free-eos.png new file mode 100644 index 00000000..ade5c03a Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/free-eos.png differ diff --git a/oss/vtiger/trunk/modules/System/images/lfs.png b/oss/vtiger/trunk/modules/System/images/lfs.png new file mode 100644 index 00000000..e5944600 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/lfs.png differ diff --git a/oss/vtiger/trunk/modules/System/images/unknown.png b/oss/vtiger/trunk/modules/System/images/unknown.png new file mode 100644 index 00000000..54dc5b47 Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/unknown.png differ diff --git a/oss/vtiger/trunk/modules/System/images/xp.gif b/oss/vtiger/trunk/modules/System/images/xp.gif new file mode 100644 index 00000000..bd97897d Binary files /dev/null and b/oss/vtiger/trunk/modules/System/images/xp.gif differ diff --git a/oss/vtiger/trunk/modules/System/includes/XPath.class.php b/oss/vtiger/trunk/modules/System/includes/XPath.class.php new file mode 100644 index 00000000..f05397f0 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/XPath.class.php @@ -0,0 +1,6355 @@ + + * | Started around 2001-07, saved phpxml from near death and renamed to Php.XPath + * | Restructured XPath code to stay in line with XPath spec. + * | Sam Blum + * | Started around 2001-09 1st major restruct (V2.0) and testbench initiator. + * | 2nd (V3.0) major rewrite in 2002-02 + * | Daniel Allen + * | Started around 2001-10 working to make Php.XPath adhere to specs + * | Main Former Author: Michael P. Mehl + * | Inital creator of V 1.0. Stoped activities around 2001-03 + * +------------------------------------------------------------------------------------------------------+ + * | Code Structure: + * | --------------_ + * | The class is split into 3 main objects. To keep usability easy all 3 + * | objects are in this file (but may be split in 3 file in future). + * | +-------------+ + * | | XPathBase | XPathBase holds general and debugging functions. + * | +------+------+ + * | v + * | +-------------+ XPathEngine is the implementation of the W3C XPath spec. It contains the + * | | XPathEngine | XML-import (parser), -export and can handle xPathQueries. It's a fully + * | +------+------+ functional class but has no functions to modify the XML-document (see following). + * | v + * | +-------------+ + * | | XPath | XPath extends the functionality with actions to modify the XML-document. + * | +-------------+ We tryed to implement a DOM - like interface. + * +------------------------------------------------------------------------------------------------------+ + * | Usage: + * | ------ + * | Scroll to the end of this php file and you will find a short sample code to get you started + * +------------------------------------------------------------------------------------------------------+ + * | Glossary: + * | --------- + * | To understand how to use the functions and to pass the right parameters, read following: + * | + * | Document: (full node tree, XML-tree) + * | After a XML-source has been imported and parsed, it's stored as a tree of nodes sometimes + * | refered to as 'document'. + * | + * | AbsoluteXPath: (xPath, xPathSet) + * | A absolute XPath is a string. It 'points' to *one* node in the XML-document. We use the + * | term 'absolute' to emphasise that it is not an xPath-query (see xPathQuery). A valid xPath + * | has the form like '/AAA[1]/BBB[2]/CCC[1]'. Usually functions that require a node (see Node) + * | will also accept an abs. XPath. + * | + * | Node: (node, nodeSet, node-tree) + * | Some funtions require or return a node (or a whole node-tree). Nodes are only used with the + * | XPath-interface and have an internal structure. Every node in a XML document has a unique + * | corresponding abs. xPath. That's why public functions that accept a node, will usually also + * | accept a abs. xPath (a string) 'pointing' to an existing node (see absolutXPath). + * | + * | XPathQuery: (xquery, query) + * | A xPath-query is a string that is matched against the XML-document. The result of the match + * | is a xPathSet (vector of xPath's). It's always possible to pass a single absoluteXPath + * | instead of a xPath-query. A valid xPathQuery could look like this: + * | '//XXX/*[contains(., "foo")]/..' (See the link in 'What Is XPath' to learn more). + * | + * | + * +------------------------------------------------------------------------------------------------------+ + * | Internals: + * | ---------- + * | - The Node Tree + * | ------------- + * | A central role of the package is how the XML-data is stored. The whole data is in a node-tree. + * | A node can be seen as the equvalent to a tag in the XML soure with some extra info. + * | For instance the following XML + * | ****** + * | Would produce folowing node-tree: + * | 'super-root' <-- $nodeRoot (Very handy) + * | | + * | 'depth' 0 AAA[1] <-- top node. The 'textParts' of this node would be + * | / | \ 'textParts' => array('***','','**','*') + * | 'depth' 1 BBB[1] CCC[1] BBB[2] (NOTE: Is always size of child nodes+1) + * | - The Node + * | -------- + * | The node itself is an structure desiged mainly to be used in connection with the interface of PHP.XPath. + * | That means it's possible for functions to return a sub-node-tree that can be used as input of an other + * | PHP.XPath function. + * | + * | The main structure of a node is: + * | $node = array( + * | 'name' => '', # The tag name. E.g. In it would be 'FOO' + * | 'attributes' => array(), # The attributes of the tag E.g. In it would be array('bar'=>'aaa') + * | 'textParts' => array(), # Array of text parts surrounding the children E.g. aabbccdd -> array('aa','bb','cc','dd') + * | 'childNodes' => array(), # Array of refences (pointers) to child nodes. + * | + * | For optimisation reasions some additional data is stored in the node too: + * | 'parentNode' => NULL # Reference (pointer) to the parent node (or NULL if it's 'super root') + * | 'depth' => 0, # The tag depth (or tree level) starting with the root tag at 0. + * | 'pos' => 0, # Is the zero-based position this node has in the parent's 'childNodes'-list. + * | 'contextPos' => 1, # Is the one-based position this node has by counting the siblings tags (tags with same name) + * | 'xpath' => '' # Is the abs. XPath to this node. + * | 'generated_id'=> '' # The id returned for this node by generate-id() (attribute and text nodes not supported) + * | + * | - The NodeIndex + * | ------------- + * | Every node in the tree has an absolute XPath. E.g '/AAA[1]/BBB[2]' the $nodeIndex is a hash array + * | to all the nodes in the node-tree. The key used is the absolute XPath (a string). + * | + * +------------------------------------------------------------------------------------------------------+ + * | License: + * | -------- + * | The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); + * | you may not use this file except in compliance with the License. You may obtain a copy of the + * | License at http://www.mozilla.org/MPL/ + * | + * | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY + * | OF ANY KIND, either express or implied. See the License for the specific language governing + * | rights and limitations under the License. + * | + * | The Original Code is . + * | + * | The Initial Developer of the Original Code is Michael P. Mehl. Portions created by Michael + * | P. Mehl are Copyright (C) 2001 Michael P. Mehl. All Rights Reserved. + * | + * | Contributor(s): N.Swinson / S.Blum / D.Allen + * | + * | Alternatively, the contents of this file may be used under the terms of either of the GNU + * | General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public + * | License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the + * | LGPL License are applicable instead of those above. If you wish to allow use of your version + * | of this file only under the terms of the GPL or the LGPL License and not to allow others to + * | use your version of this file under the MPL, indicate your decision by deleting the + * | provisions above and replace them with the notice and other provisions required by the + * | GPL or the LGPL License. If you do not delete the provisions above, a recipient may use + * | your version of this file under either the MPL, the GPL or the LGPL License. + * | + * +======================================================================================================+ + * + * @author S.Blum / N.Swinson / D.Allen / (P.Mehl) + * @link http://sourceforge.net/projects/phpxpath/ + * @version 3.5 + * @CVS $Id: XPath.class.php,v 1.9 2005/11/16 17:26:05 bigmichi1 Exp $ + */ + +// Include guard, protects file being included twice +$ConstantName = 'INCLUDED_'.strtoupper(__FILE__); +if (defined($ConstantName)) return; +define($ConstantName,1, TRUE); + +/************************************************************************************************ +* =============================================================================================== +* X P a t h B a s e - Class +* =============================================================================================== +************************************************************************************************/ +class XPathBase { + var $_lastError; + + // As debugging of the xml parse is spread across several functions, we need to make this a member. + var $bDebugXmlParse = FALSE; + + // do we want to do profiling? + var $bClassProfiling = FALSE; + + // Used to help navigate through the begin/end debug calls + var $iDebugNextLinkNumber = 1; + var $aDebugOpenLinks = array(); + var $aDebugFunctions = array( + //'_evaluatePrimaryExpr', + //'_evaluateExpr', + //'_evaluateStep', + //'_checkPredicates', + //'_evaluateFunction', + //'_evaluateOperator', + //'_evaluatePathExpr', + ); + + /** + * Constructor + */ + function XPathBase() { + # $this->bDebugXmlParse = TRUE; + $this->properties['verboseLevel'] = 1; // 0=silent, 1 and above produce verbose output (an echo to screen). + + if (!isSet($_ENV)) { // Note: $_ENV introduced in 4.1.0. In earlier versions, use $HTTP_ENV_VARS. + $_ENV = $GLOBALS['HTTP_ENV_VARS']; + } + + // Windows 95/98 do not support file locking. Detecting OS (Operation System) and setting the + // properties['OS_supports_flock'] to FALSE if win 95/98 is detected. + // This will surpress the file locking error reported from win 98 users when exportToFile() is called. + // May have to add more OS's to the list in future (Macs?). + // ### Note that it's only the FAT and NFS file systems that are really a problem. NTFS and + // the latest php libs do support flock() + $_ENV['OS'] = isSet($_ENV['OS']) ? $_ENV['OS'] : 'Unknown OS'; + switch ($_ENV['OS']) { + case 'Windows_95': + case 'Windows_98': + case 'Unknown OS': + // should catch Mac OS X compatible environment + if (!empty($_SERVER['SERVER_SOFTWARE']) + && preg_match('/Darwin/',$_SERVER['SERVER_SOFTWARE'])) { + // fall-through + } else { + $this->properties['OS_supports_flock'] = FALSE; + break; + } + default: + $this->properties['OS_supports_flock'] = TRUE; + } + } + + + /** + * Resets the object so it's able to take a new xml sting/file + * + * Constructing objects is slow. If you can, reuse ones that you have used already + * by using this reset() function. + */ + function reset() { + $this->_lastError = ''; + } + + //----------------------------------------------------------------------------------------- + // XPathBase ------ Helpers ------ + //----------------------------------------------------------------------------------------- + + /** + * This method checks the right amount and match of brackets + * + * @param $term (string) String in which is checked. + * @return (bool) TRUE: OK / FALSE: KO + */ + function _bracketsCheck($term) { + $leng = strlen($term); + $brackets = 0; + $bracketMisscount = $bracketMissmatsh = FALSE; + $stack = array(); + for ($i=0; $i<$leng; $i++) { + switch ($term[$i]) { + case '(' : + case '[' : + $stack[$brackets] = $term[$i]; + $brackets++; + break; + case ')': + $brackets--; + if ($brackets<0) { + $bracketMisscount = TRUE; + break 2; + } + if ($stack[$brackets] != '(') { + $bracketMissmatsh = TRUE; + break 2; + } + break; + case ']' : + $brackets--; + if ($brackets<0) { + $bracketMisscount = TRUE; + break 2; + } + if ($stack[$brackets] != '[') { + $bracketMissmatsh = TRUE; + break 2; + } + break; + } + } + // Check whether we had a valid number of brackets. + if ($brackets != 0) $bracketMisscount = TRUE; + if ($bracketMisscount || $bracketMissmatsh) { + return FALSE; + } + return TRUE; + } + + /** + * Looks for a string within another string -- BUT the search-string must be located *outside* of any brackets. + * + * This method looks for a string within another string. Brackets in the + * string the method is looking through will be respected, which means that + * only if the string the method is looking for is located outside of + * brackets, the search will be successful. + * + * @param $term (string) String in which the search shall take place. + * @param $expression (string) String that should be searched. + * @return (int) This method returns -1 if no string was found, + * otherwise the offset at which the string was found. + */ + function _searchString($term, $expression) { + $bracketCounter = 0; // Record where we are in the brackets. + $leng = strlen($term); + $exprLeng = strlen($expression); + for ($i=0; $i<$leng; $i++) { + $char = $term[$i]; + if ($char=='(' || $char=='[') { + $bracketCounter++; + continue; + } + elseif ($char==')' || $char==']') { + $bracketCounter--; + } + if ($bracketCounter == 0) { + // Check whether we can find the expression at this index. + if (substr($term, $i, $exprLeng) == $expression) return $i; + } + } + // Nothing was found. + return (-1); + } + + /** + * Split a string by a searator-string -- BUT the separator-string must be located *outside* of any brackets. + * + * Returns an array of strings, each of which is a substring of string formed + * by splitting it on boundaries formed by the string separator. + * + * @param $separator (string) String that should be searched. + * @param $term (string) String in which the search shall take place. + * @return (array) see above + */ + function _bracketExplode($separator, $term) { + // Note that it doesn't make sense for $separator to itself contain (,),[ or ], + // but as this is a private function we should be ok. + $resultArr = array(); + $bracketCounter = 0; // Record where we are in the brackets. + do { // BEGIN try block + // Check if any separator is in the term + $sepLeng = strlen($separator); + if (strpos($term, $separator)===FALSE) { // no separator found so end now + $resultArr[] = $term; + break; // try-block + } + + // Make a substitute separator out of 'unused chars'. + $substituteSep = str_repeat(chr(2), $sepLeng); + + // Now determine the first bracket '(' or '['. + $tmp1 = strpos($term, '('); + $tmp2 = strpos($term, '['); + if ($tmp1===FALSE) { + $startAt = (int)$tmp2; + } elseif ($tmp2===FALSE) { + $startAt = (int)$tmp1; + } else { + $startAt = min($tmp1, $tmp2); + } + + // Get prefix string part before the first bracket. + $preStr = substr($term, 0, $startAt); + // Substitute separator in prefix string. + $preStr = str_replace($separator, $substituteSep, $preStr); + + // Now get the rest-string (postfix string) + $postStr = substr($term, $startAt); + // Go all the way through the rest-string. + $strLeng = strlen($postStr); + for ($i=0; $i < $strLeng; $i++) { + $char = $postStr[$i]; + // Spot (,),[,] and modify our bracket counter. Note there is an + // assumption here that you don't have a string(with[mis)matched]brackets. + // This should be ok as the dodgy string will be detected elsewhere. + if ($char=='(' || $char=='[') { + $bracketCounter++; + continue; + } + elseif ($char==')' || $char==']') { + $bracketCounter--; + } + // If no brackets surround us check for separator + if ($bracketCounter == 0) { + // Check whether we can find the expression starting at this index. + if ((substr($postStr, $i, $sepLeng) == $separator)) { + // Substitute the found separator + for ($j=0; $j<$sepLeng; $j++) { + $postStr[$i+$j] = $substituteSep[$j]; + } + } + } + } + // Now explod using the substitute separator as key. + $resultArr = explode($substituteSep, $preStr . $postStr); + } while (FALSE); // End try block + // Return the results that we found. May be a array with 1 entry. + return $resultArr; + } + + /** + * Split a string at it's groups, ie bracketed expressions + * + * Returns an array of strings, when concatenated together would produce the original + * string. ie a(b)cde(f)(g) would map to: + * array ('a', '(b)', cde', '(f)', '(g)') + * + * @param $string (string) The string to process + * @param $open (string) The substring for the open of a group + * @param $close (string) The substring for the close of a group + * @return (array) The parsed string, see above + */ + function _getEndGroups($string, $open='[', $close=']') { + // Note that it doesn't make sense for $separator to itself contain (,),[ or ], + // but as this is a private function we should be ok. + $resultArr = array(); + do { // BEGIN try block + // Check if we have both an open and a close tag + if (empty($open) and empty($close)) { // no separator found so end now + $resultArr[] = $string; + break; // try-block + } + + if (empty($string)) { + $resultArr[] = $string; + break; // try-block + } + + + while (!empty($string)) { + // Now determine the first bracket '(' or '['. + $openPos = strpos($string, $open); + $closePos = strpos($string, $close); + if ($openPos===FALSE || $closePos===FALSE) { + // Oh, no more groups to be found then. Quit + $resultArr[] = $string; + break; + } + + // Sanity check + if ($openPos > $closePos) { + // Malformed string, dump the rest and quit. + $resultArr[] = $string; + break; + } + + // Get prefix string part before the first bracket. + $preStr = substr($string, 0, $openPos); + // This is the first string that will go in our output + if (!empty($preStr)) + $resultArr[] = $preStr; + + // Skip over what we've proceed, including the open char + $string = substr($string, $openPos + 1 - strlen($string)); + + // Find the next open char and adjust our close char +//echo "close: $closePos\nopen: $openPos\n\n"; + $closePos -= $openPos + 1; + $openPos = strpos($string, $open); +//echo "close: $closePos\nopen: $openPos\n\n"; + + // While we have found nesting... + while ($openPos && $closePos && ($closePos > $openPos)) { + // Find another close pos after the one we are looking at + $closePos = strpos($string, $close, $closePos + 1); + // And skip our open + $openPos = strpos($string, $open, $openPos + 1); + } +//echo "close: $closePos\nopen: $openPos\n\n"; + + // If we now have a close pos, then it's the end of the group. + if ($closePos === FALSE) { + // We didn't... so bail dumping what was left + $resultArr[] = $open.$string; + break; + } + + // We did, so we can extract the group + $resultArr[] = $open.substr($string, 0, $closePos + 1); + // Skip what we have processed + $string = substr($string, $closePos + 1); + } + } while (FALSE); // End try block + // Return the results that we found. May be a array with 1 entry. + return $resultArr; + } + + /** + * Retrieves a substring before a delimiter. + * + * This method retrieves everything from a string before a given delimiter, + * not including the delimiter. + * + * @param $string (string) String, from which the substring should be extracted. + * @param $delimiter (string) String containing the delimiter to use. + * @return (string) Substring from the original string before the delimiter. + * @see _afterstr() + */ + function _prestr(&$string, $delimiter, $offset=0) { + // Return the substring. + $offset = ($offset<0) ? 0 : $offset; + $pos = strpos($string, $delimiter, $offset); + if ($pos===FALSE) return $string; else return substr($string, 0, $pos); + } + + /** + * Retrieves a substring after a delimiter. + * + * This method retrieves everything from a string after a given delimiter, + * not including the delimiter. + * + * @param $string (string) String, from which the substring should be extracted. + * @param $delimiter (string) String containing the delimiter to use. + * @return (string) Substring from the original string after the delimiter. + * @see _prestr() + */ + function _afterstr($string, $delimiter, $offset=0) { + $offset = ($offset<0) ? 0 : $offset; + // Return the substring. + return substr($string, strpos($string, $delimiter, $offset) + strlen($delimiter)); + } + + //----------------------------------------------------------------------------------------- + // XPathBase ------ Debug Stuff ------ + //----------------------------------------------------------------------------------------- + + /** + * Alter the verbose (error) level reporting. + * + * Pass an int. >0 to turn on, 0 to turn off. The higher the number, the + * higher the level of verbosity. By default, the class has a verbose level + * of 1. + * + * @param $levelOfVerbosity (int) default is 1 = on + */ + function setVerbose($levelOfVerbosity = 1) { + $level = -1; + if ($levelOfVerbosity === TRUE) { + $level = 1; + } elseif ($levelOfVerbosity === FALSE) { + $level = 0; + } elseif (is_numeric($levelOfVerbosity)) { + $level = $levelOfVerbosity; + } + if ($level >= 0) $this->properties['verboseLevel'] = $levelOfVerbosity; + } + + /** + * Returns the last occured error message. + * + * @access public + * @return string (may be empty if there was no error at all) + * @see _setLastError(), _lastError + */ + function getLastError() { + return $this->_lastError; + } + + /** + * Creates a textual error message and sets it. + * + * example: 'XPath error in THIS_FILE_NAME:LINE. Message: YOUR_MESSAGE'; + * + * I don't think the message should include any markup because not everyone wants to debug + * into the browser window. + * + * You should call _displayError() rather than _setLastError() if you would like the message, + * dependant on their verbose settings, echoed to the screen. + * + * @param $message (string) a textual error message default is '' + * @param $line (int) the line number where the error occured, use __LINE__ + * @see getLastError() + */ + function _setLastError($message='', $line='-', $file='-') { + $this->_lastError = 'XPath error in ' . basename($file) . ':' . $line . '. Message: ' . $message; + } + + /** + * Displays an error message. + * + * This method displays an error messages depending on the users verbose settings + * and sets the last error message. + * + * If also possibly stops the execution of the script. + * ### Terminate should not be allowed --fab. Should it?? N.S. + * + * @param $message (string) Error message to be displayed. + * @param $lineNumber (int) line number given by __LINE__ + * @param $terminate (bool) (default TURE) End the execution of this script. + */ + function _displayError($message, $lineNumber='-', $file='-', $terminate=TRUE) { + // Display the error message. + $err = 'XPath error in '.basename($file).':'.$lineNumber.' '.$message."
    \n"; + $this->_setLastError($message, $lineNumber, $file); + if (($this->properties['verboseLevel'] > 0) OR ($terminate)) echo $err; + // End the execution of this script. + if ($terminate) exit; + } + + /** + * Displays a diagnostic message + * + * This method displays an error messages + * + * @param $message (string) Error message to be displayed. + * @param $lineNumber (int) line number given by __LINE__ + */ + function _displayMessage($message, $lineNumber='-', $file='-') { + // Display the error message. + $err = 'XPath message from '.basename($file).':'.$lineNumber.' '.$message."
    \n"; + if ($this->properties['verboseLevel'] > 0) echo $err; + } + + /** + * Called to begin the debug run of a function. + * + * This method starts a
     tag so that the entry to this function
    +   * is clear to the debugging user.  Call _closeDebugFunction() at the
    +   * end of the function to create a clean box round the function call.
    +   *
    +   * @author    Nigel Swinson 
    +   * @author    Sam   Blum    
    +   * @param     $functionName (string) the name of the function we are beginning to debug
    +   * @param     $bDebugFlag   (bool) TRUE if we are to draw a call stack, FALSE otherwise
    +   * @return                  (array)  the output from the microtime() function.
    +   * @see       _closeDebugFunction()
    +   */
    +  function _beginDebugFunction($functionName, $bDebugFlag) {
    +    if ($bDebugFlag) {
    +      $fileName = basename(__FILE__);
    +      static $color = array('green','blue','red','lime','fuchsia', 'aqua');
    +      static $colIndex = -1;
    +      $colIndex++;
    +      echo '
    '; + echo '
    ';
    +      echo 'Function Close '.$this->iDebugNextLinkNumber.'';
    +      echo "{$fileName} : {$functionName}";
    +      echo '
    '; + array_push($this->aDebugOpenLinks, $this->iDebugNextLinkNumber); + $this->iDebugNextLinkNumber++; + } + + if ($this->bClassProfiling) + $this->_ProfBegin($FunctionName); + + return TRUE; + } + + /** + * Called to end the debug run of a function. + * + * This method ends a
     block and reports the time since $aStartTime
    +   * is clear to the debugging user.
    +   *
    +   * @author    Nigel Swinson 
    +   * @param     $functionName (string) the name of the function we are beginning to debug
    +   * @param     $return_value (mixed) the return value from the function call that 
    +   *                                  we are debugging
    +   * @param     $bDebugFlag   (bool) TRUE if we are to draw a call stack, FALSE otherwise
    +   */
    +  function _closeDebugFunction($functionName, $returnValue = "", $bDebugFlag) {
    +    if ($bDebugFlag) {
    +      echo "
    "; + $iOpenLinkNumber = array_pop($this->aDebugOpenLinks); + echo 'Function Open '.$iOpenLinkNumber.''; + if (isSet($returnValue)) { + if (is_array($returnValue)) + echo "Return Value: ".print_r($returnValue)."\n"; + else if (is_numeric($returnValue)) + echo "Return Value: ".(string)$returnValue."\n"; + else if (is_bool($returnValue)) + echo "Return Value: ".($returnValue ? "TRUE" : "FALSE")."\n"; + else + echo "Return Value: \"".htmlspecialchars($returnValue)."\"\n"; + } + echo '
    '; + echo " \n
    "; + } + + if ($this->bClassProfiling) + $this->_ProfEnd($FunctionName); + + return TRUE; + } + + /** + * Profile begin call + */ + function _ProfBegin($sonFuncName) { + static $entryTmpl = array ( 'start' => array(), + 'recursiveCount' => 0, + 'totTime' => 0, + 'callCount' => 0 ); + $now = explode(' ', microtime()); + + if (empty($this->callStack)) { + $fatherFuncName = ''; + } + else { + $fatherFuncName = $this->callStack[sizeOf($this->callStack)-1]; + $fatherEntry = &$this->profile[$fatherFuncName]; + } + $this->callStack[] = $sonFuncName; + + if (!isSet($this->profile[$sonFuncName])) { + $this->profile[$sonFuncName] = $entryTmpl; + } + + $sonEntry = &$this->profile[$sonFuncName]; + $sonEntry['callCount']++; + // if we call the t's the same function let the time run, otherwise sum up + if ($fatherFuncName == $sonFuncName) { + $sonEntry['recursiveCount']++; + } + if (!empty($fatherFuncName)) { + $last = $fatherEntry['start']; + $fatherEntry['totTime'] += round( (($now[1] - $last[1]) + ($now[0] - $last[0]))*10000 ); + $fatherEntry['start'] = 0; + } + $sonEntry['start'] = explode(' ', microtime()); + } + + /** + * Profile end call + */ + function _ProfEnd($sonFuncName) { + $now = explode(' ', microtime()); + + array_pop($this->callStack); + if (empty($this->callStack)) { + $fatherFuncName = ''; + } + else { + $fatherFuncName = $this->callStack[sizeOf($this->callStack)-1]; + $fatherEntry = &$this->profile[$fatherFuncName]; + } + $sonEntry = &$this->profile[$sonFuncName]; + if (empty($sonEntry)) { + echo "ERROR in profEnd(): '$funcNam' not in list. Seams it was never started ;o)"; + } + + $last = $sonEntry['start']; + $sonEntry['totTime'] += round( (($now[1] - $last[1]) + ($now[0] - $last[0]))*10000 ); + $sonEntry['start'] = 0; + if (!empty($fatherEntry)) $fatherEntry['start'] = explode(' ', microtime()); + } + + /** + * Show profile gathered so far as HTML table + */ + function _ProfileToHtml() { + $sortArr = array(); + if (empty($this->profile)) return ''; + reset($this->profile); + while (list($funcName) = each($this->profile)) { + $sortArrKey[] = $this->profile[$funcName]['totTime']; + $sortArrVal[] = $funcName; + } + //echo '
    ';var_dump($sortArrVal);echo '
    '; + array_multisort ($sortArrKey, SORT_DESC, $sortArrVal ); + //echo '
    ';var_dump($sortArrVal);echo '
    '; + + $totTime = 0; + $size = sizeOf($sortArrVal); + for ($i=0; $i<$size; $i++) { + $funcName = &$sortArrVal[$i]; + $totTime += $this->profile[$funcName]['totTime']; + } + $out = ''; + $out .=''; + for ($i=0; $i<$size; $i++) { + $funcName = &$sortArrVal[$i]; + $row = &$this->profile[$funcName]; + $procent = round($row['totTime']*100/$totTime); + if ($procent>20) $bgc = '#ff8080'; + elseif ($procent>15) $bgc = '#ff9999'; + elseif ($procent>10) $bgc = '#ffcccc'; + elseif ($procent>5) $bgc = '#ffffcc'; + else $bgc = '#66ff99'; + + $out .=""; + $out .=''; + $out .=''; + } + $out .= '
    Function % Total [ms]# Call[ms] per Call# Recursive
    '. $funcName .''. $procent .'% '.''. $row['totTime']/10 .''. $row['callCount'] .''. round($row['totTime']/10/$row['callCount'],2) .''. $row['recursiveCount'].'
    Total Time [' . $totTime/10 .'ms]' ; + + echo $out; + return TRUE; + } + + /** + * Echo an XPath context for diagnostic purposes + * + * @param $context (array) An XPath context + */ + function _printContext($context) { + echo "{$context['nodePath']}({$context['pos']}/{$context['size']})"; + } + + /** + * This is a debug helper function. It dumps the node-tree as HTML + * + * *QUICK AND DIRTY*. Needs some polishing. + * + * @param $node (array) A node + * @param $indent (string) (optional, default=''). For internal recursive calls. + */ + function _treeDump($node, $indent = '') { + $out = ''; + + // Get rid of recursion + $parentName = empty($node['parentNode']) ? "SUPER ROOT" : $node['parentNode']['name']; + unset($node['parentNode']); + $node['parentNode'] = $parentName ; + + $out .= "NODE[{$node['name']}]\n"; + + foreach($node as $key => $val) { + if ($key === 'childNodes') continue; + if (is_Array($val)) { + $out .= $indent . " [{$key}]\n" . arrayToStr($val, $indent . ' '); + } else { + $out .= $indent . " [{$key}] => '{$val}' \n"; + } + } + + if (!empty($node['childNodes'])) { + $out .= $indent . " ['childNodes'] (Size = ".sizeOf($node['childNodes']).")\n"; + foreach($node['childNodes'] as $key => $childNode) { + $out .= $indent . " [$key] => " . $this->_treeDump($childNode, $indent . ' ') . "\n"; + } + } + + if (empty($indent)) { + return "
    " . htmlspecialchars($out) . "
    "; + } + return $out; + } +} // END OF CLASS XPathBase + + +/************************************************************************************************ +* =============================================================================================== +* X P a t h E n g i n e - Class +* =============================================================================================== +************************************************************************************************/ + +class XPathEngine extends XPathBase { + + // List of supported XPath axes. + // What a stupid idea from W3C to take axes name containing a '-' (dash) + // NOTE: We replace the '-' with '_' to avoid the conflict with the minus operator. + // We will then do the same on the users Xpath querys + // -sibling => _sibling + // -or- => _or_ + // + // This array contains a list of all valid axes that can be evaluated in an + // XPath query. + var $axes = array ( 'ancestor', 'ancestor_or_self', 'attribute', 'child', 'descendant', + 'descendant_or_self', 'following', 'following_sibling', + 'namespace', 'parent', 'preceding', 'preceding_sibling', 'self' + ); + + // List of supported XPath functions. + // What a stupid idea from W3C to take function name containing a '-' (dash) + // NOTE: We replace the '-' with '_' to avoid the conflict with the minus operator. + // We will then do the same on the users Xpath querys + // starts-with => starts_with + // substring-before => substring_before + // substring-after => substring_after + // string-length => string_length + // + // This array contains a list of all valid functions that can be evaluated + // in an XPath query. + var $functions = array ( 'last', 'position', 'count', 'id', 'name', + 'string', 'concat', 'starts_with', 'contains', 'substring_before', + 'substring_after', 'substring', 'string_length', 'normalize_space', 'translate', + 'boolean', 'not', 'true', 'false', 'lang', 'number', 'sum', 'floor', + 'ceiling', 'round', 'x_lower', 'x_upper', 'generate_id' ); + + // List of supported XPath operators. + // + // This array contains a list of all valid operators that can be evaluated + // in a predicate of an XPath query. The list is ordered by the + // precedence of the operators (lowest precedence first). + var $operators = array( ' or ', ' and ', '=', '!=', '<=', '<', '>=', '>', + '+', '-', '*', ' div ', ' mod ', ' | '); + + // List of literals from the xPath string. + var $axPathLiterals = array(); + + // The index and tree that is created during the analysis of an XML source. + var $nodeIndex = array(); + var $nodeRoot = array(); + var $emptyNode = array( + 'name' => '', // The tag name. E.g. In it would be 'FOO' + 'attributes' => array(), // The attributes of the tag E.g. In it would be array('bar'=>'aaa') + 'childNodes' => array(), // Array of pointers to child nodes. + 'textParts' => array(), // Array of text parts between the cilderen E.g. aabbccdd -> array('aa','bb','cc','dd') + 'parentNode' => NULL, // Pointer to parent node or NULL if this node is the 'super root' + //-- *!* Following vars are set by the indexer and is for optimisation only *!* + 'depth' => 0, // The tag depth (or tree level) starting with the root tag at 0. + 'pos' => 0, // Is the zero-based position this node has in the parents 'childNodes'-list. + 'contextPos' => 1, // Is the one-based position this node has by counting the siblings tags (tags with same name) + 'xpath' => '' // Is the abs. XPath to this node. + ); + var $_indexIsDirty = FALSE; + + + // These variable used during the parse XML source + var $nodeStack = array(); // The elements that we have still to close. + var $parseStackIndex = 0; // The current element of the nodeStack[] that we are adding to while + // parsing an XML source. Corresponds to the depth of the xml node. + // in our input data. + var $parseOptions = array(); // Used to set the PHP's XML parser options (see xml_parser_set_option) + var $parsedTextLocation = ''; // A reference to where we have to put char data collected during XML parsing + var $parsInCData = 0 ; // Is >0 when we are inside a CDATA section. + var $parseSkipWhiteCache = 0; // A cache of the skip whitespace parse option to speed up the parse. + + // This is the array of error strings, to keep consistency. + var $errorStrings = array( + 'AbsoluteXPathRequired' => "The supplied xPath '%s' does not *uniquely* describe a node in the xml document.", + 'NoNodeMatch' => "The supplied xPath-query '%s' does not match *any* node in the xml document.", + 'RootNodeAlreadyExists' => "An xml document may have only one root node." + ); + + /** + * Constructor + * + * Optionally you may call this constructor with the XML-filename to parse and the + * XML option vector. Each of the entries in the option vector will be passed to + * xml_parser_set_option(). + * + * A option vector sample: + * $xmlOpt = array(XML_OPTION_CASE_FOLDING => FALSE, + * XML_OPTION_SKIP_WHITE => TRUE); + * + * @param $userXmlOptions (array) (optional) Vector of (=>, + * =>, ...). See PHP's + * xml_parser_set_option() docu for a list of possible + * options. + * @see importFromFile(), importFromString(), setXmlOptions() + */ + function XPathEngine($userXmlOptions=array()) { + parent::XPathBase(); + // Default to not folding case + $this->parseOptions[XML_OPTION_CASE_FOLDING] = FALSE; + // And not skipping whitespace + $this->parseOptions[XML_OPTION_SKIP_WHITE] = FALSE; + + // Now merge in the overrides. + // Don't use PHP's array_merge! + if (is_array($userXmlOptions)) { + foreach($userXmlOptions as $key => $val) $this->parseOptions[$key] = $val; + } + } + + /** + * Resets the object so it's able to take a new xml sting/file + * + * Constructing objects is slow. If you can, reuse ones that you have used already + * by using this reset() function. + */ + function reset() { + parent::reset(); + $this->properties['xmlFile'] = ''; + $this->parseStackIndex = 0; + $this->parsedTextLocation = ''; + $this->parsInCData = 0; + $this->nodeIndex = array(); + $this->nodeRoot = array(); + $this->nodeStack = array(); + $this->aLiterals = array(); + $this->_indexIsDirty = FALSE; + } + + + //----------------------------------------------------------------------------------------- + // XPathEngine ------ Get / Set Stuff ------ + //----------------------------------------------------------------------------------------- + + /** + * Returns the property/ies you want. + * + * if $param is not given, all properties will be returned in a hash. + * + * @param $param (string) the property you want the value of, or NULL for all the properties + * @return (mixed) string OR hash of all params, or NULL on an unknown parameter. + */ + function getProperties($param=NULL) { + $this->properties['hasContent'] = !empty($this->nodeRoot); + $this->properties['caseFolding'] = $this->parseOptions[XML_OPTION_CASE_FOLDING]; + $this->properties['skipWhiteSpaces'] = $this->parseOptions[XML_OPTION_SKIP_WHITE]; + + if (empty($param)) return $this->properties; + + if (isSet($this->properties[$param])) { + return $this->properties[$param]; + } else { + return NULL; + } + } + + /** + * Set an xml_parser_set_option() + * + * @param $optionID (int) The option ID (e.g. XML_OPTION_SKIP_WHITE) + * @param $value (int) The option value. + * @see XML parser functions in PHP doc + */ + function setXmlOption($optionID, $value) { + if (!is_numeric($optionID)) return; + $this->parseOptions[$optionID] = $value; + } + + /** + * Sets a number of xml_parser_set_option()s + * + * @param $userXmlOptions (array) An array of parser options. + * @see setXmlOption + */ + function setXmlOptions($userXmlOptions=array()) { + if (!is_array($userXmlOptions)) return; + foreach($userXmlOptions as $key => $val) { + $this->setXmlOption($key, $val); + } + } + + /** + * Alternative way to control whether case-folding is enabled for this XML parser. + * + * Short cut to setXmlOptions(XML_OPTION_CASE_FOLDING, TRUE/FALSE) + * + * When it comes to XML, case-folding simply means uppercasing all tag- + * and attribute-names (NOT the content) if set to TRUE. Note if you + * have this option set, then your XPath queries will also be case folded + * for you. + * + * @param $onOff (bool) (default TRUE) + * @see XML parser functions in PHP doc + */ + function setCaseFolding($onOff=TRUE) { + $this->parseOptions[XML_OPTION_CASE_FOLDING] = $onOff; + } + + /** + * Alternative way to control whether skip-white-spaces is enabled for this XML parser. + * + * Short cut to setXmlOptions(XML_OPTION_SKIP_WHITE, TRUE/FALSE) + * + * When it comes to XML, skip-white-spaces will trim the tag content. + * An XML file with no whitespace will be faster to process, but will make + * your data less human readable when you come to write it out. + * + * Running with this option on will slow the class down, so if you want to + * speed up your XML, then run it through once skipping white-spaces, then + * write out the new version of your XML without whitespace, then use the + * new XML file with skip whitespaces turned off. + * + * @param $onOff (bool) (default TRUE) + * @see XML parser functions in PHP doc + */ + function setSkipWhiteSpaces($onOff=TRUE) { + $this->parseOptions[XML_OPTION_SKIP_WHITE] = $onOff; + } + + /** + * Get the node defined by the $absoluteXPath. + * + * @param $absoluteXPath (string) (optional, default is 'super-root') xpath to the node. + * @return (array) The node, or FALSE if the node wasn't found. + */ + function &getNode($absoluteXPath='') { + if ($absoluteXPath==='/') $absoluteXPath = ''; + if (!isSet($this->nodeIndex[$absoluteXPath])) return FALSE; + if ($this->_indexIsDirty) $this->reindexNodeTree(); + return $this->nodeIndex[$absoluteXPath]; + } + + /** + * Get a the content of a node text part or node attribute. + * + * If the absolute Xpath references an attribute (Xpath ends with @ or attribute::), + * then the text value of that node-attribute is returned. + * Otherwise the Xpath is referencing a text part of the node. This can be either a + * direct reference to a text part (Xpath ends with text()[]) or indirect reference + * (a simple abs. Xpath to a node). + * 1) Direct Reference (xpath ends with text()[]): + * If the 'part-number' is omitted, the first text-part is assumed; starting by 1. + * Negative numbers are allowed, where -1 is the last text-part a.s.o. + * 2) Indirect Reference (a simple abs. Xpath to a node): + * Default is to return the *whole text*; that is the concated text-parts of the matching + * node. (NOTE that only in this case you'll only get a copy and changes to the returned + * value wounld have no effect). Optionally you may pass a parameter + * $textPartNr to define the text-part you want; starting by 1. + * Negative numbers are allowed, where -1 is the last text-part a.s.o. + * + * NOTE I : The returned value can be fetched by reference + * E.g. $text =& wholeText(). If you wish to modify the text. + * NOTE II: text-part numbers out of range will return FALSE + * SIDENOTE:The function name is a suggestion from W3C in the XPath specification level 3. + * + * @param $absoluteXPath (string) xpath to the node (See above). + * @param $textPartNr (int) If referring to a node, specifies which text part + * to query. + * @return (&string) A *reference* to the text if the node that the other + * parameters describe or FALSE if the node is not found. + */ + function &wholeText($absoluteXPath, $textPartNr=NULL) { + $status = FALSE; + $text = NULL; + if ($this->_indexIsDirty) $this->reindexNodeTree(); + + do { // try-block + if (preg_match(";(.*)/(attribute::|@)([^/]*)$;U", $absoluteXPath, $matches)) { + $absoluteXPath = $matches[1]; + $attribute = $matches[3]; + if (!isSet($this->nodeIndex[$absoluteXPath]['attributes'][$attribute])) { + $this->_displayError("The $absoluteXPath/attribute::$attribute value isn't a node in this document.", __LINE__, __FILE__, FALSE); + break; // try-block + } + $text =& $this->nodeIndex[$absoluteXPath]['attributes'][$attribute]; + $status = TRUE; + break; // try-block + } + + // Xpath contains a 'text()'-function, thus goes right to a text node. If so interpret the Xpath. + if (preg_match(":(.*)/text\(\)(\[(.*)\])?$:U", $absoluteXPath, $matches)) { + $absoluteXPath = $matches[1]; + + if (!isSet($this->nodeIndex[$absoluteXPath])) { + $this->_displayError("The $absoluteXPath value isn't a node in this document.", __LINE__, __FILE__, FALSE); + break; // try-block + } + + // Get the amount of the text parts in the node. + $textPartSize = sizeOf($this->nodeIndex[$absoluteXPath]['textParts']); + + // default to the first text node if a text node was not specified + $textPartNr = isSet($matches[2]) ? substr($matches[2],1,-1) : 1; + + // Support negative indexes like -1 === last a.s.o. + if ($textPartNr < 0) $textPartNr = $textPartSize + $textPartNr +1; + if (($textPartNr <= 0) OR ($textPartNr > $textPartSize)) { + $this->_displayError("The $absoluteXPath/text()[$textPartNr] value isn't a NODE in this document.", __LINE__, __FILE__, FALSE); + break; // try-block + } + $text =& $this->nodeIndex[$absoluteXPath]['textParts'][$textPartNr - 1]; + $status = TRUE; + break; // try-block + } + + // At this point we have been given an xpath with neither a 'text()' nor 'attribute::' axis at the end + // So we assume a get to text is wanted and use the optioanl fallback parameters $textPartNr + + if (!isSet($this->nodeIndex[$absoluteXPath])) { + $this->_displayError("The $absoluteXPath value isn't a node in this document.", __LINE__, __FILE__, FALSE); + break; // try-block + } + + // Get the amount of the text parts in the node. + $textPartSize = sizeOf($this->nodeIndex[$absoluteXPath]['textParts']); + + // If $textPartNr == NULL we return a *copy* of the whole concated text-parts + if (is_null($textPartNr)) { + unset($text); + $text = implode('', $this->nodeIndex[$absoluteXPath]['textParts']); + $status = TRUE; + break; // try-block + } + + // Support negative indexes like -1 === last a.s.o. + if ($textPartNr < 0) $textPartNr = $textPartSize + $textPartNr +1; + if (($textPartNr <= 0) OR ($textPartNr > $textPartSize)) { + $this->_displayError("The $absoluteXPath has no text part at pos [$textPartNr] (Note: text parts start with 1).", __LINE__, __FILE__, FALSE); + break; // try-block + } + $text =& $this->nodeIndex[$absoluteXPath]['textParts'][$textPartNr -1]; + $status = TRUE; + } while (FALSE); // END try-block + + if (!$status) return FALSE; + return $text; + } + + /** + * Obtain the string value of an object + * + * http://www.w3.org/TR/xpath#dt-string-value + * + * "For every type of node, there is a way of determining a string-value for a node of that type. + * For some types of node, the string-value is part of the node; for other types of node, the + * string-value is computed from the string-value of descendant nodes." + * + * @param $node (node) The node we have to convert + * @return (string) The string value of the node. "" if the object has no evaluatable + * string value + */ + function _stringValue($node) { + // Decode the entitites and then add the resulting literal string into our array. + return $this->_addLiteral($this->decodeEntities($this->wholeText($node))); + } + + //----------------------------------------------------------------------------------------- + // XPathEngine ------ Export the XML Document ------ + //----------------------------------------------------------------------------------------- + + /** + * Returns the containing XML as marked up HTML with specified nodes hi-lighted + * + * @param $absoluteXPath (string) The address of the node you would like to export. + * If empty the whole document will be exported. + * @param $hilighXpathList (array) A list of nodes that you would like to highlight + * @return (mixed) The Xml document marked up as HTML so that it can + * be viewed in a browser, including any XML headers. + * FALSE on error. + * @see _export() + */ + function exportAsHtml($absoluteXPath='', $hilightXpathList=array()) { + $htmlString = $this->_export($absoluteXPath, $xmlHeader=NULL, $hilightXpathList); + if (!$htmlString) return FALSE; + return "
    \n" . $htmlString . "\n
    "; + } + + /** + * Given a context this function returns the containing XML + * + * @param $absoluteXPath (string) The address of the node you would like to export. + * If empty the whole document will be exported. + * @param $xmlHeader (array) The string that you would like to appear before + * the XML content. ie before the . If you + * do not specify this argument, the xmlHeader that was + * found in the parsed xml file will be used instead. + * @return (mixed) The Xml fragment/document, suitable for writing + * out to an .xml file or as part of a larger xml file, or + * FALSE on error. + * @see _export() + */ + function exportAsXml($absoluteXPath='', $xmlHeader=NULL) { + $this->hilightXpathList = NULL; + return $this->_export($absoluteXPath, $xmlHeader); + } + + /** + * Generates a XML string with the content of the current document and writes it to a file. + * + * Per default includes a tag at the start of the data too. + * + * @param $fileName (string) + * @param $absoluteXPath (string) The path to the parent node you want(see text above) + * @param $xmlHeader (array) The string that you would like to appear before + * the XML content. ie before the . If you + * do not specify this argument, the xmlHeader that was + * found in the parsed xml file will be used instead. + * @return (string) The returned string contains well-formed XML data + * or FALSE on error. + * @see exportAsXml(), exportAsHtml() + */ + function exportToFile($fileName, $absoluteXPath='', $xmlHeader=NULL) { + $status = FALSE; + do { // try-block + if (!($hFile = fopen($fileName, "wb"))) { // Did we open the file ok? + $errStr = "Failed to open the $fileName xml file."; + break; // try-block + } + + if ($this->properties['OS_supports_flock']) { + if (!flock($hFile, LOCK_EX + LOCK_NB)) { // Lock the file + $errStr = "Couldn't get an exclusive lock on the $fileName file."; + break; // try-block + } + } + if (!($xmlOut = $this->_export($absoluteXPath, $xmlHeader))) { + $errStr = "Export failed"; + break; // try-block + } + + $iBytesWritten = fwrite($hFile, $xmlOut); + if ($iBytesWritten != strlen($xmlOut)) { + $errStr = "Write error when writing back the $fileName file."; + break; // try-block + } + + // Flush and unlock the file + @fflush($hFile); + $status = TRUE; + } while(FALSE); + + @flock($hFile, LOCK_UN); + @fclose($hFile); + // Sanity check the produced file. + clearstatcache(); + if (filesize($fileName) < strlen($xmlOut)) { + $errStr = "Write error when writing back the $fileName file."; + $status = FALSE; + } + + if (!$status) $this->_displayError($errStr, __LINE__, __FILE__, FALSE); + return $status; + } + + /** + * Generates a XML string with the content of the current document. + * + * This is the start for extracting the XML-data from the node-tree. We do some preperations + * and then call _InternalExport() to fetch the main XML-data. You optionally may pass + * xpath to any node that will then be used as top node, to extract XML-parts of the + * document. Default is '', meaning to extract the whole document. + * + * You also may pass a 'xmlHeader' (usually something like that will + * overwrite any other 'xmlHeader', if there was one in the original source. If there + * wasn't one in the original source, and you still don't specify one, then it will + * use a default of + * Finaly, when exporting to HTML, you may pass a vector xPaths you want to hi-light. + * The hi-lighted tags and attributes will receive a nice color. + * + * NOTE I : The output can have 2 formats: + * a) If "skip white spaces" is/was set. (Not Recommended - slower) + * The output is formatted by adding indenting and carriage returns. + * b) If "skip white spaces" is/was *NOT* set. + * 'as is'. No formatting is done. The output should the same as the + * the original parsed XML source. + * + * @param $absoluteXPath (string) (optional, default is root) The node we choose as top-node + * @param $xmlHeader (string) (optional) content before (see text above) + * @param $hilightXpath (array) (optional) a vector of xPaths to nodes we wat to + * hi-light (see text above) + * @return (mixed) The xml string, or FALSE on error. + */ + function _export($absoluteXPath='', $xmlHeader=NULL, $hilightXpathList='') { + // Check whether a root node is given. + if (empty($absoluteXpath)) $absoluteXpath = ''; + if ($absoluteXpath == '/') $absoluteXpath = ''; + if ($this->_indexIsDirty) $this->reindexNodeTree(); + if (!isSet($this->nodeIndex[$absoluteXpath])) { + // If the $absoluteXpath was '' and it didn't exist, then the document is empty + // and we can safely return ''. + if ($absoluteXpath == '') return ''; + $this->_displayError("The given xpath '{$absoluteXpath}' isn't a node in this document.", __LINE__, __FILE__, FALSE); + return FALSE; + } + + $this->hilightXpathList = $hilightXpathList; + $this->indentStep = ' '; + $hilightIsActive = is_array($hilightXpathList); + if ($hilightIsActive) { + $this->indentStep = '    '; + } + + // Cache this now + $this->parseSkipWhiteCache = isSet($this->parseOptions[XML_OPTION_SKIP_WHITE]) ? $this->parseOptions[XML_OPTION_SKIP_WHITE] : FALSE; + + /////////////////////////////////////// + // Get the starting node and begin with the header + + // Get the start node. The super root is a special case. + $startNode = NULL; + if (empty($absoluteXPath)) { + $superRoot = $this->nodeIndex['']; + // If they didn't specify an xml header, use the one in the object + if (is_null($xmlHeader)) { + $xmlHeader = $this->parseSkipWhiteCache ? trim($superRoot['textParts'][0]) : $superRoot['textParts'][0]; + // If we still don't have an XML header, then use a suitable default + if (empty($xmlHeader)) { + $xmlHeader = ''; + } + } + + if (isSet($superRoot['childNodes'][0])) $startNode = $superRoot['childNodes'][0]; + } else { + $startNode = $this->nodeIndex[$absoluteXPath]; + } + + if (!empty($xmlHeader)) { + $xmlOut = $this->parseSkipWhiteCache ? $xmlHeader."\n" : $xmlHeader; + } else { + $xmlOut = ''; + } + + /////////////////////////////////////// + // Output the document. + + if (($xmlOut .= $this->_InternalExport($startNode)) === FALSE) { + return FALSE; + } + + /////////////////////////////////////// + + // Convert our markers to hi-lights. + if ($hilightIsActive) { + $from = array('<', '>', chr(2), chr(3)); + $to = array('<', '>', '', ''); + $xmlOut = str_replace($from, $to, $xmlOut); + } + return $xmlOut; + } + + /** + * Export the xml document starting at the named node. + * + * @param $node (node) The node we have to start exporting from + * @return (string) The string representation of the node. + */ + function _InternalExport($node) { + $ThisFunctionName = '_InternalExport'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Exporting node: ".$node['xpath']."
    \n"; + } + + //////////////////////////////// + + // Quick out. + if (empty($node)) return ''; + + // The output starts as empty. + $xmlOut = ''; + // This loop will output the text before the current child of a parent then the + // current child. Where the child is a short tag we output the child, then move + // onto the next child. Where the child is not a short tag, we output the open tag, + // then queue up on currentParentStack[] the child. + // + // When we run out of children, we then output the last text part, and close the + // 'parent' tag before popping the stack and carrying on. + // + // To illustrate, the numbers in this xml file indicate what is output on each + // pass of the while loop: + // + // 1 + // <1>2 + // <2>3 + // <3/>4 + // 5 + // <5/>6 + // + + // Although this is neater done using recursion, there's a 33% performance saving + // to be gained by using this stack mechanism. + + // Only add CR's if "skip white spaces" was set. Otherwise leave as is. + $CR = ($this->parseSkipWhiteCache) ? "\n" : ''; + $currentIndent = ''; + $hilightIsActive = is_array($this->hilightXpathList); + + // To keep track of where we are in the document we use a node stack. The node + // stack has the following parallel entries: + // 'Parent' => (array) A copy of the parent node that who's children we are + // exporting + // 'ChildIndex' => (array) The child index of the corresponding parent that we + // are currently exporting. + // 'Highlighted'=> (bool) If we are highlighting this node. Only relevant if + // the hilight is active. + + // Setup our node stack. The loop is designed to output children of a parent, + // not the parent itself, so we must put the parent on as the starting point. + $nodeStack['Parent'] = array($node['parentNode']); + // And add the childpos of our node in it's parent to our "child index stack". + $nodeStack['ChildIndex'] = array($node['pos']); + // We start at 0. + $nodeStackIndex = 0; + + // We have not to output text before/after our node, so blank it. We will recover it + // later + $OldPreceedingStringValue = $nodeStack['Parent'][0]['textParts'][$node['pos']]; + $OldPreceedingStringRef =& $nodeStack['Parent'][0]['textParts'][$node['pos']]; + $OldPreceedingStringRef = ""; + $currentXpath = ""; + + // While we still have data on our stack + while ($nodeStackIndex >= 0) { + // Count the children and get a copy of the current child. + $iChildCount = count($nodeStack['Parent'][$nodeStackIndex]['childNodes']); + $currentChild = $nodeStack['ChildIndex'][$nodeStackIndex]; + // Only do the auto indenting if the $parseSkipWhiteCache flag was set. + if ($this->parseSkipWhiteCache) + $currentIndent = str_repeat($this->indentStep, $nodeStackIndex); + + if ($bDebugThisFunction) + echo "Exporting child ".($currentChild+1)." of node {$nodeStack['Parent'][$nodeStackIndex]['xpath']}\n"; + + /////////////////////////////////////////// + // Add the text before our child. + + // Add the text part before the current child + $tmpTxt =& $nodeStack['Parent'][$nodeStackIndex]['textParts'][$currentChild]; + if (isSet($tmpTxt) AND ($tmpTxt!="")) { + // Only add CR indent if there were children + if ($iChildCount) + $xmlOut .= $CR.$currentIndent; + // Hilight if necessary. + $highlightStart = $highlightEnd = ''; + if ($hilightIsActive) { + $currentXpath = $nodeStack['Parent'][$nodeStackIndex]['xpath'].'/text()['.($currentChild+1).']'; + if (in_array($currentXpath, $this->hilightXpathList)) { + // Yes we hilight + $highlightStart = chr(2); + $highlightEnd = chr(3); + } + } + $xmlOut .= $highlightStart.$nodeStack['Parent'][$nodeStackIndex]['textParts'][$currentChild].$highlightEnd; + } + if ($iChildCount && $nodeStackIndex) $xmlOut .= $CR; + + /////////////////////////////////////////// + + // Are there any more children? + if ($iChildCount <= $currentChild) { + // Nope, so output the last text before the closing tag + $tmpTxt =& $nodeStack['Parent'][$nodeStackIndex]['textParts'][$currentChild+1]; + if (isSet($tmpTxt) AND ($tmpTxt!="")) { + // Hilight if necessary. + $highlightStart = $highlightEnd = ''; + if ($hilightIsActive) { + $currentXpath = $nodeStack['Parent'][$nodeStackIndex]['xpath'].'/text()['.($currentChild+2).']'; + if (in_array($currentXpath, $this->hilightXpathList)) { + // Yes we hilight + $highlightStart = chr(2); + $highlightEnd = chr(3); + } + } + $xmlOut .= $highlightStart + .$currentIndent.$nodeStack['Parent'][$nodeStackIndex]['textParts'][$currentChild+1].$CR + .$highlightEnd; + } + + // Now close this tag, as we are finished with this child. + + // Potentially output an (slightly smaller indent). + if ($this->parseSkipWhiteCache + && count($nodeStack['Parent'][$nodeStackIndex]['childNodes'])) { + $xmlOut .= str_repeat($this->indentStep, $nodeStackIndex - 1); + } + + // Check whether the xml-tag is to be hilighted. + $highlightStart = $highlightEnd = ''; + if ($hilightIsActive) { + $currentXpath = $nodeStack['Parent'][$nodeStackIndex]['xpath']; + if (in_array($currentXpath, $this->hilightXpathList)) { + // Yes we hilight + $highlightStart = chr(2); + $highlightEnd = chr(3); + } + } + $xmlOut .= $highlightStart + .'' + .$highlightEnd; + // Decrement the $nodeStackIndex to go back to the next unfinished parent. + $nodeStackIndex--; + + // If the index is 0 we are finished exporting the last node, as we may have been + // exporting an internal node. + if ($nodeStackIndex == 0) break; + + // Indicate to the parent that we are finished with this child. + $nodeStack['ChildIndex'][$nodeStackIndex]++; + + continue; + } + + /////////////////////////////////////////// + // Ok, there are children still to process. + + // Queue up the next child (I can copy because I won't modify and copying is faster.) + $nodeStack['Parent'][$nodeStackIndex + 1] = $nodeStack['Parent'][$nodeStackIndex]['childNodes'][$currentChild]; + + // Work out if it is a short child tag. + $iGrandChildCount = count($nodeStack['Parent'][$nodeStackIndex + 1]['childNodes']); + $shortGrandChild = (($iGrandChildCount == 0) AND (implode('',$nodeStack['Parent'][$nodeStackIndex + 1]['textParts'])=='')); + + /////////////////////////////////////////// + // Assemble the attribute string first. + $attrStr = ''; + foreach($nodeStack['Parent'][$nodeStackIndex + 1]['attributes'] as $key=>$val) { + // Should we hilight the attribute? + if ($hilightIsActive AND in_array($currentXpath.'/attribute::'.$key, $this->hilightXpathList)) { + $hiAttrStart = chr(2); + $hiAttrEnd = chr(3); + } else { + $hiAttrStart = $hiAttrEnd = ''; + } + $attrStr .= ' '.$hiAttrStart.$key.'="'.$val.'"'.$hiAttrEnd; + } + + /////////////////////////////////////////// + // Work out what goes before and after the tag content + + $beforeTagContent = $currentIndent; + if ($shortGrandChild) $afterTagContent = '/>'; + else $afterTagContent = '>'; + + // Check whether the xml-tag is to be hilighted. + if ($hilightIsActive) { + $currentXpath = $nodeStack['Parent'][$nodeStackIndex + 1]['xpath']; + if (in_array($currentXpath, $this->hilightXpathList)) { + // Yes we hilight + $beforeTagContent .= chr(2); + $afterTagContent .= chr(3); + } + } + $beforeTagContent .= '<'; +// if ($shortGrandChild) $afterTagContent .= $CR; + + /////////////////////////////////////////// + // Output the tag + + $xmlOut .= $beforeTagContent + .$nodeStack['Parent'][$nodeStackIndex + 1]['name'].$attrStr + .$afterTagContent; + + /////////////////////////////////////////// + // Carry on. + + // If it is a short tag, then we've already done this child, we just move to the next + if ($shortGrandChild) { + // Move to the next child, we need not go deeper in the tree. + $nodeStack['ChildIndex'][$nodeStackIndex]++; + // But if we are just exporting the one node we'd go no further. + if ($nodeStackIndex == 0) break; + } else { + // Else queue up the child going one deeper in the stack + $nodeStackIndex++; + // Start with it's first child + $nodeStack['ChildIndex'][$nodeStackIndex] = 0; + } + } + + $result = $xmlOut; + + // Repair what we "undid" + $OldPreceedingStringRef = $OldPreceedingStringValue; + + //////////////////////////////////////////// + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + return $result; + } + + //----------------------------------------------------------------------------------------- + // XPathEngine ------ Import the XML Source ------ + //----------------------------------------------------------------------------------------- + + /** + * Reads a file or URL and parses the XML data. + * + * Parse the XML source and (upon success) store the information into an internal structure. + * + * @param $fileName (string) Path and name (or URL) of the file to be read and parsed. + * @return (bool) TRUE on success, FALSE on failure (check getLastError()) + * @see importFromString(), getLastError(), + */ + function importFromFile($fileName) { + $status = FALSE; + $errStr = ''; + do { // try-block + // Remember file name. Used in error output to know in which file it happend + $this->properties['xmlFile'] = $fileName; + // If we already have content, then complain. + if (!empty($this->nodeRoot)) { + $errStr = 'Called when this object already contains xml data. Use reset().'; + break; // try-block + } + // The the source is an url try to fetch it. + if (preg_match(';^http(s)?://;', $fileName)) { + // Read the content of the url...this is really prone to errors, and we don't really + // check for too many here...for now, suppressing both possible warnings...we need + // to check if we get a none xml page or something of that nature in the future + $xmlString = @implode('', @file($fileName)); + if (!empty($xmlString)) { + $status = TRUE; + } else { + $errStr = "The url '{$fileName}' could not be found or read."; + } + break; // try-block + } + + // Reaching this point we're dealing with a real file (not an url). Check if the file exists and is readable. + if (!is_readable($fileName)) { // Read the content from the file + $errStr = "File '{$fileName}' could not be found or read."; + break; // try-block + } + if (is_dir($fileName)) { + $errStr = "'{$fileName}' is a directory."; + break; // try-block + } + // Read the file + if (!($fp = @fopen($fileName, 'rb'))) { + $errStr = "Failed to open '{$fileName}' for read."; + break; // try-block + } + $xmlString = fread($fp, filesize($fileName)); + @fclose($fp); + + $status = TRUE; + } while (FALSE); + + if (!$status) { + $this->_displayError('In importFromFile(): '. $errStr, __LINE__, __FILE__, FALSE); + return FALSE; + } + return $this->importFromString($xmlString); + } + + /** + * Reads a string and parses the XML data. + * + * Parse the XML source and (upon success) store the information into an internal structure. + * If a parent xpath is given this means that XML data is to be *appended* to that parent. + * + * ### If a function uses setLastError(), then say in the function header that getLastError() is useful. + * + * @param $xmlString (string) Name of the string to be read and parsed. + * @param $absoluteParentPath (string) Node to append data too (see above) + * @return (bool) TRUE on success, FALSE on failure + * (check getLastError()) + */ + function importFromString($xmlString, $absoluteParentPath = '') { + $ThisFunctionName = 'importFromString'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Importing from string of length ".strlen($xmlString)." to node '$absoluteParentPath'\n
    "; + echo "Parser options:\n
    "; + print_r($this->parseOptions); + } + + $status = FALSE; + $errStr = ''; + do { // try-block + // If we already have content, then complain. + if (!empty($this->nodeRoot) AND empty($absoluteParentPath)) { + $errStr = 'Called when this object already contains xml data. Use reset() or pass the parent Xpath as 2ed param to where tie data will append.'; + break; // try-block + } + // Check whether content has been read. + if (empty($xmlString)) { + // Nothing to do!! + $status = TRUE; + // If we were importing to root, build a blank root. + if (empty($absoluteParentPath)) { + $this->_createSuperRoot(); + } + $this->reindexNodeTree(); +// $errStr = 'This xml document (string) was empty'; + break; // try-block + } else { + $xmlString = $this->_translateAmpersand($xmlString); + } + + // Restart our node index with a root entry. + $nodeStack = array(); + $this->parseStackIndex = 0; + + // If a parent xpath is given this means that XML data is to be *appended* to that parent. + if (!empty($absoluteParentPath)) { + // Check if parent exists + if (!isSet($this->nodeIndex[$absoluteParentPath])) { + $errStr = "You tried to append XML data to a parent '$absoluteParentPath' that does not exist."; + break; // try-block + } + // Add it as the starting point in our array. + $this->nodeStack[0] =& $this->nodeIndex[$absoluteParentPath]; + } else { + // Build a 'super-root' + $this->_createSuperRoot(); + // Put it in as the start of our node stack. + $this->nodeStack[0] =& $this->nodeRoot; + } + + // Point our text buffer reference at the next text part of the root + $this->parsedTextLocation =& $this->nodeStack[0]['textParts'][]; + $this->parsInCData = 0; + // We cache this now. + $this->parseSkipWhiteCache = isSet($this->parseOptions[XML_OPTION_SKIP_WHITE]) ? $this->parseOptions[XML_OPTION_SKIP_WHITE] : FALSE; + + // Create an XML parser. + $parser = xml_parser_create(); + // Set default XML parser options. + if (is_array($this->parseOptions)) { + foreach($this->parseOptions as $key => $val) { + xml_parser_set_option($parser, $key, $val); + } + } + + // Set the object and the element handlers for the XML parser. + xml_set_object($parser, $this); + xml_set_element_handler($parser, '_handleStartElement', '_handleEndElement'); + xml_set_character_data_handler($parser, '_handleCharacterData'); + xml_set_default_handler($parser, '_handleDefaultData'); + xml_set_processing_instruction_handler($parser, '_handlePI'); + + // Parse the XML source and on error generate an error message. + if (!xml_parse($parser, $xmlString, TRUE)) { + $source = empty($this->properties['xmlFile']) ? 'string' : 'file ' . basename($this->properties['xmlFile']) . "'"; + $errStr = "XML error in given {$source} on line ". + xml_get_current_line_number($parser). ' column '. xml_get_current_column_number($parser) . + '. Reason:'. xml_error_string(xml_get_error_code($parser)); + break; // try-block + } + + // Free the parser. + @xml_parser_free($parser); + // And we don't need this any more. + $this->nodeStack = array(); + + $this->reindexNodeTree(); + + if ($bDebugThisFunction) { + print_r(array_keys($this->nodeIndex)); + } + + $status = TRUE; + } while (FALSE); + + if (!$status) { + $this->_displayError('In importFromString(): '. $errStr, __LINE__, __FILE__, FALSE); + $bResult = FALSE; + } else { + $bResult = TRUE; + } + + //////////////////////////////////////////// + + $this->_closeDebugFunction($ThisFunctionName, $bResult, $bDebugThisFunction); + + return $bResult; + } + + + //----------------------------------------------------------------------------------------- + // XPathEngine ------ XML Handlers ------ + //----------------------------------------------------------------------------------------- + + /** + * Handles opening XML tags while parsing. + * + * While parsing a XML document for each opening tag this method is + * called. It'll add the tag found to the tree of document nodes. + * + * @param $parser (int) Handler for accessing the current XML parser. + * @param $name (string) Name of the opening tag found in the document. + * @param $attributes (array) Associative array containing a list of + * all attributes of the tag found in the document. + * @see _handleEndElement(), _handleCharacterData() + */ + function _handleStartElement($parser, $nodeName, $attributes) { + if (empty($nodeName)) { + $this->_displayError('XML error in file at line'. xml_get_current_line_number($parser) .'. Empty name.', __LINE__, __FILE__); + return; + } + + // Trim accumulated text if necessary. + if ($this->parseSkipWhiteCache) { + $iCount = count($this->nodeStack[$this->parseStackIndex]['textParts']); + $this->nodeStack[$this->parseStackIndex]['textParts'][$iCount-1] = rtrim($this->parsedTextLocation); + } + + if ($this->bDebugXmlParse) { + echo "
    " . htmlspecialchars("Start node: <".$nodeName . ">")."
    "; + echo "Appended to stack entry: $this->parseStackIndex
    \n"; + echo "Text part before element is: ".htmlspecialchars($this->parsedTextLocation); + /* + echo "
    ";
    +      $dataPartsCount = count($this->nodeStack[$this->parseStackIndex]['textParts']);
    +      for ($i = 0; $i < $dataPartsCount; $i++) {
    +        echo "$i:". htmlspecialchars($this->nodeStack[$this->parseStackIndex]['textParts'][$i])."\n";
    +      }
    +      echo "
    "; + */ + } + + // Add a node and set path to current. + if (!$this->_internalAppendChild($this->parseStackIndex, $nodeName)) { + $this->_displayError('Internal error during parse of XML file at line'. xml_get_current_line_number($parser) .'. Empty name.', __LINE__, __FILE__); + return; + } + + // We will have gone one deeper then in the stack. + $this->parseStackIndex++; + + // Point our parseTxtBuffer reference at the new node. + $this->parsedTextLocation =& $this->nodeStack[$this->parseStackIndex]['textParts'][0]; + + // Set the attributes. + if (!empty($attributes)) { + if ($this->bDebugXmlParse) { + echo 'Attributes:
    '; + print_r($attributes); + echo '
    '; + } + $this->nodeStack[$this->parseStackIndex]['attributes'] = $attributes; + } + } + + /** + * Handles closing XML tags while parsing. + * + * While parsing a XML document for each closing tag this method is called. + * + * @param $parser (int) Handler for accessing the current XML parser. + * @param $name (string) Name of the closing tag found in the document. + * @see _handleStartElement(), _handleCharacterData() + */ + function _handleEndElement($parser, $name) { + if (($this->parsedTextLocation=='') + && empty($this->nodeStack[$this->parseStackIndex]['textParts'])) { + // We reach this point when parsing a tag of format . The 'textParts'-array + // should stay empty and not have an empty string in it. + } else { + // Trim accumulated text if necessary. + if ($this->parseSkipWhiteCache) { + $iCount = count($this->nodeStack[$this->parseStackIndex]['textParts']); + $this->nodeStack[$this->parseStackIndex]['textParts'][$iCount-1] = rtrim($this->parsedTextLocation); + } + } + + if ($this->bDebugXmlParse) { + echo "Text part after element is: ".htmlspecialchars($this->parsedTextLocation)."
    \n"; + echo htmlspecialchars("Parent:<{$this->parseStackIndex}>, End-node: '".$this->parsedTextLocation) . "'
    Text nodes:
    \n";
    +      $dataPartsCount = count($this->nodeStack[$this->parseStackIndex]['textParts']);
    +      for ($i = 0; $i < $dataPartsCount; $i++) {
    +        echo "$i:". htmlspecialchars($this->nodeStack[$this->parseStackIndex]['textParts'][$i])."\n";
    +      }
    +      var_dump($this->nodeStack[$this->parseStackIndex]['textParts']);
    +      echo "
    \n"; + } + + // Jump back to the parent element. + $this->parseStackIndex--; + + // Set our reference for where we put any more whitespace + $this->parsedTextLocation =& $this->nodeStack[$this->parseStackIndex]['textParts'][]; + + // Note we leave the entry in the stack, as it will get blanked over by the next element + // at this level. The safe thing to do would be to remove it too, but in the interests + // of performance, we will not bother, as were it to be a problem, then it would be an + // internal bug anyway. + if ($this->parseStackIndex < 0) { + $this->_displayError('Internal error during parse of XML file at line'. xml_get_current_line_number($parser) .'. Empty name.', __LINE__, __FILE__); + return; + } + } + + /** + * Handles character data while parsing. + * + * While parsing a XML document for each character data this method + * is called. It'll add the character data to the document tree. + * + * @param $parser (int) Handler for accessing the current XML parser. + * @param $text (string) Character data found in the document. + * @see _handleStartElement(), _handleEndElement() + */ + function _handleCharacterData($parser, $text) { + + if ($this->parsInCData >0) $text = $this->_translateAmpersand($text, $reverse=TRUE); + + if ($this->bDebugXmlParse) echo "Handling character data: '".htmlspecialchars($text)."'
    "; + if ($this->parseSkipWhiteCache AND !empty($text) AND !$this->parsInCData) { + // Special case CR. CR always comes in a separate data. Trans. it to '' or ' '. + // If txtBuffer is already ending with a space use '' otherwise ' '. + $bufferHasEndingSpace = (empty($this->parsedTextLocation) OR substr($this->parsedTextLocation, -1) === ' ') ? TRUE : FALSE; + if ($text=="\n") { + $text = $bufferHasEndingSpace ? '' : ' '; + } else { + if ($bufferHasEndingSpace) { + $text = ltrim(preg_replace('/\s+/', ' ', $text)); + } else { + $text = preg_replace('/\s+/', ' ', $text); + } + } + if ($this->bDebugXmlParse) echo "'Skip white space' is ON. reduced to : '" .htmlspecialchars($text) . "'
    "; + } + $this->parsedTextLocation .= $text; + } + + /** + * Default handler for the XML parser. + * + * While parsing a XML document for string not caught by one of the other + * handler functions, we end up here. + * + * @param $parser (int) Handler for accessing the current XML parser. + * @param $text (string) Character data found in the document. + * @see _handleStartElement(), _handleEndElement() + */ + function _handleDefaultData($parser, $text) { + do { // try-block + if (!strcmp($text, 'parsInCData++; + } elseif (!strcmp($text, ']]>')) { + $this->parsInCData--; + if ($this->parsInCData < 0) $this->parsInCData = 0; + } + $this->parsedTextLocation .= $this->_translateAmpersand($text, $reverse=TRUE); + if ($this->bDebugXmlParse) echo "Default handler data: ".htmlspecialchars($text)."
    "; + break; // try-block + } while (FALSE); // END try-block + } + + /** + * Handles processing instruction (PI) + * + * A processing instruction has the following format: + * e.g. + * + * Currently I have no bether idea as to left it 'as is' and treat the PI data as normal + * text (and adding the surrounding PI-tags ). + * + * @param $parser (int) Handler for accessing the current XML parser. + * @param $target (string) Name of the PI target. E.g. XML, PHP, DTD, ... + * @param $data (string) Associative array containing a list of + * @see PHP's manual "xml_set_processing_instruction_handler" + */ + function _handlePI($parser, $target, $data) { + //echo("pi data=".$data."end"); exit; + $data = $this->_translateAmpersand($data, $reverse=TRUE); + $this->parsedTextLocation .= ""; + return TRUE; + } + + //----------------------------------------------------------------------------------------- + // XPathEngine ------ Node Tree Stuff ------ + //----------------------------------------------------------------------------------------- + + /** + * Creates a super root node. + */ + function _createSuperRoot() { + // Build a 'super-root' + $this->nodeRoot = $this->emptyNode; + $this->nodeRoot['name'] = ''; + $this->nodeRoot['parentNode'] = NULL; + $this->nodeIndex[''] =& $this->nodeRoot; + } + + /** + * Adds a new node to the XML document tree during xml parsing. + * + * This method adds a new node to the tree of nodes of the XML document + * being handled by this class. The new node is created according to the + * parameters passed to this method. This method is a much watered down + * version of appendChild(), used in parsing an xml file only. + * + * It is assumed that adding starts with root and progresses through the + * document in parse order. New nodes must have a corresponding parent. And + * once we have read the tag for the element we will never need to add + * any more data to that node. Otherwise the add will be ignored or fail. + * + * The function is faciliated by a nodeStack, which is an array of nodes that + * we have yet to close. + * + * @param $stackParentIndex (int) The index into the nodeStack[] of the parent + * node to which the new node should be added as + * a child. *READONLY* + * @param $nodeName (string) Name of the new node. *READONLY* + * @return (bool) TRUE if we successfully added a new child to + * the node stack at index $stackParentIndex + 1, + * FALSE on error. + */ + function _internalAppendChild($stackParentIndex, $nodeName) { + // This call is likely to be executed thousands of times, so every 0.01ms counts. + // If you want to debug this function, you'll have to comment the stuff back in + //$bDebugThisFunction = FALSE; + + /* + $ThisFunctionName = '_internalAppendChild'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Current Node (parent-index) and the child to append : '{$stackParentIndex}' + '{$nodeName}' \n
    "; + } + */ + ////////////////////////////////////// + + if (!isSet($this->nodeStack[$stackParentIndex])) { + $errStr = "Invalid parent. You tried to append the tag '{$nodeName}' to an non-existing parent in our node stack '{$stackParentIndex}'."; + $this->_displayError('In _internalAppendChild(): '. $errStr, __LINE__, __FILE__, FALSE); + + /* + $this->_closeDebugFunction($ThisFunctionName, FALSE, $bDebugThisFunction); + */ + + return FALSE; + } + + // Retrieve the parent node from the node stack. This is the last node at that + // depth that we have yet to close. This is where we should add the text/node. + $parentNode =& $this->nodeStack[$stackParentIndex]; + + // Brand new node please + $newChildNode = $this->emptyNode; + + // Save the vital information about the node. + $newChildNode['name'] = $nodeName; + $parentNode['childNodes'][] =& $newChildNode; + + // Add to our node stack + $this->nodeStack[$stackParentIndex + 1] =& $newChildNode; + + /* + if ($bDebugThisFunction) { + echo "The new node received index: '".($stackParentIndex + 1)."'\n"; + foreach($this->nodeStack as $key => $val) echo "$key => ".$val['name']."\n"; + } + $this->_closeDebugFunction($ThisFunctionName, TRUE, $bDebugThisFunction); + */ + + return TRUE; + } + + /** + * Update nodeIndex and every node of the node-tree. + * + * Call after you have finished any tree modifications other wise a match with + * an xPathQuery will produce wrong results. The $this->nodeIndex[] is recreated + * and every nodes optimization data is updated. The optimization data is all the + * data that is duplicate information, would just take longer to find. Child nodes + * with value NULL are removed from the tree. + * + * By default the modification functions in this component will automatically re-index + * the nodes in the tree. Sometimes this is not the behaver you want. To surpress the + * reindex, set the functions $autoReindex to FALSE and call reindexNodeTree() at the + * end of your changes. This sometimes leads to better code (and less CPU overhead). + * + * Sample: + * ======= + * Given the xml is .. | Goal is .. (Delete B[1] and B[3]) + * $xPathSet = $xPath->match('//B'); # Will result in array('/AAA[1]/B[1]', '/AAA[1]/B[2]', '/AAA[1]/B[3]'); + * Three ways to do it. + * 1) Top-Down (with auto reindexing) - Safe, Slow and you get easily mix up with the the changing node index + * removeChild('/AAA[1]/B[1]'); // B[1] removed, thus all B[n] become B[n-1] !! + * removeChild('/AAA[1]/B[2]'); // Now remove B[2] (That originaly was B[3]) + * 2) Bottom-Up (with auto reindexing) - Safe, Slow and the changing node index (caused by auto-reindex) can be ignored. + * for ($i=sizeOf($xPathSet)-1; $i>=0; $i--) { + * if ($i==1) continue; + * removeChild($xPathSet[$i]); + * } + * 3) // Top-down (with *NO* auto reindexing) - Fast, Safe as long as you call reindexNodeTree() + * foreach($xPathSet as $xPath) { + * // Specify no reindexing + * if ($xPath == $xPathSet[1]) continue; + * removeChild($xPath, $autoReindex=FALSE); + * // The object is now in a slightly inconsistent state. + * } + * // Finally do the reindex and the object is consistent again + * reindexNodeTree(); + * + * @return (bool) TRUE on success, FALSE otherwise. + * @see _recursiveReindexNodeTree() + */ + function reindexNodeTree() { + //return; + $this->_indexIsDirty = FALSE; + $this->nodeIndex = array(); + $this->nodeIndex[''] =& $this->nodeRoot; + // Quick out for when the tree has no data. + if (empty($this->nodeRoot)) return TRUE; + return $this->_recursiveReindexNodeTree(''); + } + + + /** + * Create the ids that are accessable through the generate-id() function + */ + function _generate_ids() { + // If we have generated them already, then bail. + if (isset($this->nodeIndex['']['generate_id'])) return; + + // keys generated are the string 'id0' . hexatridecimal-based (0..9,a-z) index + $aNodeIndexes = array_keys($this->nodeIndex); + $idNumber = 0; + foreach($aNodeIndexes as $index => $key) { +// $this->nodeIndex[$key]['generated_id'] = 'id' . base_convert($index,10,36); + // Skip attribute and text nodes. + // ### Currently don't support attribute and text nodes. + if (strstr($key, 'text()') !== FALSE) continue; + if (strstr($key, 'attribute::') !== FALSE) continue; + $this->nodeIndex[$key]['generated_id'] = 'idPhpXPath' . $idNumber; + + // Make the id's sequential so that we can test predictively. + $idNumber++; + } + } + + /** + * Here's where the work is done for reindexing (see reindexNodeTree) + * + * @param $absoluteParentPath (string) the xPath to the parent node + * @return (bool) TRUE on success, FALSE otherwise. + * @see reindexNodeTree() + */ + function _recursiveReindexNodeTree($absoluteParentPath) { + $parentNode =& $this->nodeIndex[$absoluteParentPath]; + + // Check for any 'dead' child nodes first and concate the text parts if found. + for ($iChildIndex=sizeOf($parentNode['childNodes'])-1; $iChildIndex>=0; $iChildIndex--) { + // Check if the child node still exits (it may have been removed). + if (!empty($parentNode['childNodes'][$iChildIndex])) continue; + // Child node was removed. We got to merge the text parts then. + $parentNode['textParts'][$iChildIndex] .= $parentNode['textParts'][$iChildIndex+1]; + array_splice($parentNode['textParts'], $iChildIndex+1, 1); + array_splice($parentNode['childNodes'], $iChildIndex, 1); + } + + // Now start a reindex. + $contextHash = array(); + $childSize = sizeOf($parentNode['childNodes']); + + // If there are no children, we have to treat this specially: + if ($childSize == 0) { + // Add a dummy text node. + $this->nodeIndex[$absoluteParentPath.'/text()[1]'] =& $parentNode; + } else { + for ($iChildIndex=0; $iChildIndex<$childSize; $iChildIndex++) { + $childNode =& $parentNode['childNodes'][$iChildIndex]; + // Make sure that there is a text-part in front of every node. (May be empty) + if (!isSet($parentNode['textParts'][$iChildIndex])) $parentNode['textParts'][$iChildIndex] = ''; + // Count the nodes with same name (to determine their context position) + $childName = $childNode['name']; + if (empty($contextHash[$childName])) { + $contextPos = $contextHash[$childName] = 1; + } else { + $contextPos = ++$contextHash[$childName]; + } + // Make the node-index hash + $newPath = $absoluteParentPath . '/' . $childName . '['.$contextPos.']'; + + // ### Note ultimately we will end up supporting text nodes as actual nodes. + + // Preceed with a dummy entry for the text node. + $this->nodeIndex[$absoluteParentPath.'/text()['.($childNode['pos']+1).']'] =& $childNode; + // Then the node itself + $this->nodeIndex[$newPath] =& $childNode; + + // Now some dummy nodes for each of the attribute nodes. + $iAttributeCount = sizeOf($childNode['attributes']); + if ($iAttributeCount > 0) { + $aAttributesNames = array_keys($childNode['attributes']); + for ($iAttributeIndex = 0; $iAttributeIndex < $iAttributeCount; $iAttributeIndex++) { + $attribute = $aAttributesNames[$iAttributeIndex]; + $newAttributeNode = $this->emptyNode; + $newAttributeNode['name'] = $attribute; + $newAttributeNode['textParts'] = array($childNode['attributes'][$attribute]); + $newAttributeNode['contextPos'] = $iAttributeIndex; + $newAttributeNode['xpath'] = "$newPath/attribute::$attribute"; + $newAttributeNode['parentNode'] =& $childNode; + $newAttributeNode['depth'] =& $parentNode['depth'] + 2; + // Insert the node as a master node, not a reference, otherwise there will be + // variable "bleeding". + $this->nodeIndex["$newPath/attribute::$attribute"] = $newAttributeNode; + } + } + + // Update the node info (optimisation) + $childNode['parentNode'] =& $parentNode; + $childNode['depth'] = $parentNode['depth'] + 1; + $childNode['pos'] = $iChildIndex; + $childNode['contextPos'] = $contextHash[$childName]; + $childNode['xpath'] = $newPath; + $this->_recursiveReindexNodeTree($newPath); + + // Follow with a dummy entry for the text node. + $this->nodeIndex[$absoluteParentPath.'/text()['.($childNode['pos']+2).']'] =& $childNode; + } + + // Make sure that their is a text-part after the last node. + if (!isSet($parentNode['textParts'][$iChildIndex])) $parentNode['textParts'][$iChildIndex] = ''; + } + + return TRUE; + } + + /** + * Clone a node and it's child nodes. + * + * NOTE: If the node has children you *MUST* use the reference operator! + * E.g. $clonedNode =& cloneNode($node); + * Otherwise the children will not point back to the parent, they will point + * back to your temporary variable instead. + * + * @param $node (mixed) Either a node (hash array) or an abs. Xpath to a node in + * the current doc + * @return (&array) A node and it's child nodes. + */ + function &cloneNode($node, $recursive=FALSE) { + if (is_string($node) AND isSet($this->nodeIndex[$node])) { + $node = $this->nodeIndex[$node]; + } + // Copy the text-parts () + $textParts = $node['textParts']; + $node['textParts'] = array(); + foreach ($textParts as $key => $val) { + $node['textParts'][] = $val; + } + + $childSize = sizeOf($node['childNodes']); + for ($i=0; $i<$childSize; $i++) { + $childNode =& $this->cloneNode($node['childNodes'][$i], TRUE); // copy child + $node['childNodes'][$i] =& $childNode; // reference the copy + $childNode['parentNode'] =& $node; // child references the parent. + } + + if (!$recursive) { + //$node['childNodes'][0]['parentNode'] = null; + //print "
    ";
    +      //var_dump($node);
    +    }
    +    return $node;
    +  }
    +  
    +  
    +/** Nice to have but __sleep() has a bug. 
    +    (2002-2 PHP V4.1. See bug #15350)
    +  
    +  /**
    +   * PHP cals this function when you call PHP's serialize. 
    +   *
    +   * It prevents cyclic referencing, which is why print_r() of an XPath object doesn't work.
    +   *
    +  function __sleep() {
    +    // Destroy recursive pointers
    +    $keys = array_keys($this->nodeIndex);
    +    $size = sizeOf($keys);
    +    for ($i=0; $i<$size; $i++) {
    +      unset($this->nodeIndex[$keys[$i]]['parentNode']);
    +    }
    +    unset($this->nodeIndex);
    +  }
    +  
    +  /**
    +   * PHP cals this function when you call PHP's unserialize. 
    +   *
    +   * It reindexes the node-tree
    +   *
    +  function __wakeup() {
    +    $this->reindexNodeTree();
    +  }
    +  
    +*/
    +  
    +  //-----------------------------------------------------------------------------------------
    +  // XPath            ------  XPath Query / Evaluation Handlers  ------                      
    +  //-----------------------------------------------------------------------------------------
    +  
    +  /**
    +   * Matches (evaluates) an XPath query
    +   *
    +   * This method tries to evaluate an XPath query by parsing it. A XML source must 
    +   * have been imported before this method is able to work.
    +   *
    +   * @param     $xPathQuery  (string) XPath query to be evaluated.
    +   * @param     $baseXPath   (string) (default is super-root) XPath query to a single document node, 
    +   *                                  from which the XPath query should  start evaluating.
    +   * @return                 (mixed)  The result of the XPath expression.  Either:
    +   *                                    node-set (an ordered collection of absolute references to nodes without duplicates) 
    +   *                                    boolean (true or false) 
    +   *                                    number (a floating-point number) 
    +   *                                    string (a sequence of UCS characters) 
    +   */
    +  function match($xPathQuery, $baseXPath='') {
    +    if ($this->_indexIsDirty) $this->reindexNodeTree();
    +    
    +    // Replace a double slashes, because they'll cause problems otherwise.
    +    static $slashes2descendant = array(
    +        '//@' => '/descendant_or_self::*/attribute::', 
    +        '//'  => '/descendant_or_self::node()/', 
    +        '/@'  => '/attribute::');
    +    // Stupid idea from W3C to take axes name containing a '-' (dash) !!!
    +    // We replace the '-' with '_' to avoid the conflict with the minus operator.
    +    static $dash2underscoreHash = array( 
    +        '-sibling'    => '_sibling', 
    +        '-or-'        => '_or_',
    +        'starts-with' => 'starts_with', 
    +        'substring-before' => 'substring_before',
    +        'substring-after'  => 'substring_after', 
    +        'string-length'    => 'string_length',
    +        'normalize-space'  => 'normalize_space',
    +        'x-lower'          => 'x_lower',
    +        'x-upper'          => 'x_upper',
    +        'generate-id'      => 'generate_id');
    +    
    +    if (empty($xPathQuery)) return array();
    +
    +    // Special case for when document is empty.
    +    if (empty($this->nodeRoot)) return array();
    +
    +    if (!isSet($this->nodeIndex[$baseXPath])) {
    +            $xPathSet = $this->_resolveXPathQuery($baseXPath,'match');
    +            if (sizeOf($xPathSet) !== 1) {
    +                $this->_displayError(sprintf($this->errorStrings['NoNodeMatch'], $xPathQuery), __LINE__, __FILE__, FALSE);
    +                return FALSE;
    +            }
    +            $baseXPath = $xPathSet[0];
    +    }
    +
    +    // We should possibly do a proper syntactical parse, but instead we will cheat and just
    +    // remove any literals that could make things very difficult for us, and replace them with
    +    // special tags.  Then we can treat the xPathQuery much more easily as JUST "syntax".  Provided 
    +    // there are no literals in the string, then we can guarentee that most of the operators and 
    +    // syntactical elements are indeed elements and not just part of a literal string.
    +    $processedxPathQuery = $this->_removeLiterals($xPathQuery);
    +    
    +    // Replace a double slashes, and '-' (dash) in axes names.
    +    $processedxPathQuery = strtr($processedxPathQuery, $slashes2descendant);
    +    $processedxPathQuery = strtr($processedxPathQuery, $dash2underscoreHash);
    +
    +    // Build the context
    +    $context = array('nodePath' => $baseXPath, 'pos' => 1, 'size' => 1);
    +
    +    // The primary syntactic construct in XPath is the expression.
    +    $result = $this->_evaluateExpr($processedxPathQuery, $context);
    +
    +    // We might have been returned a string.. If so convert back to a literal
    +    $literalString = $this->_asLiteral($result);
    +    if ($literalString != FALSE) return $literalString;
    +    else return $result;
    +  }
    +
    +  /**
    +   * Alias for the match function
    +   *
    +   * @see match()
    +   */
    +  function evaluate($xPathQuery, $baseXPath='') {
    +    return $this->match($xPathQuery, $baseXPath);
    +  }
    +
    +  /**
    +   * Parse out the literals of an XPath expression.
    +   *
    +   * Instead of doing a full lexical parse, we parse out the literal strings, and then
    +   * Treat the sections of the string either as parts of XPath or literal strings.  So
    +   * this function replaces each literal it finds with a literal reference, and then inserts
    +   * the reference into an array of strings that we can access.  The literals can be accessed
    +   * later from the literals associative array.
    +   *
    +   * Example:
    +   *  XPathExpr = /AAA[@CCC = "hello"]/BBB[DDD = 'world'] 
    +   *  =>  literals: array("hello", "world")
    +   *      return value: /AAA[@CCC = $1]/BBB[DDD = $2] 
    +   *
    +   * Note: This does not interfere with the VariableReference syntactical element, as these 
    +   * elements must not start with a number.
    +   *
    +   * @param  $xPathQuery  (string) XPath expression to be processed
    +   * @return              (string) The XPath expression without the literals.
    +   *                              
    +   */
    +  function _removeLiterals($xPathQuery) {
    +    // What comes first?  A " or a '?
    +    if (!preg_match(":^([^\"']*)([\"'].*)$:", $xPathQuery, $aMatches)) {
    +      // No " or ' means no more literals.
    +      return $xPathQuery;
    +    }
    +    
    +    $result = $aMatches[1];
    +    $remainder = $aMatches[2];
    +    // What kind of literal?
    +    if (preg_match(':^"([^"]*)"(.*)$:', $remainder, $aMatches)) {
    +      // A "" literal.
    +      $literal = $aMatches[1];
    +      $remainder = $aMatches[2];
    +    } else if (preg_match(":^'([^']*)'(.*)$:", $remainder, $aMatches)) {
    +      // A '' literal.
    +      $literal = $aMatches[1];
    +      $remainder = $aMatches[2];
    +    } else {
    +      $this->_displayError("The '$xPathQuery' argument began a literal, but did not close it.", __LINE__, __FILE__);
    +    }
    +
    +    // Store the literal
    +    $literalNumber = count($this->axPathLiterals);
    +    $this->axPathLiterals[$literalNumber] = $literal;
    +    $result .= '$'.$literalNumber;
    +    return $result.$this->_removeLiterals($remainder);
    +  }
    +
    +  /**
    +   * Returns the given string as a literal reference.
    +   *
    +   * @param $string (string) The string that we are processing
    +   * @return        (mixed)  The literal string.  FALSE if the string isn't a literal reference.
    +   */
    +  function _asLiteral($string) {
    +    if (empty($string)) return FALSE;
    +    if (empty($string[0])) return FALSE;
    +    if ($string[0] == '$') {
    +      $remainder = substr($string, 1);
    +      if (is_numeric($remainder)) {
    +        // We have a string reference then.
    +        $stringNumber = (int)$remainder;
    +        if ($stringNumber >= count($this->axPathLiterals)) {
    +            $this->_displayError("Internal error.  Found a string reference that we didn't set in xPathQuery: '$xPathQuery'.", __LINE__, __FILE__);
    +            return FALSE;
    +        }
    +        return $this->axPathLiterals[$stringNumber];
    +      }
    +    }
    +
    +    // It's not a reference then.
    +    return FALSE;
    +  }
    +  
    +  /**
    +   * Adds a literal to our array of literals
    +   *
    +   * In order to make sure we don't interpret literal strings as XPath expressions, we have to
    +   * encode literal strings so that we know that they are not XPaths.
    +   *
    +   * @param $string (string) The literal string that we need to store for future access
    +   * @return        (mixed)  A reference string to this literal.
    +   */
    +  function _addLiteral($string) {
    +    // Store the literal
    +    $literalNumber = count($this->axPathLiterals);
    +    $this->axPathLiterals[$literalNumber] = $string;
    +    $result = '$'.$literalNumber;
    +    return $result;
    +  }
    +
    +  /**
    +   * Look for operators in the expression
    +   *
    +   * Parses through the given expression looking for operators.  If found returns
    +   * the operands and the operator in the resulting array.
    +   *
    +   * @param  $xPathQuery  (string) XPath query to be evaluated.
    +   * @return              (array)  If an operator is found, it returns an array containing
    +   *                               information about the operator.  If no operator is found
    +   *                               then it returns an empty array.  If an operator is found,
    +   *                               but has invalid operands, it returns FALSE.
    +   *                               The resulting array has the following entries:
    +   *                                'operator' => The string version of operator that was found,
    +   *                                              trimmed for whitespace
    +   *                                'left operand' => The left operand, or empty if there was no
    +   *                                              left operand for this operator.
    +   *                                'right operand' => The right operand, or empty if there was no
    +   *                                              right operand for this operator.
    +   */
    +  function _GetOperator($xPathQuery) {
    +    $position = 0;
    +    $operator = '';
    +
    +    // The results of this function can easily be cached.
    +    static $aResultsCache = array();
    +    if (isset($aResultsCache[$xPathQuery])) {
    +      return $aResultsCache[$xPathQuery];
    +    }
    +
    +    // Run through all operators and try to find one.
    +    $opSize = sizeOf($this->operators);
    +    for ($i=0; $i<$opSize; $i++) {
    +      // Pick an operator to try.
    +      $operator = $this->operators[$i];
    +      // Quickcheck. If not present don't wast time searching 'the hard way'
    +      if (strpos($xPathQuery, $operator)===FALSE) continue;
    +      // Special check
    +      $position = $this->_searchString($xPathQuery, $operator);
    +      // Check whether a operator was found.
    +      if ($position <= 0 ) continue;
    +
    +      // Check whether it's the equal operator.
    +      if ($operator == '=') {
    +        // Also look for other operators containing the equal sign.
    +        switch ($xPathQuery[$position-1]) {
    +          case '<' : 
    +            $position--;
    +            $operator = '<=';
    +            break;
    +          case '>' : 
    +            $position--;
    +            $operator = '>=';
    +            break;
    +          case '!' : 
    +            $position--;
    +            $operator = '!=';
    +            break;
    +          default:
    +            // It's a pure = operator then.
    +        }
    +        break;
    +      }
    +
    +      if ($operator == '*') {
    +        // http://www.w3.org/TR/xpath#exprlex:
    +        // "If there is a preceding token and the preceding token is not one of @, ::, (, [, 
    +        // or an Operator, then a * must be recognized as a MultiplyOperator and an NCName must 
    +        // be recognized as an OperatorName."
    +
    +        // Get some substrings.
    +        $character = substr($xPathQuery, $position - 1, 1);
    +      
    +        // Check whether it's a multiply operator or a name test.
    +        if (strchr('/@:([', $character) != FALSE) {
    +          // Don't use the operator.
    +            $position = -1;
    +          continue;
    +        } else {
    +          // The operator is good.  Lets use it.
    +          break;
    +        }
    +      }
    +
    +      // Extremely annoyingly, we could have a node name like "for-each" and we should not
    +      // parse this as a "-" operator.  So if the first char of the right operator is alphabetic,
    +      // then this is NOT an interger operator.
    +      if (strchr('-+*', $operator) != FALSE) {
    +        $rightOperand = trim(substr($xPathQuery, $position + strlen($operator)));
    +        if (strlen($rightOperand) > 1) {
    +          if (preg_match(':^\D$:', $rightOperand[0])) {
    +            // Don't use the operator.
    +            $position = -1;
    +            continue;
    +          } else {
    +            // The operator is good.  Lets use it.
    +            break;
    +          }
    +        }
    +      }
    +
    +      // The operator must be good then :o)
    +      break;
    +
    +    } // end while each($this->operators)
    +
    +    // Did we find an operator?
    +    if ($position == -1) {
    +      $aResultsCache[$xPathQuery] = array();
    +      return array();
    +    }
    +
    +    /////////////////////////////////////////////
    +    // Get the operands
    +
    +    // Get the left and the right part of the expression.
    +    $leftOperand  = trim(substr($xPathQuery, 0, $position));
    +    $rightOperand = trim(substr($xPathQuery, $position + strlen($operator)));
    +  
    +    // Remove whitespaces.
    +    $leftOperand  = trim($leftOperand);
    +    $rightOperand = trim($rightOperand);
    +
    +    /////////////////////////////////////////////
    +    // Check the operands.
    +
    +    if ($leftOperand == '') {
    +      $aResultsCache[$xPathQuery] = FALSE;
    +      return FALSE;
    +    }
    +
    +    if ($rightOperand == '') {
    +      $aResultsCache[$xPathQuery] = FALSE;
    +      return FALSE;
    +    }
    +
    +    // Package up and return what we found.
    +    $aResult = array('operator' => $operator,
    +                'left operand' => $leftOperand,
    +                'right operand' => $rightOperand);
    +
    +    $aResultsCache[$xPathQuery] = $aResult;
    +
    +    return $aResult;
    +  }
    +
    +  /**
    +   * Evaluates an XPath PrimaryExpr
    +   *
    +   * http://www.w3.org/TR/xpath#section-Basics
    +   *
    +   *  [15]    PrimaryExpr    ::= VariableReference  
    +   *                             | '(' Expr ')'  
    +   *                             | Literal  
    +   *                             | Number  
    +   *                             | FunctionCall 
    +   *
    +   * @param  $xPathQuery  (string)   XPath query to be evaluated.
    +   * @param  $context     (array)    The context from which to evaluate
    +   * @param  $results     (mixed)    If the expression could be parsed and evaluated as one of these
    +   *                                 syntactical elements, then this will be either:
    +   *                                    - node-set (an ordered collection of nodes without duplicates) 
    +   *                                    - boolean (true or false) 
    +   *                                    - number (a floating-point number) 
    +   *                                    - string (a sequence of UCS characters) 
    +   * @return              (string)    An empty string if the query was successfully parsed and 
    +   *                                  evaluated, else a string containing the reason for failing.
    +   * @see    evaluate()
    +   */
    +  function _evaluatePrimaryExpr($xPathQuery, $context, &$result) {
    +    $ThisFunctionName = '_evaluatePrimaryExpr';
    +    $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions);
    +    $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction);
    +    if ($bDebugThisFunction) {
    +      echo "Path: $xPathQuery\n";
    +      echo "Context:";
    +      $this->_printContext($context);
    +      echo "\n";
    +    }
    +
    +    // Certain expressions will never be PrimaryExpr, so to speed up processing, cache the
    +    // results we do find from this function.
    +    static $aResultsCache = array();
    +    
    +    // Do while false loop
    +    $error = "";
    +    // If the result is independant of context, then we can cache the result and speed this function
    +    // up on future calls.
    +    $bCacheableResult = FALSE;
    +    do {
    +      if (isset($aResultsCache[$xPathQuery])) {
    +        $error = $aResultsCache[$xPathQuery]['Error'];
    +        $result = $aResultsCache[$xPathQuery]['Result'];
    +        break;
    +      }
    +
    +      // VariableReference 
    +      // ### Not supported.
    +
    +      // Is it a number?
    +      // | Number  
    +      if (is_numeric($xPathQuery)) {
    +        $result = doubleval($xPathQuery);
    +        $bCacheableResult = TRUE;
    +        break;
    +      }
    +
    +      // If it starts with $, and the remainder is a number, then it's a string.
    +      // | Literal  
    +      $literal = $this->_asLiteral($xPathQuery);
    +      if ($literal !== FALSE) {
    +        $result = $xPathQuery;
    +        $bCacheableResult = TRUE;
    +        break;
    +      }
    +
    +      // Is it a function?
    +      // | FunctionCall 
    +      {
    +        // Check whether it's all wrapped in a function.  will be like count(.*) where .* is anything
    +        // text() will try to be matched here, so just explicitly ignore it
    +        $regex = ":^([^\(\)\[\]/]*)\s*\((.*)\)$:U";
    +        if (preg_match($regex, $xPathQuery, $aMatch) && $xPathQuery != "text()") {
    +          $function = $aMatch[1];
    +          $data     = $aMatch[2];
    +          // It is possible that we will get "a() or b()" which will match as function "a" with
    +          // arguments ") or b(" which is clearly wrong... _bracketsCheck() should catch this.
    +          if ($this->_bracketsCheck($data)) {
    +            if (in_array($function, $this->functions)) {
    +              if ($bDebugThisFunction) echo "XPathExpr: $xPathQuery is a $function() function call:\n";
    +              $result = $this->_evaluateFunction($function, $data, $context);
    +              break;
    +            } 
    +          }
    +        }
    +      }
    +
    +      // Is it a bracketed expression?
    +      // | '(' Expr ')'  
    +      // If it is surrounded by () then trim the brackets
    +      $bBrackets = FALSE;
    +      if (preg_match(":^\((.*)\):", $xPathQuery, $aMatches)) {
    +        // Do not keep trimming off the () as we could have "(() and ())"
    +        $bBrackets = TRUE;
    +        $xPathQuery = $aMatches[1];
    +      }
    +
    +      if ($bBrackets) {
    +        // Must be a Expr then.
    +        $result = $this->_evaluateExpr($xPathQuery, $context);
    +        break;
    +      }
    +
    +      // Can't be a PrimaryExpr then.
    +      $error = "Expression is not a PrimaryExpr";
    +      $bCacheableResult = TRUE;
    +    } while (FALSE);
    +    //////////////////////////////////////////////    
    +
    +    // If possible, cache the result.
    +    if ($bCacheableResult) {
    +        $aResultsCache[$xPathQuery]['Error'] = $error;
    +        $aResultsCache[$xPathQuery]['Result'] = $result;
    +    }
    +
    +    $this->_closeDebugFunction($ThisFunctionName, array('result' => $result, 'error' => $error), $bDebugThisFunction);
    +
    +    // Return the result.
    +    return $error;
    +  }
    +
    +  /**
    +   * Evaluates an XPath Expr
    +   *
    +   * $this->evaluate() is the entry point and does some inits, while this 
    +   * function is called recursive internaly for every sub-xPath expresion we find.
    +   * It handles the following syntax, and calls evaluatePathExpr if it finds that none
    +   * of this grammer applies.
    +   *
    +   * http://www.w3.org/TR/xpath#section-Basics
    +   *
    +   * [14]    Expr               ::= OrExpr 
    +   * [21]    OrExpr             ::= AndExpr  
    +   *                                | OrExpr 'or' AndExpr  
    +   * [22]    AndExpr            ::= EqualityExpr  
    +   *                                | AndExpr 'and' EqualityExpr  
    +   * [23]    EqualityExpr       ::= RelationalExpr  
    +   *                                | EqualityExpr '=' RelationalExpr  
    +   *                                | EqualityExpr '!=' RelationalExpr  
    +   * [24]    RelationalExpr     ::= AdditiveExpr  
    +   *                                | RelationalExpr '<' AdditiveExpr  
    +   *                                | RelationalExpr '>' AdditiveExpr  
    +   *                                | RelationalExpr '<=' AdditiveExpr  
    +   *                                | RelationalExpr '>=' AdditiveExpr  
    +   * [25]    AdditiveExpr       ::= MultiplicativeExpr  
    +   *                                | AdditiveExpr '+' MultiplicativeExpr  
    +   *                                | AdditiveExpr '-' MultiplicativeExpr  
    +   * [26]    MultiplicativeExpr ::= UnaryExpr  
    +   *                                | MultiplicativeExpr MultiplyOperator UnaryExpr  
    +   *                                | MultiplicativeExpr 'div' UnaryExpr  
    +   *                                | MultiplicativeExpr 'mod' UnaryExpr  
    +   * [27]    UnaryExpr          ::= UnionExpr  
    +   *                                | '-' UnaryExpr 
    +   * [18]    UnionExpr          ::= PathExpr  
    +   *                                | UnionExpr '|' PathExpr 
    +   *
    +   * NOTE: The effect of the above grammar is that the order of precedence is 
    +   * (lowest precedence first): 
    +   * 1) or 
    +   * 2) and 
    +   * 3) =, != 
    +   * 4) <=, <, >=, > 
    +   * 5) +, -
    +   * 6) *, div, mod
    +   * 7) - (negate)
    +   * 8) |
    +   *
    +   * @param  $xPathQuery  (string)   XPath query to be evaluated.
    +   * @param  $context     (array)    An associative array the describes the context from which
    +   *                                 to evaluate the XPath Expr.  Contains three members:
    +   *                                  'nodePath' => The absolute XPath expression to the context node
    +   *                                  'size' => The context size
    +   *                                  'pos' => The context position
    +   * @return              (mixed)    The result of the XPath expression.  Either:
    +   *                                 node-set (an ordered collection of nodes without duplicates) 
    +   *                                 boolean (true or false) 
    +   *                                 number (a floating-point number) 
    +   *                                 string (a sequence of UCS characters) 
    +   * @see    evaluate()
    +   */
    +  function _evaluateExpr($xPathQuery, $context) {
    +    $ThisFunctionName = '_evaluateExpr';
    +    $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions);
    +    $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction);
    +    if ($bDebugThisFunction) {
    +      echo "Path: $xPathQuery\n";
    +      echo "Context:";
    +      $this->_printContext($context);
    +      echo "\n";    
    +    }
    +
    +    // Numpty check
    +    if (!isset($xPathQuery) || ($xPathQuery == '')) {
    +      $this->_displayError("The \$xPathQuery argument must have a value.", __LINE__, __FILE__);
    +      return FALSE;
    +    }
    +
    +    // At the top level we deal with booleans.  Only if the Expr is just an AdditiveExpr will 
    +    // the result not be a boolean.
    +    //
    +    //
    +    // Between these syntactical elements we get PathExprs.
    +
    +    // Do while false loop
    +    do {
    +      static $aKnownPathExprCache = array();
    +
    +      if (isset($aKnownPathExprCache[$xPathQuery])) {
    +        if ($bDebugThisFunction) echo "XPathExpr is a PathExpr\n";
    +        $result = $this->_evaluatePathExpr($xPathQuery, $context);
    +        break;
    +      }
    +
    +      // Check for operators first, as we could have "() op ()" and the PrimaryExpr will try to
    +      // say that that is an Expr called ") op ("
    +      // Set the default position and the type of the operator.
    +      $aOperatorInfo = $this->_GetOperator($xPathQuery);
    +
    +      // An expression can be one of these, and we should catch these "first" as they are most common
    +      if (empty($aOperatorInfo)) {
    +        $error = $this->_evaluatePrimaryExpr($xPathQuery, $context, $result);
    +        if (empty($error)) {
    +          // It could be parsed as a PrimaryExpr, so look no further :o)
    +          break;
    +        }
    +      }
    +
    +      // Check whether an operator was found.
    +      if (empty($aOperatorInfo)) {
    +        if ($bDebugThisFunction) echo "XPathExpr is a PathExpr\n";
    +        $aKnownPathExprCache[$xPathQuery] = TRUE;
    +        // No operator.  Means we have a PathExpr then.  Go to the next level.
    +        $result = $this->_evaluatePathExpr($xPathQuery, $context);
    +        break;
    +      } 
    +
    +      if ($bDebugThisFunction) { echo "\nFound and operator:"; print_r($aOperatorInfo); }//LEFT:[$leftOperand]  oper:[$operator]  RIGHT:[$rightOperand]";
    +
    +      $operator = $aOperatorInfo['operator'];
    +
    +      /////////////////////////////////////////////
    +      // Recursively process the operator
    +
    +      // Check the kind of operator.
    +      switch ($operator) {
    +        case ' or ': 
    +        case ' and ':
    +          $operatorType = 'Boolean';
    +          break;
    +        case '+': 
    +        case '-': 
    +        case '*':
    +        case ' div ':
    +        case ' mod ':
    +          $operatorType = 'Integer';
    +          break;
    +        case ' | ':
    +          $operatorType = 'NodeSet';
    +          break;
    +        case '<=':
    +        case '<': 
    +        case '>=':
    +        case '>':
    +        case '=': 
    +        case '!=':
    +          $operatorType = 'Multi';
    +          break;
    +        default:
    +            $this->_displayError("Internal error.  Default case of switch statement reached.", __LINE__, __FILE__);
    +      }
    +
    +      if ($bDebugThisFunction) echo "\nOperator is a [$operator]($operatorType operator)";
    +
    +      /////////////////////////////////////////////
    +      // Evaluate the operands
    +
    +      // Evaluate the left part.
    +      if ($bDebugThisFunction) echo "\nEvaluating LEFT:[{$aOperatorInfo['left operand']}]\n";
    +      $left = $this->_evaluateExpr($aOperatorInfo['left operand'], $context);
    +      if ($bDebugThisFunction) {echo "{$aOperatorInfo['left operand']} evals as:\n"; print_r($left); }
    +      
    +      // If it is a boolean operator, it's possible we don't need to evaluate the right part.
    +
    +      // Only evaluate the right part if we need to.
    +      $right = '';
    +      if ($operatorType == 'Boolean') {
    +        // Is the left part false?
    +        $left = $this->_handleFunction_boolean($left, $context);
    +        if (!$left and ($operator == ' and ')) {
    +          $result = FALSE;
    +          break;
    +        } else if ($left and ($operator == ' or ')) {
    +          $result = TRUE;
    +          break;
    +        }
    +      } 
    +
    +      // Evaluate the right part
    +      if ($bDebugThisFunction) echo "\nEvaluating RIGHT:[{$aOperatorInfo['right operand']}]\n";
    +      $right = $this->_evaluateExpr($aOperatorInfo['right operand'], $context);
    +      if ($bDebugThisFunction) {echo "{$aOperatorInfo['right operand']} evals as:\n"; print_r($right); echo "\n";}
    +
    +      /////////////////////////////////////////////
    +      // Combine the operands
    +
    +      // If necessary, work out how to treat the multi operators
    +      if ($operatorType != 'Multi') {
    +        $result = $this->_evaluateOperator($left, $operator, $right, $operatorType, $context);
    +      } else {
    +        // http://www.w3.org/TR/xpath#booleans
    +        // If both objects to be compared are node-sets, then the comparison will be true if and 
    +        // only if there is a node in the first node-set and a node in the second node-set such 
    +        // that the result of performing the comparison on the string-values of the two nodes is 
    +        // true. 
    +        // 
    +        // If one object to be compared is a node-set and the other is a number, then the 
    +        // comparison will be true if and only if there is a node in the node-set such that the 
    +        // result of performing the comparison on the number to be compared and on the result of 
    +        // converting the string-value of that node to a number using the number function is true. 
    +        //
    +        // If one object to be compared is a node-set and the other is a string, then the comparison 
    +        // will be true if and only if there is a node in the node-set such that the result of performing 
    +        // the comparison on the string-value of the node and the other string is true. 
    +        // 
    +        // If one object to be compared is a node-set and the other is a boolean, then the comparison 
    +        // will be true if and only if the result of performing the comparison on the boolean and on 
    +        // the result of converting the node-set to a boolean using the boolean function is true.
    +        if (is_array($left) || is_array($right)) {
    +          if ($bDebugThisFunction) echo "As one of the operands is an array, we will need to loop\n";
    +          if (is_array($left) && is_array($right)) {
    +            $operatorType = 'String';
    +          } elseif (is_numeric($left) || is_numeric($right)) {
    +            $operatorType = 'Integer';
    +          } elseif (is_bool($left)) {
    +            $operatorType = 'Boolean';
    +            $right = $this->_handleFunction_boolean($right, $context);
    +          } elseif (is_bool($right)) {
    +            $operatorType = 'Boolean';
    +            $left = $this->_handleFunction_boolean($left, $context);
    +          } else {
    +            $operatorType = 'String';
    +          }
    +          if ($bDebugThisFunction) echo "Equals operator is a $operatorType operator\n";
    +          // Turn both operands into arrays to simplify logic
    +          $aLeft = $left;
    +          $aRight = $right;
    +          if (!is_array($aLeft)) $aLeft = array($aLeft);
    +          if (!is_array($aRight)) $aRight = array($aRight);
    +          $result = FALSE;
    +          if (!empty($aLeft)) {
    +            foreach ($aLeft as $leftItem) {
    +              if (empty($aRight)) break;
    +              // If the item is from a node set, we should evaluate it's string-value
    +              if (is_array($left)) {
    +                if ($bDebugThisFunction) echo "\tObtaining string-value of LHS:$leftItem as it's from a nodeset\n";
    +                $leftItem = $this->_stringValue($leftItem);
    +              }
    +              foreach ($aRight as $rightItem) {
    +                // If the item is from a node set, we should evaluate it's string-value
    +                if (is_array($right)) {
    +                  if ($bDebugThisFunction) echo "\tObtaining string-value of RHS:$rightItem as it's from a nodeset\n";
    +                  $rightItem = $this->_stringValue($rightItem);
    +                }
    +
    +                if ($bDebugThisFunction) echo "\tEvaluating $leftItem $operator $rightItem\n";
    +                $result = $this->_evaluateOperator($leftItem, $operator, $rightItem, $operatorType, $context);
    +                if ($result === TRUE) break;
    +              }
    +              if ($result === TRUE) break;
    +            }
    +          }
    +        } 
    +        // When neither object to be compared is a node-set and the operator is = or !=, then the 
    +        // objects are compared by converting them to a common type as follows and then comparing 
    +        // them. 
    +        //
    +        // If at least one object to be compared is a boolean, then each object to be compared 
    +        // is converted to a boolean as if by applying the boolean function. 
    +        //
    +        // Otherwise, if at least one object to be compared is a number, then each object to be 
    +        // compared is converted to a number as if by applying the number function. 
    +        //
    +        // Otherwise, both objects to be compared are converted to strings as if by applying 
    +        // the string function. 
    +        //  
    +        // The = comparison will be true if and only if the objects are equal; the != comparison 
    +        // will be true if and only if the objects are not equal. Numbers are compared for equality 
    +        // according to IEEE 754 [IEEE 754]. Two booleans are equal if either both are true or 
    +        // both are false. Two strings are equal if and only if they consist of the same sequence 
    +        // of UCS characters.
    +        else {
    +          if (is_bool($left) || is_bool($right)) {
    +            $operatorType = 'Boolean';
    +          } elseif (is_numeric($left) || is_numeric($right)) {
    +            $operatorType = 'Integer';
    +          } else {
    +            $operatorType = 'String';
    +          }
    +          if ($bDebugThisFunction) echo "Equals operator is a $operatorType operator\n";
    +          $result = $this->_evaluateOperator($left, $operator, $right, $operatorType, $context);
    +        }
    +      }
    +
    +    } while (FALSE);
    +    //////////////////////////////////////////////
    +
    +    $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction);
    +
    +    // Return the result.
    +    return $result;
    +  }
    +
    +  /**
    +   * Evaluate the result of an operator whose operands have been evaluated
    +   *
    +   * If the operator type is not "NodeSet", then neither the left or right operators 
    +   * will be node sets, as the processing when one or other is an array is complex,
    +   * and should be handled by the caller.
    +   *
    +   * @param  $left          (mixed)   The left operand
    +   * @param  $right         (mixed)   The right operand
    +   * @param  $operator      (string)  The operator to use to combine the operands
    +   * @param  $operatorType  (string)  The type of the operator.  Either 'Boolean', 
    +   *                                  'Integer', 'String', or 'NodeSet'
    +   * @param  $context     (array)    The context from which to evaluate
    +   * @return              (mixed)    The result of the XPath expression.  Either:
    +   *                                 node-set (an ordered collection of nodes without duplicates) 
    +   *                                 boolean (true or false) 
    +   *                                 number (a floating-point number) 
    +   *                                 string (a sequence of UCS characters) 
    +   */
    +  function _evaluateOperator($left, $operator, $right, $operatorType, $context) {
    +    $ThisFunctionName = '_evaluateOperator';
    +    $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions);
    +    $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction);
    +    if ($bDebugThisFunction) {
    +      echo "left: $left\n";
    +      echo "right: $right\n";
    +      echo "operator: $operator\n";
    +      echo "operator type: $operatorType\n";
    +    }
    +
    +    // Do while false loop
    +    do {
    +      // Handle the operator depending on the operator type.
    +      switch ($operatorType) {
    +        case 'Boolean':
    +          {
    +            // Boolify the arguments.  (The left arg is already a bool)
    +            $right = $this->_handleFunction_boolean($right, $context);
    +            switch ($operator) {
    +              case '=': // Compare the two results.
    +                $result = (bool)($left == $right); 
    +                break;
    +              case ' or ': // Return the two results connected by an 'or'.
    +                $result = (bool)( $left or $right );
    +                break;
    +              case ' and ': // Return the two results connected by an 'and'.
    +                $result = (bool)( $left and $right );
    +                break;
    +              case '!=': // Check whether the two results are not equal.
    +                $result = (bool)( $left != $right );
    +                break;
    +              default:
    +                $this->_displayError("Internal error.  Default case of switch statement reached.", __LINE__, __FILE__);
    +            }
    +          }
    +          break;
    +        case 'Integer':
    +          {
    +            // Convert both left and right operands into numbers.
    +            if (empty($left) && ($operator == '-')) {
    +              // There may be no left operator if the op is '-'
    +              $left = 0;
    +            } else {
    +              $left = $this->_handleFunction_number($left, $context);
    +            }
    +            $right = $this->_handleFunction_number($right, $context);
    +            if ($bDebugThisFunction) echo "\nLeft is $left, Right is $right\n";
    +            switch ($operator) {
    +              case '=': // Compare the two results.
    +                $result = (bool)($left == $right); 
    +                break;
    +              case '!=': // Compare the two results.
    +                $result = (bool)($left != $right); 
    +                break;
    +              case '+': // Return the result by adding one result to the other.
    +                $result = $left + $right;
    +                break;
    +              case '-': // Return the result by decrease one result by the other.
    +                $result = $left - $right;
    +                break;
    +              case '*': // Return a multiplication of the two results.
    +                $result =  $left * $right;
    +                break;
    +              case ' div ': // Return a division of the two results.
    +                $result = $left / $right;
    +                break;
    +              case ' mod ': // Return a modulo division of the two results.
    +                $result = $left % $right;
    +                break;
    +              case '<=': // Compare the two results.
    +                $result = (bool)( $left <= $right );
    +                break;
    +              case '<': // Compare the two results.
    +                $result = (bool)( $left < $right );
    +                break;
    +              case '>=': // Compare the two results.
    +                $result = (bool)( $left >= $right );
    +                break;
    +              case '>': // Compare the two results.
    +                $result = (bool)( $left > $right );
    +                break;
    +              default:
    +                $this->_displayError("Internal error.  Default case of switch statement reached.", __LINE__, __FILE__);
    +            }
    +          }
    +          break;
    +        case 'NodeSet':
    +          // Add the nodes to the result set
    +          $result = array_merge($left, $right);
    +          // Remove duplicated nodes.
    +          $result = array_unique($result);
    +
    +          // Preserve doc order if there was more than one query.
    +          if (count($result) > 1) {
    +            $result = $this->_sortByDocOrder($result);
    +          }
    +          break;
    +        case 'String':
    +            $left = $this->_handleFunction_string($left, $context);
    +            $right = $this->_handleFunction_string($right, $context);
    +            if ($bDebugThisFunction) echo "\nLeft is $left, Right is $right\n";
    +            switch ($operator) {
    +              case '=': // Compare the two results.
    +                $result = (bool)($left == $right); 
    +                break;
    +              case '!=': // Compare the two results.
    +                $result = (bool)($left != $right); 
    +                break;
    +              default:
    +                $this->_displayError("Internal error.  Default case of switch statement reached.", __LINE__, __FILE__);
    +            }
    +          break;
    +        default:
    +          $this->_displayError("Internal error.  Default case of switch statement reached.", __LINE__, __FILE__);
    +      }
    +    } while (FALSE);
    +
    +    //////////////////////////////////////////////
    +
    +    $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction);
    +
    +    // Return the result.
    +    return $result;
    +  }
    +  
    +  /**
    +   * Evaluates an XPath PathExpr
    +   *
    +   * It handles the following syntax:
    +   *
    +   * http://www.w3.org/TR/xpath#node-sets
    +   * http://www.w3.org/TR/xpath#NT-LocationPath
    +   * http://www.w3.org/TR/xpath#path-abbrev
    +   * http://www.w3.org/TR/xpath#NT-Step
    +   *
    +   * [19]   PathExpr              ::= LocationPath  
    +   *                                  | FilterExpr  
    +   *                                  | FilterExpr '/' RelativeLocationPath  
    +   *                                  | FilterExpr '//' RelativeLocationPath
    +   * [20]   FilterExpr            ::= PrimaryExpr  
    +   *                                  | FilterExpr Predicate 
    +   * [1]    LocationPath          ::= RelativeLocationPath  
    +   *                                  | AbsoluteLocationPath  
    +   * [2]    AbsoluteLocationPath  ::= '/' RelativeLocationPath?  
    +   *                                  | AbbreviatedAbsoluteLocationPath
    +   * [3]    RelativeLocationPath  ::= Step  
    +   *                                  | RelativeLocationPath '/' Step  
    +   *                                  | AbbreviatedRelativeLocationPath
    +   * [4]    Step                  ::= AxisSpecifier NodeTest Predicate*  
    +   *                                  | AbbreviatedStep  
    +   * [5]    AxisSpecifier         ::= AxisName '::'  
    +   *                                  | AbbreviatedAxisSpecifier  
    +   * [10]   AbbreviatedAbsoluteLocationPath
    +   *                              ::= '//' RelativeLocationPath
    +   * [11]   AbbreviatedRelativeLocationPath
    +   *                              ::= RelativeLocationPath '//' Step
    +   * [12]   AbbreviatedStep       ::= '.'  
    +   *                                  | '..'  
    +   * [13]   AbbreviatedAxisSpecifier    
    +   *                              ::= '@'? 
    +   *
    +   * If you expand all the abbreviated versions, then the grammer simplifies to:
    +   *
    +   * [19]   PathExpr              ::= RelativeLocationPath  
    +   *                                  | '/' RelativeLocationPath?  
    +   *                                  | FilterExpr  
    +   *                                  | FilterExpr '/' RelativeLocationPath  
    +   * [20]   FilterExpr            ::= PrimaryExpr  
    +   *                                  | FilterExpr Predicate 
    +   * [3]    RelativeLocationPath  ::= Step  
    +   *                                  | RelativeLocationPath '/' Step  
    +   * [4]    Step                  ::= AxisName '::' NodeTest Predicate*  
    +   *
    +   * Conceptually you can say that we should split by '/' and try to treat the parts
    +   * as steps, and if that fails then try to treat it as a PrimaryExpr.  
    +   * 
    +   * @param  $PathExpr   (string) PathExpr syntactical element
    +   * @param  $context    (array)  The context from which to evaluate
    +   * @return             (mixed)  The result of the XPath expression.  Either:
    +   *                               node-set (an ordered collection of nodes without duplicates) 
    +   *                               boolean (true or false) 
    +   *                               number (a floating-point number) 
    +   *                               string (a sequence of UCS characters) 
    +   * @see    evaluate()
    +   */
    +  function _evaluatePathExpr($PathExpr, $context) {
    +    $ThisFunctionName = '_evaluatePathExpr';
    +    $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions);
    +    $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction);
    +    if ($bDebugThisFunction) {
    +      echo "PathExpr: $PathExpr\n";
    +      echo "Context:";
    +      $this->_printContext($context);
    +      echo "\n";
    +    }
    +    
    +    // Numpty check
    +    if (empty($PathExpr)) {
    +      $this->_displayError("The \$PathExpr argument must have a value.", __LINE__, __FILE__);
    +      return FALSE;
    +    }
    +    //////////////////////////////////////////////
    +
    +    // Parsing the expression into steps is a cachable operation as it doesn't depend on the context
    +    static $aResultsCache = array();
    +
    +    if (isset($aResultsCache[$PathExpr])) {
    +      $steps = $aResultsCache[$PathExpr];
    +    } else {
    +      // Note that we have used $this->slashes2descendant to simplify this logic, so the 
    +      // "Abbreviated" paths basically never exist as '//' never exists.
    +
    +      // mini syntax check
    +      if (!$this->_bracketsCheck($PathExpr)) {
    +        $this->_displayError('While parsing an XPath query, in the PathExpr "' .
    +        $PathExpr.
    +        '", there was an invalid number of brackets or a bracket mismatch.', __LINE__, __FILE__);
    +      }
    +      // Save the current path.
    +      $this->currentXpathQuery = $PathExpr;
    +      // Split the path at every slash *outside* a bracket.
    +      $steps = $this->_bracketExplode('/', $PathExpr);
    +      if ($bDebugThisFunction) { echo "
    Split the path '$PathExpr' at every slash *outside* a bracket.\n "; print_r($steps); } + // Check whether the first element is empty. + if (empty($steps[0])) { + // Remove the first and empty element. It's a starting '//'. + array_shift($steps); + } + $aResultsCache[$PathExpr] = $steps; + } + + // Start to evaluate the steps. + // ### Consider implementing an evaluateSteps() function that removes recursion from + // evaluateStep() + $result = $this->_evaluateStep($steps, $context); + + // Preserve doc order if there was more than one result + if (count($result) > 1) { + $result = $this->_sortByDocOrder($result); + } + ////////////////////////////////////////////// + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + // Return the result. + return $result; + } + + /** + * Sort an xPathSet by doc order. + * + * @param $xPathSet (array) Array of full paths to nodes that need to be sorted + * @return (array) Array containing the same contents as $xPathSet, but + * with the contents in doc order + */ + function _sortByDocOrder($xPathSet) { + $ThisFunctionName = '_sortByDocOrder'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "_sortByDocOrder(xPathSet:[".count($xPathSet)."])"; + echo "xPathSet:\n"; + print_r($xPathSet); + echo "
    \n"; + } + ////////////////////////////////////////////// + + $aResult = array(); + + // Spot some common shortcuts. + if (count($xPathSet) < 1) { + $aResult = $xPathSet; + } else { + // Build an array of doc-pos indexes. + $aDocPos = array(); + $nodeCount = count($this->nodeIndex); + $aPaths = array_keys($this->nodeIndex); + if ($bDebugThisFunction) { + echo "searching for path indices in array_keys(this->nodeIndex)...\n"; + //print_r($aPaths); + } + + // The last index we found. In general the elements will be in groups + // that are themselves in order. + $iLastIndex = 0; + foreach ($xPathSet as $path) { + // Cycle round the nodes, starting at the last index, looking for the path. + $foundNode = FALSE; + for ($iIndex = $iLastIndex; $iIndex < $nodeCount + $iLastIndex; $iIndex++) { + $iThisIndex = $iIndex % $nodeCount; + if (!strcmp($aPaths[$iThisIndex],$path)) { + // we have found the doc-position index of the path + $aDocPos[] = $iThisIndex; + $iLastIndex = $iThisIndex; + $foundNode = TRUE; + break; + } + } + if ($bDebugThisFunction) { + if (!$foundNode) + echo "Error: $path not found in \$this->nodeIndex\n"; + else + echo "Found node after ".($iIndex - $iLastIndex)." iterations\n"; + } + } + // Now count the number of doc pos we have and the number of results and + // confirm that we have the same number of each. + $iDocPosCount = count($aDocPos); + $iResultCount = count($xPathSet); + if ($iDocPosCount != $iResultCount) { + if ($bDebugThisFunction) { + echo "count(\$aDocPos)=$iDocPosCount; count(\$result)=$iResultCount\n"; + print_r(array_keys($this->nodeIndex)); + } + $this->_displayError('Results from _InternalEvaluate() are corrupt. '. + 'Do you need to call reindexNodeTree()?', __LINE__, __FILE__); + } + + // Now sort the indexes. + sort($aDocPos); + + // And now convert back to paths. + $iPathCount = count($aDocPos); + for ($iIndex = 0; $iIndex < $iPathCount; $iIndex++) { + $aResult[] = $aPaths[$aDocPos[$iIndex]]; + } + } + + // Our result from the function is this array. + $result = $aResult; + + ////////////////////////////////////////////// + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + // Return the result. + return $result; + } + + /** + * Evaluate a step from a XPathQuery expression at a specific contextPath. + * + * Steps are the arguments of a XPathQuery when divided by a '/'. A contextPath is a + * absolute XPath (or vector of XPaths) to a starting node(s) from which the step should + * be evaluated. + * + * @param $steps (array) Vector containing the remaining steps of the current + * XPathQuery expression. + * @param $context (array) The context from which to evaluate + * @return (array) Vector of absolute XPath's as a result of the step + * evaluation. The results will not necessarily be in doc order + * @see _evaluatePathExpr() + */ + function _evaluateStep($steps, $context) { + $ThisFunctionName = '_evaluateStep'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Context:"; + $this->_printContext($context); + echo "\n"; + echo "Steps: "; + print_r($steps); + echo "
    \n"; + } + ////////////////////////////////////////////// + + $result = array(); // Create an empty array for saving the abs. XPath's found. + + $contextPaths = array(); // Create an array to save the new contexts. + $step = trim(array_shift($steps)); // Get this step. + if ($bDebugThisFunction) echo __LINE__.":Evaluating step $step\n"; + + $axis = $this->_getAxis($step); // Get the axis of the current step. + + // If there was no axis, then it must be a PrimaryExpr + if ($axis == FALSE) { + if ($bDebugThisFunction) echo __LINE__.":Step is not an axis but a PrimaryExpr\n"; + // ### This isn't correct, as the result of this function might not be a node set. + $error = $this->_evaluatePrimaryExpr($step, $context, $contextPaths); + if (!empty($error)) { + $this->_displayError("Expression failed to parse as PrimaryExpr because: $error" + , __LINE__, __FILE__, FALSE); + } + } else { + if ($bDebugThisFunction) { echo __LINE__.":Axis of step is:\n"; print_r($axis); echo "\n";} + $method = '_handleAxis_' . $axis['axis']; // Create the name of the method. + + // Check whether the axis handler is defined. If not display an error message. + if (!method_exists($this, $method)) { + $this->_displayError('While parsing an XPath query, the axis ' . + $axis['axis'] . ' could not be handled, because this version does not support this axis.', __LINE__, __FILE__); + } + if ($bDebugThisFunction) echo __LINE__.":Calling user method $method\n"; + + // Perform an axis action. + $contextPaths = $this->$method($axis, $context['nodePath']); + if ($bDebugThisFunction) { echo __LINE__.":We found these contexts from this step:\n"; print_r( $contextPaths ); echo "\n";} + } + + // Check whether there are predicates. + if (count($contextPaths) > 0 && count($axis['predicate']) > 0) { + if ($bDebugThisFunction) echo __LINE__.":Filtering contexts by predicate...\n"; + + // Check whether each node fits the predicates. + $contextPaths = $this->_checkPredicates($contextPaths, $axis['predicate']); + } + + // Check whether there are more steps left. + if (count($steps) > 0) { + if ($bDebugThisFunction) echo __LINE__.":Evaluating next step given the context of the first step...\n"; + + // Continue the evaluation of the next steps. + + // Run through the array. + $size = sizeOf($contextPaths); + for ($pos=0; $pos<$size; $pos++) { + // Build new context + $newContext = array('nodePath' => $contextPaths[$pos], 'size' => $size, 'pos' => $pos + 1); + if ($bDebugThisFunction) echo __LINE__.":Evaluating step for the {$contextPaths[$pos]} context...\n"; + // Call this method for this single path. + $xPathSetNew = $this->_evaluateStep($steps, $newContext); + if ($bDebugThisFunction) {echo "New results for this context:\n"; print_r($xPathSetNew);} + $result = array_merge($result, $xPathSetNew); + } + + // Remove duplicated nodes. + $result = array_unique($result); + } else { + $result = $contextPaths; // Save the found contexts. + } + + ////////////////////////////////////////////// + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + // Return the result. + return $result; + } + + /** + * Checks whether a node matches predicates. + * + * This method checks whether a list of nodes passed to this method match + * a given list of predicates. + * + * @param $xPathSet (array) Array of full paths of all nodes to be tested. + * @param $predicates (array) Array of predicates to use. + * @return (array) Vector of absolute XPath's that match the given predicates. + * @see _evaluateStep() + */ + function _checkPredicates($xPathSet, $predicates) { + $ThisFunctionName = '_checkPredicates'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "XPathSet:"; + print_r($xPathSet); + echo "Predicates:"; + print_r($predicates); + echo "
    "; + } + ////////////////////////////////////////////// + // Create an empty set of nodes. + $result = array(); + + // Run through all predicates. + $pSize = sizeOf($predicates); + for ($j=0; $j<$pSize; $j++) { + $predicate = $predicates[$j]; + if ($bDebugThisFunction) echo "Evaluating predicate \"$predicate\"\n"; + + // This will contain all the nodes that match this predicate + $aNewSet = array(); + + // Run through all nodes. + $contextSize = count($xPathSet); + for ($contextPos=0; $contextPos<$contextSize; $contextPos++) { + $xPath = $xPathSet[$contextPos]; + + // Build the context for this predicate + $context = array('nodePath' => $xPath, 'size' => $contextSize, 'pos' => $contextPos + 1); + + // Check whether the predicate is just an number. + if (preg_match('/^\d+$/', $predicate)) { + if ($bDebugThisFunction) echo "Taking short cut and calling _handleFunction_position() directly.\n"; + // Take a short cut. If it is just a position, then call + // _handleFunction_position() directly. 70% of the + // time this will be the case. ## N.S +// $check = (bool) ($predicate == $context['pos']); + $check = (bool) ($predicate == $this->_handleFunction_position('', $context)); + } else { + // Else do the predicate check the long and through way. + $check = $this->_evaluateExpr($predicate, $context); + } + if ($bDebugThisFunction) { + echo "Evaluating the predicate returned "; + var_dump($check); + echo "\n"; + } + + if (is_int($check)) { // Check whether it's an integer. + // Check whether it's the current position. + $check = (bool) ($check == $this->_handleFunction_position('', $context)); + } else { + $check = (bool) ($this->_handleFunction_boolean($check, $context)); +// if ($bDebugThisFunction) {echo $this->_handleFunction_string($check, $context);} + } + + if ($bDebugThisFunction) echo "Node $xPath matches predicate $predicate: " . (($check) ? "TRUE" : "FALSE") ."\n"; + + // Do we add it? + if ($check) $aNewSet[] = $xPath; + } + + // Use the newly filtered list. + $xPathSet = $aNewSet; + + if ($bDebugThisFunction) {echo "Node set now contains : "; print_r($xPathSet); } + } + + $result = $xPathSet; + + ////////////////////////////////////////////// + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + // Return the array of nodes. + return $result; + } + + /** + * Evaluates an XPath function + * + * This method evaluates a given XPath function with its arguments on a + * specific node of the document. + * + * @param $function (string) Name of the function to be evaluated. + * @param $arguments (string) String containing the arguments being + * passed to the function. + * @param $context (array) The context from which to evaluate + * @return (mixed) This method returns the result of the evaluation of + * the function. Depending on the function the type of the + * return value can be different. + * @see evaluate() + */ + function _evaluateFunction($function, $arguments, $context) { + $ThisFunctionName = '_evaluateFunction'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + if (is_array($arguments)) { + echo "Arguments:\n"; + print_r($arguments); + } else { + echo "Arguments: $arguments\n"; + } + echo "Context:"; + $this->_printContext($context); + echo "\n"; + echo "
    \n"; + } + ///////////////////////////////////// + // Remove whitespaces. + $function = trim($function); + $arguments = trim($arguments); + // Create the name of the function handling function. + $method = '_handleFunction_'. $function; + + // Check whether the function handling function is available. + if (!method_exists($this, $method)) { + // Display an error message. + $this->_displayError("While parsing an XPath query, ". + "the function \"$function\" could not be handled, because this ". + "version does not support this function.", __LINE__, __FILE__); + } + if ($bDebugThisFunction) echo "Calling function $method($arguments)\n"; + + // Return the result of the function. + $result = $this->$method($arguments, $context); + + ////////////////////////////////////////////// + // Return the nodes found. + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + // Return the result. + return $result; + } + + /** + * Checks whether a node matches a node-test. + * + * This method checks whether a node in the document matches a given node-test. + * A node test is something like text(), node(), or an element name. + * + * @param $contextPath (string) Full xpath of the node, which should be tested for + * matching the node-test. + * @param $nodeTest (string) String containing the node-test for the node. + * @return (boolean) This method returns TRUE if the node matches the + * node-test, otherwise FALSE. + * @see evaluate() + */ + function _checkNodeTest($contextPath, $nodeTest) { + // Empty node test means that it must match + if (empty($nodeTest)) return TRUE; + + if ($nodeTest == '*') { + // * matches all element nodes. + return (!preg_match(':/[^/]+\(\)\[\d+\]$:U', $contextPath)); + } + elseif (preg_match('/^[\w-:\.]+$/', $nodeTest)) { + // http://www.w3.org/TR/2000/REC-xml-20001006#NT-Name + // The real spec for what constitutes whitespace is quite elaborate, and + // we currently just hope that "\w" catches them all. In reality it should + // start with a letter too, not a number, but we've just left it simple. + // It's just a node name test. It should end with "/$nodeTest[x]" + return (preg_match('"/'.$nodeTest.'\[\d+\]$"', $contextPath)); + } + elseif (preg_match('/\(/U', $nodeTest)) { // Check whether it's a function. + // Get the type of function to use. + $function = $this->_prestr($nodeTest, '('); + // Check whether the node fits the method. + switch ($function) { + case 'node': // Add this node to the list of nodes. + return TRUE; + case 'text': // Check whether the node has some text. + $tmp = implode('', $this->nodeIndex[$contextPath]['textParts']); + if (!empty($tmp)) { + return TRUE; // Add this node to the list of nodes. + } + break; +/******** NOT supported (yet?) + case 'comment': // Check whether the node has some comment. + if (!empty($this->nodeIndex[$contextPath]['comment'])) { + return TRUE; // Add this node to the list of nodes. + } + break; + case 'processing-instruction': + $literal = $this->_afterstr($axis['node-test'], '('); // Get the literal argument. + $literal = substr($literal, 0, strlen($literal) - 1); // Cut the literal. + + // Check whether a literal was given. + if (!empty($literal)) { + // Check whether the node's processing instructions are matching the literals given. + if ($this->nodeIndex[$context]['processing-instructions'] == $literal) { + return TRUE; // Add this node to the node-set. + } + } else { + // Check whether the node has processing instructions. + if (!empty($this->nodeIndex[$contextPath]['processing-instructions'])) { + return TRUE; // Add this node to the node-set. + } + } + break; +***********/ + default: // Display an error message. + $this->_displayError('While parsing an XPath query there was an undefined function called "' . + str_replace($function, ''.$function.'', $this->currentXpathQuery) .'"', __LINE__, __FILE__); + } + } + else { // Display an error message. + $this->_displayError("While parsing the XPath query \"{$this->currentXpathQuery}\" ". + "an empty and therefore invalid node-test has been found.", __LINE__, __FILE__, FALSE); + } + + return FALSE; // Don't add this context. + } + + //----------------------------------------------------------------------------------------- + // XPath ------ XPath AXIS Handlers ------ + //----------------------------------------------------------------------------------------- + + /** + * Retrieves axis information from an XPath query step. + * + * This method tries to extract the name of the axis and its node-test + * from a given step of an XPath query at a given node. If it can't parse + * the step, then we treat it as a PrimaryExpr. + * + * [4] Step ::= AxisSpecifier NodeTest Predicate* + * | AbbreviatedStep + * [5] AxisSpecifier ::= AxisName '::' + * | AbbreviatedAxisSpecifier + * [12] AbbreviatedStep ::= '.' + * | '..' + * [13] AbbreviatedAxisSpecifier + * ::= '@'? + * + * [7] NodeTest ::= NameTest + * | NodeType '(' ')' + * | 'processing-instruction' '(' Literal ')' + * [37] NameTest ::= '*' + * | NCName ':' '*' + * | QName + * [38] NodeType ::= 'comment' + * | 'text' + * | 'processing-instruction' + * | 'node' + * + * @param $step (string) String containing a step of an XPath query. + * @return (array) Contains information about the axis found in the step, or FALSE + * if the string isn't a valid step. + * @see _evaluateStep() + */ + function _getAxis($step) { + // The results of this function are very cachable, as it is completely independant of context. + static $aResultsCache = array(); + + // Create an array to save the axis information. + $axis = array( + 'axis' => '', + 'node-test' => '', + 'predicate' => array() + ); + + $cacheKey = $step; + do { // parse block + $parseBlock = 1; + + if (isset($aResultsCache[$cacheKey])) { + return $aResultsCache[$cacheKey]; + } else { + // We have some danger of causing recursion here if we refuse to parse a step as having an + // axis, and demand it be treated as a PrimaryExpr. So if we are going to fail, make sure + // we record what we tried, so that we can catch to see if it comes straight back. + $guess = array( + 'axis' => 'child', + 'node-test' => $step, + 'predicate' => array()); + $aResultsCache[$cacheKey] = $guess; + } + + /////////////////////////////////////////////////// + // Spot the steps that won't come with an axis + + // Check whether the step is empty or only self. + if (empty($step) OR ($step == '.') OR ($step == 'current()')) { + // Set it to the default value. + $step = '.'; + $axis['axis'] = 'self'; + $axis['node-test'] = '*'; + break $parseBlock; + } + + if ($step == '..') { + // Select the parent axis. + $axis['axis'] = 'parent'; + $axis['node-test'] = '*'; + break $parseBlock; + } + + /////////////////////////////////////////////////// + // Pull off the predicates + + // Check whether there are predicates and add the predicate to the list + // of predicates without []. Get contents of every [] found. + $groups = $this->_getEndGroups($step); +//print_r($groups); + $groupCount = count($groups); + while (($groupCount > 0) && ($groups[$groupCount - 1][0] == '[')) { + // Remove the [] and add the predicate to the top of the list + $predicate = substr($groups[$groupCount - 1], 1, -1); + array_unshift($axis['predicate'], $predicate); + // Pop a group off the end of the list + array_pop($groups); + $groupCount--; + } + + // Finally stick the rest back together and this is the rest of our step + if ($groupCount > 0) { + $step = implode('', $groups); + } + + /////////////////////////////////////////////////// + // Pull off the axis + + // Check for abbreviated syntax + if ($step[0] == '@') { + // Use the attribute axis and select the attribute. + $axis['axis'] = 'attribute'; + $step = substr($step, 1); + } else { + // Check whether the axis is given in plain text. + if (preg_match("/^([^:]*)::(.*)$/", $step, $match)) { + // Split the step to extract axis and node-test. + $axis['axis'] = $match[1]; + $step = $match[2]; + } else { + // The default axis is child + $axis['axis'] = 'child'; + } + } + + /////////////////////////////////////////////////// + // Process the rest which will either a node test, or else this isn't a step. + + // Check whether is an abbreviated syntax. + if ($step == '*') { + // Use the child axis and select all children. + $axis['node-test'] = '*'; + break $parseBlock; + } + + // ### I'm pretty sure our current handling of cdata is a fudge, and we should + // really do this better, but leave this as is for now. + if ($step == "text()") { + // Handle the text node + $axis["node-test"] = "cdata"; + break $parseBlock; + } + + // There are a few node tests that we match verbatim. + if ($step == "node()" + || $step == "comment()" + || $step == "text()" + || $step == "processing-instruction") { + $axis["node-test"] = $step; + break $parseBlock; + } + + // processing-instruction() is allowed to take an argument, but if it does, the argument + // is a literal, which we will have parsed out to $[number]. + if (preg_match(":processing-instruction\(\$\d*\):", $step)) { + $axis["node-test"] = $step; + break $parseBlock; + } + + // The only remaining way this can be a step, is if the remaining string is a simple name + // or else a :* name. + // http://www.w3.org/TR/xpath#NT-NameTest + // NameTest ::= '*' + // | NCName ':' '*' + // | QName + // QName ::= (Prefix ':')? LocalPart + // Prefix ::= NCName + // LocalPart ::= NCName + // + // ie + // NameTest ::= '*' + // | NCName ':' '*' + // | (NCName ':')? NCName + // NCName ::= (Letter | '_') (NCNameChar)* + $NCName = "[a-zA-Z_][\w\.\-_]*"; + if (preg_match("/^$NCName:$NCName$/", $step) + || preg_match("/^$NCName:*$/", $step)) { + $axis['node-test'] = $step; + if (!empty($this->parseOptions[XML_OPTION_CASE_FOLDING])) { + // Case in-sensitive + $axis['node-test'] = strtoupper($axis['node-test']); + } + // Not currently recursing + $LastFailedStep = ''; + $LastFailedContext = ''; + break $parseBlock; + } + + // It's not a node then, we must treat it as a PrimaryExpr + // Check for recursion + if ($LastFailedStep == $step) { + $this->_displayError('Recursion detected while parsing an XPath query, in the step ' . + str_replace($step, ''.$step.'', $this->currentXpathQuery) + , __LINE__, __FILE__, FALSE); + $axis['node-test'] = $step; + } else { + $LastFailedStep = $step; + $axis = FALSE; + } + + } while(FALSE); // end parse block + + // Check whether it's a valid axis. + if ($axis !== FALSE) { + if (!in_array($axis['axis'], array_merge($this->axes, array('function')))) { + // Display an error message. + $this->_displayError('While parsing an XPath query, in the step ' . + str_replace($step, ''.$step.'', $this->currentXpathQuery) . + ' the invalid axis ' . $axis['axis'] . ' was found.', __LINE__, __FILE__, FALSE); + } + } + + // Cache the real axis information + $aResultsCache[$cacheKey] = $axis; + + // Return the axis information. + return $axis; + } + + + /** + * Handles the XPath child axis. + * + * This method handles the XPath child axis. It essentially filters out the + * children to match the name specified after the '/'. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should + * be processed. + * @return (array) A vector containing all nodes that were found, during + * the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_child($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set to hold the results of the child matches + if ($axis["node-test"] == "cdata") { + if (!isSet($this->nodeIndex[$contextPath]['textParts']) ) return ''; + $tSize = sizeOf($this->nodeIndex[$contextPath]['textParts']); + for ($i=1; $i<=$tSize; $i++) { + $xPathSet[] = $contextPath . '/text()['.$i.']'; + } + } + else { + // Get a list of all children. + $allChildren = $this->nodeIndex[$contextPath]['childNodes']; + + // Run through all children in the order they where set. + $cSize = sizeOf($allChildren); + for ($i=0; $i<$cSize; $i++) { + $childPath = $contextPath .'/'. $allChildren[$i]['name'] .'['. $allChildren[$i]['contextPos'] .']'; + $textChildPath = $contextPath.'/text()['.($i + 1).']'; + // Check the text node + if ($this->_checkNodeTest($textChildPath, $axis['node-test'])) { // node test check + $xPathSet[] = $textChildPath; // Add the child to the node-set. + } + // Check the actual node + if ($this->_checkNodeTest($childPath, $axis['node-test'])) { // node test check + $xPathSet[] = $childPath; // Add the child to the node-set. + } + } + + // Finally there will be one more text node to try + $textChildPath = $contextPath.'/text()['.($cSize + 1).']'; + // Check the text node + if ($this->_checkNodeTest($textChildPath, $axis['node-test'])) { // node test check + $xPathSet[] = $textChildPath; // Add the child to the node-set. + } + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath parent axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the + * evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_parent($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Check whether the parent matches the node-test. + $parentPath = $this->getParentXPath($contextPath); + if ($this->_checkNodeTest($parentPath, $axis['node-test'])) { + $xPathSet[] = $parentPath; // Add this node to the list of nodes. + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath attribute axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_attribute($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Check whether all nodes should be selected. + $nodeAttr = $this->nodeIndex[$contextPath]['attributes']; + if ($axis['node-test'] == '*' + || $axis['node-test'] == 'node()') { + foreach($nodeAttr as $key=>$dummy) { // Run through the attributes. + $xPathSet[] = $contextPath.'/attribute::'.$key; // Add this node to the node-set. + } + } + elseif (isset($nodeAttr[$axis['node-test']])) { + $xPathSet[] = $contextPath . '/attribute::'. $axis['node-test']; // Add this node to the node-set. + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath self axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_self($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Check whether the context match the node-test. + if ($this->_checkNodeTest($contextPath, $axis['node-test'])) { + $xPathSet[] = $contextPath; // Add this node to the node-set. + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath descendant axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_descendant($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Get a list of all children. + $allChildren = $this->nodeIndex[$contextPath]['childNodes']; + + // Run through all children in the order they where set. + $cSize = sizeOf($allChildren); + for ($i=0; $i<$cSize; $i++) { + $childPath = $allChildren[$i]['xpath']; + // Check whether the child matches the node-test. + if ($this->_checkNodeTest($childPath, $axis['node-test'])) { + $xPathSet[] = $childPath; // Add the child to the list of nodes. + } + // Recurse to the next level. + $xPathSet = array_merge($xPathSet, $this->_handleAxis_descendant($axis, $childPath)); + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath ancestor axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_ancestor($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + $parentPath = $this->getParentXPath($contextPath); // Get the parent of the current node. + + // Check whether the parent isn't super-root. + if (!empty($parentPath)) { + // Check whether the parent matches the node-test. + if ($this->_checkNodeTest($parentPath, $axis['node-test'])) { + $xPathSet[] = $parentPath; // Add the parent to the list of nodes. + } + // Handle all other ancestors. + $xPathSet = array_merge($this->_handleAxis_ancestor($axis, $parentPath), $xPathSet); + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath namespace axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_namespace($axis, $contextPath) { + $this->_displayError("The axis 'namespace is not suported'", __LINE__, __FILE__, FALSE); + } + + /** + * Handles the XPath following axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_following($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + do { // try-block + $node = $this->nodeIndex[$contextPath]; // Get the current node + $position = $node['pos']; // Get the current tree position. + $parent = $node['parentNode']; + // Check if there is a following sibling at all; if not end. + if ($position >= sizeOf($parent['childNodes'])) break; // try-block + // Build the starting abs. XPath + $startXPath = $parent['childNodes'][$position+1]['xpath']; + // Run through all nodes of the document. + $nodeKeys = array_keys($this->nodeIndex); + $nodeSize = sizeOf($nodeKeys); + for ($k=0; $k<$nodeSize; $k++) { + if ($nodeKeys[$k] == $startXPath) break; // Check whether this is the starting abs. XPath + } + for (; $k<$nodeSize; $k++) { + // Check whether the node fits the node-test. + if ($this->_checkNodeTest($nodeKeys[$k], $axis['node-test'])) { + $xPathSet[] = $nodeKeys[$k]; // Add the node to the list of nodes. + } + } + } while(FALSE); + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath preceding axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_preceding($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Run through all nodes of the document. + foreach ($this->nodeIndex as $xPath=>$dummy) { + if (empty($xPath)) continue; // skip super-Root + + // Check whether this is the context node. + if ($xPath == $contextPath) { + break; // After this we won't look for more nodes. + } + if (!strncmp($xPath, $contextPath, strLen($xPath))) { + continue; + } + // Check whether the node fits the node-test. + if ($this->_checkNodeTest($xPath, $axis['node-test'])) { + $xPathSet[] = $xPath; // Add the node to the list of nodes. + } + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath following-sibling axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_following_sibling($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Get all children from the parent. + $siblings = $this->_handleAxis_child($axis, $this->getParentXPath($contextPath)); + // Create a flag whether the context node was already found. + $found = FALSE; + + // Run through all siblings. + $size = sizeOf($siblings); + for ($i=0; $i<$size; $i++) { + $sibling = $siblings[$i]; + + // Check whether the context node was already found. + if ($found) { + // Check whether the sibling matches the node-test. + if ($this->_checkNodeTest($sibling, $axis['node-test'])) { + $xPathSet[] = $sibling; // Add the sibling to the list of nodes. + } + } + // Check if we reached *this* context node. + if ($sibling == $contextPath) { + $found = TRUE; // Continue looking for other siblings. + } + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath preceding-sibling axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_preceding_sibling($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Get all children from the parent. + $siblings = $this->_handleAxis_child($axis, $this->getParentXPath($contextPath)); + + // Run through all siblings. + $size = sizeOf($siblings); + for ($i=0; $i<$size; $i++) { + $sibling = $siblings[$i]; + // Check whether this is the context node. + if ($sibling == $contextPath) { + break; // Don't continue looking for other siblings. + } + // Check whether the sibling matches the node-test. + if ($this->_checkNodeTest($sibling, $axis['node-test'])) { + $xPathSet[] = $sibling; // Add the sibling to the list of nodes. + } + } + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath descendant-or-self axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_descendant_or_self($axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Read the nodes. + $xPathSet = array_merge( + $this->_handleAxis_self($axis, $contextPath), + $this->_handleAxis_descendant($axis, $contextPath) + ); + return $xPathSet; // Return the nodeset. + } + + /** + * Handles the XPath ancestor-or-self axis. + * + * This method handles the XPath ancestor-or-self axis. + * + * @param $axis (array) Array containing information about the axis. + * @param $contextPath (string) xpath to starting node from which the axis should be processed. + * @return (array) A vector containing all nodes that were found, during the evaluation of the axis. + * @see evaluate() + */ + function _handleAxis_ancestor_or_self ( $axis, $contextPath) { + $xPathSet = array(); // Create an empty node-set. + + // Read the nodes. + $xPathSet = array_merge( + $this->_handleAxis_ancestor($axis, $contextPath), + $this->_handleAxis_self($axis, $contextPath) + ); + return $xPathSet; // Return the nodeset. + } + + + //----------------------------------------------------------------------------------------- + // XPath ------ XPath FUNCTION Handlers ------ + //----------------------------------------------------------------------------------------- + + /** + * Handles the XPath function last. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_last($arguments, $context) { + return $context['size']; + } + + /** + * Handles the XPath function position. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_position($arguments, $context) { + return $context['pos']; + } + + /** + * Handles the XPath function count. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_count($arguments, $context) { + // Evaluate the argument of the method as an XPath and return the number of results. + return count($this->_evaluateExpr($arguments, $context)); + } + + /** + * Handles the XPath function id. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_id($arguments, $context) { + $arguments = trim($arguments); // Trim the arguments. + $arguments = explode(' ', $arguments); // Now split the arguments into an array. + // Create a list of nodes. + $resultXPaths = array(); + // Run through all nodes of the document. + $keys = array_keys($this->nodeIndex); + $kSize = $sizeOf($keys); + for ($i=0; $i<$kSize; $i++) { + if (empty($keys[$i])) continue; // skip super-Root + if (in_array($this->nodeIndex[$keys[$i]]['attributes']['id'], $arguments)) { + $resultXPaths[] = $context['nodePath']; // Add this node to the list of nodes. + } + } + return $resultXPaths; // Return the list of nodes. + } + + /** + * Handles the XPath function name. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_name($arguments, $context) { + // If the argument it omitted, it defaults to a node-set with the context node as its only member. + if (empty($arguments)) { + return $this->_addLiteral($this->nodeIndex[$context['nodePath']]['name']); + } + + // Evaluate the argument to get a node set. + $nodeSet = $this->_evaluateExpr($arguments, $context); + if (!is_array($nodeSet)) return ''; + if (count($nodeSet) < 1) return ''; + if (!isset($this->nodeIndex[$nodeSet[0]])) return ''; + // Return a reference to the name of the node. + return $this->_addLiteral($this->nodeIndex[$nodeSet[0]]['name']); + } + + /** + * Handles the XPath function string. + * + * http://www.w3.org/TR/xpath#section-String-Functions + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_string($arguments, $context) { + // Check what type of parameter is given + if (is_array($arguments)) { + // Get the value of the first result (which means we want to concat all the text...unless + // a specific text() node has been given, and it will switch off to substringData + if (!count($arguments)) $result = ''; + else { + $result = $this->_stringValue($arguments[0]); + if (($literal = $this->_asLiteral($result)) !== FALSE) { + $result = $literal; + } + } + } + // Is it a number string? + elseif (preg_match('/^[0-9]+(\.[0-9]+)?$/', $arguments) OR preg_match('/^\.[0-9]+$/', $arguments)) { + // ### Note no support for NaN and Infinity. + $number = doubleval($arguments); // Convert the digits to a number. + $result = strval($number); // Return the number. + } + elseif (is_bool($arguments)) { // Check whether it's TRUE or FALSE and return as string. + // ### Note that we used to return TRUE and FALSE which was incorrect according to the standard. + if ($arguments === TRUE) { + $result = 'true'; + } else { + $result = 'false'; + } + } + elseif (($literal = $this->_asLiteral($arguments)) !== FALSE) { + return $literal; + } + elseif (!empty($arguments)) { + // Spec says: + // "An object of a type other than the four basic types is converted to a string in a way that + // is dependent on that type." + // Use the argument as an XPath. + $result = $this->_evaluateExpr($arguments, $context); + if (is_string($result) && is_string($arguments) && (!strcmp($result, $arguments))) { + $this->_displayError("Loop detected in XPath expression. Probably an internal error :o/. _handleFunction_string($result)", __LINE__, __FILE__, FALSE); + return ''; + } else { + $result = $this->_handleFunction_string($result, $context); + } + } + else { + $result = ''; // Return an empty string. + } + return $result; + } + + /** + * Handles the XPath function concat. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_concat($arguments, $context) { + // Split the arguments. + $arguments = explode(',', $arguments); + // Run through each argument and evaluate it. + $size = sizeof($arguments); + for ($i=0; $i<$size; $i++) { + $arguments[$i] = trim($arguments[$i]); // Trim each argument. + // Evaluate it. + $arguments[$i] = $this->_handleFunction_string($arguments[$i], $context); + } + $arguments = implode('', $arguments); // Put the string together and return it. + return $this->_addLiteral($arguments); + } + + /** + * Handles the XPath function starts-with. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_starts_with($arguments, $context) { + // Get the arguments. + $first = trim($this->_prestr($arguments, ',')); + $second = trim($this->_afterstr($arguments, ',')); + // Evaluate each argument. + $first = $this->_handleFunction_string($first, $context); + $second = $this->_handleFunction_string($second, $context); + // Check whether the first string starts with the second one. + return (bool) ereg('^'.$second, $first); + } + + /** + * Handles the XPath function contains. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_contains($arguments, $context) { + // Get the arguments. + $first = trim($this->_prestr($arguments, ',')); + $second = trim($this->_afterstr($arguments, ',')); + //echo "Predicate: $arguments First: ".$first." Second: ".$second."\n"; + // Evaluate each argument. + $first = $this->_handleFunction_string($first, $context); + $second = $this->_handleFunction_string($second, $context); + //echo $second.": ".$first."\n"; + // If the search string is null, then the provided there is a value it will contain it as + // it is considered that all strings contain the empty string. ## N.S. + if ($second==='') return TRUE; + // Check whether the first string starts with the second one. + if (strpos($first, $second) === FALSE) { + return FALSE; + } else { + return TRUE; + } + } + + /** + * Handles the XPath function substring-before. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_substring_before($arguments, $context) { + // Get the arguments. + $first = trim($this->_prestr($arguments, ',')); + $second = trim($this->_afterstr($arguments, ',')); + // Evaluate each argument. + $first = $this->_handleFunction_string($first, $context); + $second = $this->_handleFunction_string($second, $context); + // Return the substring. + return $this->_addLiteral($this->_prestr(strval($first), strval($second))); + } + + /** + * Handles the XPath function substring-after. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_substring_after($arguments, $context) { + // Get the arguments. + $first = trim($this->_prestr($arguments, ',')); + $second = trim($this->_afterstr($arguments, ',')); + // Evaluate each argument. + $first = $this->_handleFunction_string($first, $context); + $second = $this->_handleFunction_string($second, $context); + // Return the substring. + return $this->_addLiteral($this->_afterstr(strval($first), strval($second))); + } + + /** + * Handles the XPath function substring. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_substring($arguments, $context) { + // Split the arguments. + $arguments = explode(",", $arguments); + $size = sizeOf($arguments); + for ($i=0; $i<$size; $i++) { // Run through all arguments. + $arguments[$i] = trim($arguments[$i]); // Trim the string. + // Evaluate each argument. + $arguments[$i] = $this->_handleFunction_string($arguments[$i], $context); + } + // Check whether a third argument was given and return the substring.. + if (!empty($arguments[2])) { + return $this->_addLiteral(substr(strval($arguments[0]), $arguments[1] - 1, $arguments[2])); + } else { + return $this->_addLiteral(substr(strval($arguments[0]), $arguments[1] - 1)); + } + } + + /** + * Handles the XPath function string-length. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_string_length($arguments, $context) { + $arguments = trim($arguments); // Trim the argument. + // Evaluate the argument. + $arguments = $this->_handleFunction_string($arguments, $context); + return strlen(strval($arguments)); // Return the length of the string. + } + + /** + * Handles the XPath function normalize-space. + * + * The normalize-space function returns the argument string with whitespace + * normalized by stripping leading and trailing whitespace and replacing sequences + * of whitespace characters by a single space. + * If the argument is omitted, it defaults to the context node converted to a string, + * in other words the string-value of the context node + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (stri)g trimed string + * @see evaluate() + */ + function _handleFunction_normalize_space($arguments, $context) { + if (empty($arguments)) { + $arguments = $this->getParentXPath($context['nodePath']).'/'.$this->nodeIndex[$context['nodePath']]['name'].'['.$this->nodeIndex[$context['nodePath']]['contextPos'].']'; + } else { + $arguments = $this->_handleFunction_string($arguments, $context); + } + $arguments = trim(preg_replace (";[[:space:]]+;s",' ',$arguments)); + return $this->_addLiteral($arguments); + } + + /** + * Handles the XPath function translate. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_translate($arguments, $context) { + $arguments = explode(',', $arguments); // Split the arguments. + $size = sizeOf($arguments); + for ($i=0; $i<$size; $i++) { // Run through all arguments. + $arguments[$i] = trim($arguments[$i]); // Trim the argument. + // Evaluate the argument. + $arguments[$i] = $this->_handleFunction_string($arguments[$i], $context); + } + // Return the translated string. + return $this->_addLiteral(strtr($arguments[0], $arguments[1], $arguments[2])); + } + + /** + * Handles the XPath function boolean. + * + * http://www.w3.org/TR/xpath#section-Boolean-Functions + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_boolean($arguments, $context) { + if (empty($arguments)) { + return FALSE; // Sorry, there were no arguments. + } + // a bool is dead obvious + elseif (is_bool($arguments)) { + return $arguments; + } + // a node-set is true if and only if it is non-empty + elseif (is_array($arguments)) { + return (count($arguments) > 0); + } + // a number is true if and only if it is neither positive or negative zero nor NaN + // (Straight out of the XPath spec.. makes no sense?????) + elseif (preg_match('/^[0-9]+(\.[0-9]+)?$/', $arguments) || preg_match('/^\.[0-9]+$/', $arguments)) { + $number = doubleval($arguments); // Convert the digits to a number. + // If number zero return FALSE else TRUE. + if ($number == 0) return FALSE; else return TRUE; + } + // a string is true if and only if its length is non-zero + elseif (($literal = $this->_asLiteral($arguments)) !== FALSE) { + return (strlen($literal) != 0); + } + // an object of a type other than the four basic types is converted to a boolean in a + // way that is dependent on that type + else { + // Spec says: + // "An object of a type other than the four basic types is converted to a number in a way + // that is dependent on that type" + // Try to evaluate the argument as an XPath. + $result = $this->_evaluateExpr($arguments, $context); + if (is_string($result) && is_string($arguments) && (!strcmp($result, $arguments))) { + $this->_displayError("Loop detected in XPath expression. Probably an internal error :o/. _handleFunction_boolean($result)", __LINE__, __FILE__, FALSE); + return FALSE; + } else { + return $this->_handleFunction_boolean($result, $context); + } + } + } + + /** + * Handles the XPath function not. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_not($arguments, $context) { + // Return the negative value of the content of the brackets. + $bArgResult = $this->_handleFunction_boolean($arguments, $context); +//echo "Before inversion: ".($bArgResult?"TRUE":"FALSE")."\n"; + return !$bArgResult; + } + + /** + * Handles the XPath function TRUE. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_true($arguments, $context) { + return TRUE; // Return TRUE. + } + + /** + * Handles the XPath function FALSE. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_false($arguments, $context) { + return FALSE; // Return FALSE. + } + + /** + * Handles the XPath function lang. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_lang($arguments, $context) { + $arguments = trim($arguments); // Trim the arguments. + $currentNode = $this->nodeIndex[$context['nodePath']]; + while (!empty($currentNode['name'])) { // Run through the ancestors. + // Check whether the node has an language attribute. + if (isSet($currentNode['attributes']['xml:lang'])) { + // Check whether it's the language, the user asks for; if so return TRUE else FALSE + return eregi('^'.$arguments, $currentNode['attributes']['xml:lang']); + } + $currentNode = $currentNode['parentNode']; // Move up to parent + } // End while + return FALSE; + } + + /** + * Handles the XPath function number. + * + * http://www.w3.org/TR/xpath#section-Number-Functions + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_number($arguments, $context) { + // Check the type of argument. + + // A string that is a number + if (is_numeric($arguments)) { + return doubleval($arguments); // Return the argument as a number. + } + // A bool + elseif (is_bool($arguments)) { // Return TRUE/FALSE as a number. + if ($arguments === TRUE) return 1; else return 0; + } + // A node set + elseif (is_array($arguments)) { + // Is converted to a string then handled like a string + $string = $this->_handleFunction_string($arguments, $context); + if (is_numeric($string)) + return doubleval($string); + } + elseif (($literal = $this->_asLiteral($arguments)) !== FALSE) { + if (is_numeric($literal)) { + return doubleval($literal); + } else { + // If we are to stick strictly to the spec, we should return NaN, but lets just + // leave PHP to see if can do some dynamic conversion. + return $literal; + } + } + else { + // Spec says: + // "An object of a type other than the four basic types is converted to a number in a way + // that is dependent on that type" + // Try to evaluate the argument as an XPath. + $result = $this->_evaluateExpr($arguments, $context); + if (is_string($result) && is_string($arguments) && (!strcmp($result, $arguments))) { + $this->_displayError("Loop detected in XPath expression. Probably an internal error :o/. _handleFunction_number($result)", __LINE__, __FILE__, FALSE); + return FALSE; + } else { + return $this->_handleFunction_number($result, $context); + } + } + } + + /** + * Handles the XPath function sum. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_sum($arguments, $context) { + $arguments = trim($arguments); // Trim the arguments. + // Evaluate the arguments as an XPath query. + $result = $this->_evaluateExpr($arguments, $context); + $sum = 0; // Create a variable to save the sum. + // The sum function expects a node set as an argument. + if (is_array($result)) { + // Run through all results. + $size = sizeOf($result); + for ($i=0; $i<$size; $i++) { + $value = $this->_stringValue($result[$i], $context); + if (($literal = $this->_asLiteral($value)) !== FALSE) { + $value = $literal; + } + $sum += doubleval($value); // Add it to the sum. + } + } + return $sum; // Return the sum. + } + + /** + * Handles the XPath function floor. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_floor($arguments, $context) { + if (!is_numeric($arguments)) { + $arguments = $this->_handleFunction_number($arguments, $context); + } + $arguments = doubleval($arguments); // Convert the arguments to a number. + return floor($arguments); // Return the result + } + + /** + * Handles the XPath function ceiling. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_ceiling($arguments, $context) { + if (!is_numeric($arguments)) { + $arguments = $this->_handleFunction_number($arguments, $context); + } + $arguments = doubleval($arguments); // Convert the arguments to a number. + return ceil($arguments); // Return the result + } + + /** + * Handles the XPath function round. + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_round($arguments, $context) { + if (!is_numeric($arguments)) { + $arguments = $this->_handleFunction_number($arguments, $context); + } + $arguments = doubleval($arguments); // Convert the arguments to a number. + return round($arguments); // Return the result + } + + //----------------------------------------------------------------------------------------- + // XPath ------ XPath Extension FUNCTION Handlers ------ + //----------------------------------------------------------------------------------------- + + /** + * Handles the XPath function x-lower. + * + * lower case a string. + * string x-lower(string) + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_x_lower($arguments, $context) { + // Evaluate the argument. + $string = $this->_handleFunction_string($arguments, $context); + // Return a reference to the lowercased string + return $this->_addLiteral(strtolower(strval($string))); + } + + /** + * Handles the XPath function x-upper. + * + * upper case a string. + * string x-upper(string) + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @see evaluate() + */ + function _handleFunction_x_upper($arguments, $context) { + // Evaluate the argument. + $string = $this->_handleFunction_string($arguments, $context); + // Return a reference to the lowercased string + return $this->_addLiteral(strtoupper(strval($string))); + } + + /** + * Handles the XPath function generate-id. + * + * Produce a unique id for the first node of the node set. + * + * Example usage, produces an index of all the nodes in an .xml document, where the content of each + * "section" is the exported node as XML. + * + * $aFunctions = $xPath->match('//'); + * + * foreach ($aFunctions as $Function) { + * $id = $xPath->match("generate-id($Function)"); + * echo "$Function
    "; + * } + * + * foreach ($aFunctions as $Function) { + * $id = $xPath->match("generate-id($Function)"); + * echo "

    $Function

    "; + * echo htmlspecialchars($xPath->exportAsXml($Function)); + * } + * + * @param $arguments (string) String containing the arguments that were passed to the function. + * @param $context (array) The context from which to evaluate the function + * @return (mixed) Depending on the type of function being processed + * @author Ricardo Garcia + * @see evaluate() + */ + function _handleFunction_generate_id($arguments, $context) { + // If the argument is omitted, it defaults to a node-set with the context node as its only member. + if (is_string($arguments) && empty($arguments)) { + // We need ids then + $this->_generate_ids(); + return $this->_addLiteral($this->nodeIndex[$context['nodePath']]['generated_id']); + } + + // Evaluate the argument to get a node set. + $nodeSet = $this->_evaluateExpr($arguments, $context); + + if (!is_array($nodeSet)) return ''; + if (count($nodeSet) < 1) return ''; + if (!isset($this->nodeIndex[$nodeSet[0]])) return ''; + // Return a reference to the name of the node. + // We need ids then + $this->_generate_ids(); + return $this->_addLiteral($this->nodeIndex[$nodeSet[0]]['generated_id']); + } + + //----------------------------------------------------------------------------------------- + // XPathEngine ------ Help Stuff ------ + //----------------------------------------------------------------------------------------- + + /** + * Decodes the character set entities in the given string. + * + * This function is given for convenience, as all text strings or attributes + * are going to come back to you with their entities still encoded. You can + * use this function to remove these entites. + * + * It makes use of the get_html_translation_table(HTML_ENTITIES) php library + * call, so is limited in the same ways. At the time of writing this seemed + * be restricted to iso-8859-1 + * + * ### Provide an option that will do this by default. + * + * @param $encodedData (mixed) The string or array that has entities you would like to remove + * @param $reverse (bool) If TRUE entities will be encoded rather than decoded, ie + * < to < rather than < to <. + * @return (mixed) The string or array returned with entities decoded. + */ + function decodeEntities($encodedData, $reverse=FALSE) { + static $aEncodeTbl; + static $aDecodeTbl; + // Get the translation entities, but we'll cache the result to enhance performance. + if (empty($aDecodeTbl)) { + // Get the translation entities. + $aEncodeTbl = get_html_translation_table(HTML_ENTITIES); + $aDecodeTbl = array_flip($aEncodeTbl); + } + + // If it's just a single string. + if (!is_array($encodedData)) { + if ($reverse) { + return strtr($encodedData, $aEncodeTbl); + } else { + return strtr($encodedData, $aDecodeTbl); + } + } + + $result = array(); + foreach($encodedData as $string) { + if ($reverse) { + $result[] = strtr($string, $aEncodeTbl); + } else { + $result[] = strtr($string, $aDecodeTbl); + } + } + + return $result; + } + + /** + * Compare two nodes to see if they are equal (point to the same node in the doc) + * + * 2 nodes are considered equal if the absolute XPath is equal. + * + * @param $node1 (mixed) Either an absolute XPath to an node OR a real tree-node (hash-array) + * @param $node2 (mixed) Either an absolute XPath to an node OR a real tree-node (hash-array) + * @return (bool) TRUE if equal (see text above), FALSE if not (and on error). + */ + function equalNodes($node1, $node2) { + $xPath_1 = is_string($node1) ? $node1 : $this->getNodePath($node1); + $xPath_2 = is_string($node2) ? $node2 : $this->getNodePath($node2); + return (strncasecmp ($xPath_1, $xPath_2, strLen($xPath_1)) == 0); + } + + /** + * Get the absolute XPath of a node that is in a document tree. + * + * @param $node (array) A real tree-node (hash-array) + * @return (string) The string path to the node or FALSE on error. + */ + function getNodePath($node) { + if (!empty($node['xpath'])) return $node['xpath']; + $pathInfo = array(); + do { + if (empty($node['name']) OR empty($node['parentNode'])) break; // End criteria + $pathInfo[] = array('name' => $node['name'], 'contextPos' => $node['contextPos']); + $node = $node['parentNode']; + } while (TRUE); + + $xPath = ''; + for ($i=sizeOf($pathInfo)-1; $i>=0; $i--) { + $xPath .= '/' . $pathInfo[$i]['name'] . '[' . $pathInfo[$i]['contextPos'] . ']'; + } + if (empty($xPath)) return FALSE; + return $xPath; + } + + /** + * Retrieves the absolute parent XPath query. + * + * The parents stored in the tree are only relative parents...but all the parent + * information is stored in the XPath query itself...so instead we use a function + * to extract the parent from the absolute Xpath query + * + * @param $childPath (string) String containing an absolute XPath query + * @return (string) returns the absolute XPath of the parent + */ + function getParentXPath($absoluteXPath) { + $lastSlashPos = strrpos($absoluteXPath, '/'); + if ($lastSlashPos == 0) { // it's already the root path + return ''; // 'super-root' + } else { + return (substr($absoluteXPath, 0, $lastSlashPos)); + } + } + + /** + * Returns TRUE if the given node has child nodes below it + * + * @param $absoluteXPath (string) full path of the potential parent node + * @return (bool) TRUE if this node exists and has a child, FALSE otherwise + */ + function hasChildNodes($absoluteXPath) { + if ($this->_indexIsDirty) $this->reindexNodeTree(); + return (bool) (isSet($this->nodeIndex[$absoluteXPath]) + AND sizeOf($this->nodeIndex[$absoluteXPath]['childNodes'])); + } + + /** + * Translate all ampersands to it's literal entities '&' and back. + * + * I wasn't aware of this problem at first but it's important to understand why we do this. + * At first you must know: + * a) PHP's XML parser *translates* all entities to the equivalent char E.g. < is returned as '<' + * b) PHP's XML parser (in V 4.1.0) has problems with most *literal* entities! The only one's that are + * recognized are &, < > and ". *ALL* others (like   © a.s.o.) cause an + * XML_ERROR_UNDEFINED_ENTITY error. I reported this as bug at http://bugs.php.net/bug.php?id=15092 + * (It turned out not to be a 'real' bug, but one of those nice W3C-spec things). + * + * Forget position b) now. It's just for info. Because the way we will solve a) will also solve b) too. + * + * THE PROBLEM + * To understand the problem, here a sample: + * Given is the following XML: " <   > " + * Try to parse it and PHP's XML parser will fail with a XML_ERROR_UNDEFINED_ENTITY becaus of + * the unknown litteral-entity ' '. (The numeric equivalent ' ' would work though). + * Next try is to use the numeric equivalent 160 for ' ', thus " <   > " + * The data we receive in the tag is " < > ". So we get the *translated entities* and + * NOT the 3 entities <   >. Thus, we will not even notice that there were entities at all! + * In *most* cases we're not able to tell if the data was given as entity or as 'normal' char. + * E.g. When receiving a quote or a single space were not able to tell if it was given as 'normal' char + * or as   or ". Thus we loose the entity-information of the XML-data! + * + * THE SOLUTION + * The better solution is to keep the data 'as is' by replacing the '&' before parsing begins. + * E.g. Taking the original input from above, this would result in " &lt; &nbsp; &gt; " + * The data we receive now for the tag is " <   > ". and that's what we want. + * + * The bad thing is, that a global replace will also replace data in section that are NOT translated by the + * PHP XML-parser. That is comments (), IP-sections (stuff between ) and CDATA-block too. + * So all data comming from those sections must be reversed. This is done during the XML parse phase. + * So: + * a) Replacement of all '&' in the XML-source. + * b) All data that is not char-data or in CDATA-block have to be reversed during the XML-parse phase. + * + * @param $xmlSource (string) The XML string + * @return (string) The XML string with translated ampersands. + */ + function _translateAmpersand($xmlSource, $reverse=FALSE) { + $PHP5 = (substr(phpversion(), 0, 1) == '5'); + if ($PHP5) { + //otherwise we receive &nbsp; instead of   + return $xmlSource; + } else { + return ($reverse ? str_replace('&', '&', $xmlSource) : str_replace('&', '&', $xmlSource)); + } + } + +} // END OF CLASS XPathEngine + + +/************************************************************************************************ +* =============================================================================================== +* X P a t h - Class +* =============================================================================================== +************************************************************************************************/ + +define('XPATH_QUERYHIT_ALL' , 1); +define('XPATH_QUERYHIT_FIRST' , 2); +define('XPATH_QUERYHIT_UNIQUE', 3); + +class XPath extends XPathEngine { + + /** + * Constructor of the class + * + * Optionally you may call this constructor with the XML-filename to parse and the + * XML option vector. A option vector sample: + * $xmlOpt = array(XML_OPTION_CASE_FOLDING => FALSE, XML_OPTION_SKIP_WHITE => TRUE); + * + * @param $userXmlOptions (array) (optional) Vector of (=>, =>, ...) + * @param $fileName (string) (optional) Filename of XML file to load from. + * It is recommended that you call importFromFile() + * instead as you will get an error code. If the + * import fails, the object will be set to FALSE. + * @see parent::XPathEngine() + */ + function XPath($fileName='', $userXmlOptions=array()) { + parent::XPathEngine($userXmlOptions); + $this->properties['modMatch'] = XPATH_QUERYHIT_ALL; + if ($fileName) { + if (!$this->importFromFile($fileName)) { + // Re-run the base constructor to "reset" the object. If the user has any sense, then + // they will have created the object, and then explicitly called importFromFile(), giving + // them the chance to catch and handle the error properly. + parent::XPathEngine($userXmlOptions); + } + } + } + + /** + * Resets the object so it's able to take a new xml sting/file + * + * Constructing objects is slow. If you can, reuse ones that you have used already + * by using this reset() function. + */ + function reset() { + parent::reset(); + $this->properties['modMatch'] = XPATH_QUERYHIT_ALL; + } + + //----------------------------------------------------------------------------------------- + // XPath ------ Get / Set Stuff ------ + //----------------------------------------------------------------------------------------- + + /** + * Resolves and xPathQuery array depending on the property['modMatch'] + * + * Most of the modification functions of XPath will also accept a xPathQuery (instead + * of an absolute Xpath). The only problem is that the query could match more the one + * node. The question is, if the none, the fist or all nodes are to be modified. + * The behaver can be set with setModMatch() + * + * @param $modMatch (int) One of the following: + * - XPATH_QUERYHIT_ALL (default) + * - XPATH_QUERYHIT_FIRST + * - XPATH_QUERYHIT_UNIQUE // If the query matches more then one node. + * @see _resolveXPathQuery() + */ + function setModMatch($modMatch = XPATH_QUERYHIT_ALL) { + switch($modMatch) { + case XPATH_QUERYHIT_UNIQUE : $this->properties['modMatch'] = XPATH_QUERYHIT_UNIQUE; break; + case XPATH_QUERYHIT_FIRST: $this->properties['modMatch'] = XPATH_QUERYHIT_FIRST; break; + default: $this->properties['modMatch'] = XPATH_QUERYHIT_ALL; + } + } + + //----------------------------------------------------------------------------------------- + // XPath ------ DOM Like Modification ------ + //----------------------------------------------------------------------------------------- + + //----------------------------------------------------------------------------------------- + // XPath ------ Child (Node) Set/Get ------ + //----------------------------------------------------------------------------------------- + + /** + * Retrieves the name(s) of a node or a group of document nodes. + * + * This method retrieves the names of a group of document nodes + * specified in the argument. So if the argument was '/A[1]/B[2]' then it + * would return 'B' if the node did exist in the tree. + * + * @param $xPathQuery (mixed) Array or single full document path(s) of the node(s), + * from which the names should be retrieved. + * @return (mixed) Array or single string of the names of the specified + * nodes, or just the individual name. If the node did + * not exist, then returns FALSE. + */ + function nodeName($xPathQuery) { + if (is_array($xPathQuery)) { + $xPathSet = $xPathQuery; + } else { + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'nodeName'); + } + if (count($xPathSet) == 0) return FALSE; + // For each node, get it's name + $result = array(); + foreach($xPathSet as $xPath) { + $node = &$this->getNode($xPath); + if (!$node) { + // ### Fatal internal error?? + continue; + } + $result[] = $node['name']; + } + // If just a single string, return string + if (count($xPathSet) == 1) $result = $result[0]; + // Return result. + return $result; + } + + /** + * Removes a node from the XML document. + * + * This method removes a node from the tree of nodes of the XML document. If the node + * is a document node, all children of the node and its character data will be removed. + * If the node is an attribute node, only this attribute will be removed, the node to which + * the attribute belongs as well as its children will remain unmodified. + * + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $autoReindex (bool) (optional, default=TRUE) Reindex the document to reflect + * the changes. A performance helper. See reindexNodeTree() + * @return (bool) TRUE on success, FALSE on error; + * @see setModMatch(), reindexNodeTree() + */ + function removeChild($xPathQuery, $autoReindex=TRUE) { + $ThisFunctionName = 'removeChild'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Node: $xPathQuery\n"; + echo '
    '; + } + + $NULL = NULL; + $status = FALSE; + do { // try-block + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'removeChild'); + if (sizeOf($xPathSet) === 0) { + $this->_displayError(sprintf($this->errorStrings['NoNodeMatch'], $xPathQuery), __LINE__, __FILE__, FALSE); + break; // try-block + } + $mustReindex = FALSE; + // Make chages from 'bottom-up'. In this manner the modifications will not affect itself. + for ($i=sizeOf($xPathSet)-1; $i>=0; $i--) { + $absoluteXPath = $xPathSet[$i]; + if (preg_match(';/attribute::;', $absoluteXPath)) { // Handle the case of an attribute node + $xPath = $this->_prestr($absoluteXPath, '/attribute::'); // Get the path to the attribute node's parent. + $attribute = $this->_afterstr($absoluteXPath, '/attribute::'); // Get the name of the attribute. + unSet($this->nodeIndex[$xPath]['attributes'][$attribute]); // Unset the attribute + if ($bDebugThisFunction) echo "We removed the attribute '$attribute' of node '$xPath'.\n"; + continue; + } + // Otherwise remove the node by setting it to NULL. It will be removed on the next reindexNodeTree() call. + $mustReindex = $autoReindex; + // Flag the index as dirty; it's not uptodate. A reindex will be forced (if dirty) when exporting the XML doc + $this->_indexIsDirty = TRUE; + + $theNode = $this->nodeIndex[$absoluteXPath]; + $theNode['parentNode']['childNodes'][$theNode['pos']] =& $NULL; + if ($bDebugThisFunction) echo "We removed the node '$absoluteXPath'.\n"; + } + // Reindex the node tree again + if ($mustReindex) $this->reindexNodeTree(); + $status = TRUE; + } while(FALSE); + + $this->_closeDebugFunction($ThisFunctionName, $status, $bDebugThisFunction); + + return $status; + } + + /** + * Replace a node with any data string. The $data is taken 1:1. + * + * This function will delete the node you define by $absoluteXPath (plus it's sub-nodes) and + * substitute it by the string $text. Often used to push in not well formed HTML. + * WARNING: + * The $data is taken 1:1. + * You are in charge that the data you enter is valid XML if you intend + * to export and import the content again. + * + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $data (string) String containing the content to be set. *READONLY* + * @param $autoReindex (bool) (optional, default=TRUE) Reindex the document to reflect + * the changes. A performance helper. See reindexNodeTree() + * @return (bool) TRUE on success, FALSE on error; + * @see setModMatch(), replaceChild(), reindexNodeTree() + */ + function replaceChildByData($xPathQuery, $data, $autoReindex=TRUE) { + $ThisFunctionName = 'replaceChildByData'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Node: $xPathQuery\n"; + } + + $NULL = NULL; + $status = FALSE; + do { // try-block + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'replaceChildByData'); + if (sizeOf($xPathSet) === 0) { + $this->_displayError(sprintf($this->errorStrings['NoNodeMatch'], $xPathQuery), __LINE__, __FILE__, FALSE); + break; // try-block + } + $mustReindex = FALSE; + // Make chages from 'bottom-up'. In this manner the modifications will not affect itself. + for ($i=sizeOf($xPathSet)-1; $i>=0; $i--) { + $mustReindex = $autoReindex; + // Flag the index as dirty; it's not uptodate. A reindex will be forced (if dirty) when exporting the XML doc + $this->_indexIsDirty = TRUE; + + $absoluteXPath = $xPathSet[$i]; + $theNode = $this->nodeIndex[$absoluteXPath]; + $pos = $theNode['pos']; + $theNode['parentNode']['textParts'][$pos] .= $data; + $theNode['parentNode']['childNodes'][$pos] =& $NULL; + if ($bDebugThisFunction) echo "We replaced the node '$absoluteXPath' with data.\n"; + } + // Reindex the node tree again + if ($mustReindex) $this->reindexNodeTree(); + $status = TRUE; + } while(FALSE); + + $this->_closeDebugFunction($ThisFunctionName, ($status) ? 'Success' : '!!! FAILD !!!', $bDebugThisFunction); + + return $status; + } + + /** + * Replace the node(s) that matches the xQuery with the passed node (or passed node-tree) + * + * If the passed node is a string it's assumed to be XML and replaceChildByXml() + * will be called. + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) Xpath to the node being replaced. + * @param $node (mixed) String or Array (Usually a String) + * If string: Vaild XML. E.g. "" or " foo bar " + * If array: A Node (can be a whole sub-tree) (See comment in header) + * @param $autoReindex (bool) (optional, default=TRUE) Reindex the document to reflect + * the changes. A performance helper. See reindexNodeTree() + * @return (array) The last replaced $node (can be a whole sub-tree) + * @see reindexNodeTree() + */ + function &replaceChild($xPathQuery, $node, $autoReindex=TRUE) { + $NULL = NULL; + if (is_string($node)) { + if (empty($node)) { //--sam. Not sure how to react on an empty string - think it's an error. + return array(); + } else { + if (!($node = $this->_xml2Document($node))) return FALSE; + } + } + + // Special case if it's 'super root'. We then have to take the child node == top node + if (empty($node['parentNode'])) $node = $node['childNodes'][0]; + + $status = FALSE; + do { // try-block + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'replaceChild'); + if (sizeOf($xPathSet) === 0) { + $this->_displayError(sprintf($this->errorStrings['NoNodeMatch'], $xPathQuery), __LINE__, __FILE__, FALSE); + break; // try-block + } + $mustReindex = FALSE; + + // Make chages from 'bottom-up'. In this manner the modifications will not affect itself. + for ($i=sizeOf($xPathSet)-1; $i>=0; $i--) { + $mustReindex = $autoReindex; + // Flag the index as dirty; it's not uptodate. A reindex will be forced (if dirty) when exporting the XML doc + $this->_indexIsDirty = TRUE; + + $absoluteXPath = $xPathSet[$i]; + $childNode =& $this->nodeIndex[$absoluteXPath]; + $parentNode =& $childNode['parentNode']; + $childNode['parentNode'] =& $NULL; + $childPos = $childNode['pos']; + $parentNode['childNodes'][$childPos] =& $this->cloneNode($node); + } + if ($mustReindex) $this->reindexNodeTree(); + $status = TRUE; + } while(FALSE); + + if (!$status) return FALSE; + return $childNode; + } + + /** + * Insert passed node (or passed node-tree) at the node(s) that matches the xQuery. + * + * With parameters you can define if the 'hit'-node is shifted to the right or left + * and if it's placed before of after the text-part. + * Per derfault the 'hit'-node is shifted to the right and the node takes the place + * the of the 'hit'-node. + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * E.g. Following is given: AAA[1] + * / \ + * ..BBB[1]..BBB[2] .. + * + * a) insertChild('/AAA[1]/BBB[2]', ) + * b) insertChild('/AAA[1]/BBB[2]', , $shiftRight=FALSE) + * c) insertChild('/AAA[1]/BBB[2]', , $shiftRight=FALSE, $afterText=FALSE) + * + * a) b) c) + * AAA[1] AAA[1] AAA[1] + * / | \ / | \ / | \ + * ..BBB[1]..CCC[1]BBB[2].. ..BBB[1]..BBB[2]..CCC[1] ..BBB[1]..BBB[2]CCC[1].. + * + * #### Do a complete review of the "(optional)" tag after several arguments. + * + * @param $xPathQuery (string) Xpath to the node to append. + * @param $node (mixed) String or Array (Usually a String) + * If string: Vaild XML. E.g. "" or " foo bar " + * If array: A Node (can be a whole sub-tree) (See comment in header) + * @param $shiftRight (bool) (optional, default=TRUE) Shift the target node to the right. + * @param $afterText (bool) (optional, default=TRUE) Insert after the text. + * @param $autoReindex (bool) (optional, default=TRUE) Reindex the document to reflect + * the changes. A performance helper. See reindexNodeTree() + * @return (mixed) FALSE on error (or no match). On success we return the path(s) to the newly + * appended nodes. That is: Array of paths if more then 1 node was added or + * a single path string if only one node was added. + * NOTE: If autoReindex is FALSE, then we can't return the *complete* path + * as the exact doc-pos isn't available without reindexing. In that case we leave + * out the last [docpos] in the path(s). ie we'd return /A[3]/B instead of /A[3]/B[2] + * @see appendChildByXml(), reindexNodeTree() + */ + function insertChild($xPathQuery, $node, $shiftRight=TRUE, $afterText=TRUE, $autoReindex=TRUE) { + if (is_string($node)) { + if (empty($node)) { //--sam. Not sure how to react on an empty string - think it's an error. + return FALSE; + } else { + if (!($node = $this->_xml2Document($node))) return FALSE; + } + } + + // Special case if it's 'super root'. We then have to take the child node == top node + if (empty($node['parentNode'])) $node = $node['childNodes'][0]; + + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'insertChild'); + if (sizeOf($xPathSet) === 0) { + $this->_displayError(sprintf($this->errorStrings['NoNodeMatch'], $xPathQuery), __LINE__, __FILE__, FALSE); + return FALSE; + } + $mustReindex = FALSE; + $newNodes = array(); + $result = array(); + // Make chages from 'bottom-up'. In this manner the modifications will not affect itself. + for ($i=sizeOf($xPathSet)-1; $i>=0; $i--) { + $absoluteXPath = $xPathSet[$i]; + $childNode =& $this->nodeIndex[$absoluteXPath]; + $parentNode =& $childNode['parentNode']; + + // We can't insert at the super root or at the root. + if (empty($absoluteXPath) || (!$parentNode['parentNode'])) { + $this->_displayError(sprintf($this->errorStrings['RootNodeAlreadyExists']), __LINE__, __FILE__, FALSE); + return FALSE; + } + + $mustReindex = $autoReindex; + // Flag the index as dirty; it's not uptodate. A reindex will be forced (if dirty) when exporting the XML doc + $this->_indexIsDirty = TRUE; + + //Special case: It not possible to add siblings to the top node. + if (empty($parentNode['name'])) continue; + $newNode =& $this->cloneNode($node); + $pos = $shiftRight ? $childNode['pos'] : $childNode['pos']+1; + $parentNode['childNodes'] = array_merge( + array_slice($parentNode['childNodes'], 0, $pos), + array(&$newNode), + array_slice($parentNode['childNodes'], $pos) + ); + $pos += $afterText ? 1 : 0; + $parentNode['textParts'] = array_merge( + array_slice($parentNode['textParts'], 0, $pos), + array(''), + array_slice($parentNode['textParts'], $pos) + ); + + // We are going from bottom to top, but the user will want results from top to bottom. + if ($mustReindex) { + // We'll have to wait till after the reindex to get the full path to this new node. + $newNodes[] = &$newNode; + } else { + // If we are reindexing the tree later, then we can't return the user any + // useful results, so we just return them the count. + $newNodePath = $parentNode['xpath'].'/'.$newNode['name']; + array_unshift($result, $newNodePath); + } + } + if ($mustReindex) { + $this->reindexNodeTree(); + // Now we must fill in the result array. Because until now we did not + // know what contextpos our newly added entries had, just their pos within + // the siblings. + foreach ($newNodes as $newNode) { + array_unshift($result, $newNode['xpath']); + } + } + if (count($result) == 1) $result = $result[0]; + return $result; + } + + /** + * Appends a child to anothers children. + * + * If you intend to do a lot of appending, you should leave autoIndex as FALSE + * and then call reindexNodeTree() when you are finished all the appending. + * + * @param $xPathQuery (string) Xpath to the node to append to. + * @param $node (mixed) String or Array (Usually a String) + * If string: Vaild XML. E.g. "" or " foo bar " + * If array: A Node (can be a whole sub-tree) (See comment in header) + * @param $afterText (bool) (optional, default=FALSE) Insert after the text. + * @param $autoReindex (bool) (optional, default=TRUE) Reindex the document to reflect + * the changes. A performance helper. See reindexNodeTree() + * @return (mixed) FALSE on error (or no match). On success we return the path(s) to the newly + * appended nodes. That is: Array of paths if more then 1 node was added or + * a single path string if only one node was added. + * NOTE: If autoReindex is FALSE, then we can't return the *complete* path + * as the exact doc-pos isn't available without reindexing. In that case we leave + * out the last [docpos] in the path(s). ie we'd return /A[3]/B instead of /A[3]/B[2] + * @see insertChild(), reindexNodeTree() + */ + function appendChild($xPathQuery, $node, $afterText=FALSE, $autoReindex=TRUE) { + if (is_string($node)) { + if (empty($node)) { //--sam. Not sure how to react on an empty string - think it's an error. + return FALSE; + } else { + if (!($node = $this->_xml2Document($node))) return FALSE; + } + } + + // Special case if it's 'super root'. We then have to take the child node == top node + if (empty($node['parentNode'])) $node = $node['childNodes'][0]; + + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQueryForNodeMod($xPathQuery, 'appendChild'); + if (sizeOf($xPathSet) === 0) return FALSE; + + $mustReindex = FALSE; + $newNodes = array(); + $result = array(); + // Make chages from 'bottom-up'. In this manner the modifications will not affect itself. + for ($i=sizeOf($xPathSet)-1; $i>=0; $i--) { + $mustReindex = $autoReindex; + // Flag the index as dirty; it's not uptodate. A reindex will be forced (if dirty) when exporting the XML doc + $this->_indexIsDirty = TRUE; + + $absoluteXPath = $xPathSet[$i]; + $parentNode =& $this->nodeIndex[$absoluteXPath]; + $newNode =& $this->cloneNode($node); + $parentNode['childNodes'][] =& $newNode; + $pos = count($parentNode['textParts']); + $pos -= $afterText ? 0 : 1; + $parentNode['textParts'] = array_merge( + array_slice($parentNode['textParts'], 0, $pos), + array(''), + array_slice($parentNode['textParts'], $pos) + ); + // We are going from bottom to top, but the user will want results from top to bottom. + if ($mustReindex) { + // We'll have to wait till after the reindex to get the full path to this new node. + $newNodes[] = &$newNode; + } else { + // If we are reindexing the tree later, then we can't return the user any + // useful results, so we just return them the count. + array_unshift($result, "$absoluteXPath/{$newNode['name']}"); + } + } + if ($mustReindex) { + $this->reindexNodeTree(); + // Now we must fill in the result array. Because until now we did not + // know what contextpos our newly added entries had, just their pos within + // the siblings. + foreach ($newNodes as $newNode) { + array_unshift($result, $newNode['xpath']); + } + } + if (count($result) == 1) $result = $result[0]; + return $result; + } + + /** + * Inserts a node before the reference node with the same parent. + * + * If you intend to do a lot of appending, you should leave autoIndex as FALSE + * and then call reindexNodeTree() when you are finished all the appending. + * + * @param $xPathQuery (string) Xpath to the node to insert new node before + * @param $node (mixed) String or Array (Usually a String) + * If string: Vaild XML. E.g. "" or " foo bar " + * If array: A Node (can be a whole sub-tree) (See comment in header) + * @param $afterText (bool) (optional, default=FLASE) Insert after the text. + * @param $autoReindex (bool) (optional, default=TRUE) Reindex the document to reflect + * the changes. A performance helper. See reindexNodeTree() + * @return (mixed) FALSE on error (or no match). On success we return the path(s) to the newly + * appended nodes. That is: Array of paths if more then 1 node was added or + * a single path string if only one node was added. + * NOTE: If autoReindex is FALSE, then we can't return the *complete* path + * as the exact doc-pos isn't available without reindexing. In that case we leave + * out the last [docpos] in the path(s). ie we'd return /A[3]/B instead of /A[3]/B[2] + * @see reindexNodeTree() + */ + function insertBefore($xPathQuery, $node, $afterText=TRUE, $autoReindex=TRUE) { + return $this->insertChild($xPathQuery, $node, $shiftRight=TRUE, $afterText, $autoReindex); + } + + + //----------------------------------------------------------------------------------------- + // XPath ------ Attribute Set/Get ------ + //----------------------------------------------------------------------------------------- + + /** + * Retrieves a dedecated attribute value or a hash-array of all attributes of a node. + * + * The first param $absoluteXPath must be a valid xpath OR a xpath-query that results + * to *one* xpath. If the second param $attrName is not set, a hash-array of all attributes + * of that node is returned. + * + * Optionally you may pass an attrubute name in $attrName and the function will return the + * string value of that attribute. + * + * @param $absoluteXPath (string) Full xpath OR a xpath-query that results to *one* xpath. + * @param $attrName (string) (Optional) The name of the attribute. See above. + * @return (mixed) hash-array or a string of attributes depending if the + * parameter $attrName was set (see above). FALSE if the + * node or attribute couldn't be found. + * @see setAttribute(), removeAttribute() + */ + function getAttributes($absoluteXPath, $attrName=NULL) { + // Numpty check + if (!isSet($this->nodeIndex[$absoluteXPath])) { + $xPathSet = $this->_resolveXPathQuery($absoluteXPath,'getAttributes'); + if (empty($xPathSet)) return FALSE; + // only use the first entry + $absoluteXPath = $xPathSet[0]; + } + if (!empty($this->parseOptions[XML_OPTION_CASE_FOLDING])) { + // Case in-sensitive + $attrName = strtoupper($attrName); + } + + // Return the complete list or just the desired element + if (is_null($attrName)) { + return $this->nodeIndex[$absoluteXPath]['attributes']; + } elseif (isSet($this->nodeIndex[$absoluteXPath]['attributes'][$attrName])) { + return $this->nodeIndex[$absoluteXPath]['attributes'][$attrName]; + } + return FALSE; + } + + /** + * Set attributes of a node(s). + * + * This method sets a number single attributes. An existing attribute is overwritten (default) + * with the new value, but setting the last param to FALSE will prevent overwritten. + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $name (string) Attribute name. + * @param $value (string) Attribute value. + * @param $overwrite (bool) If the attribute is already set we overwrite it (see text above) + * @return (bool) TRUE on success, FALSE on failure. + * @see getAttributes(), removeAttribute() + */ + function setAttribute($xPathQuery, $name, $value, $overwrite=TRUE) { + return $this->setAttributes($xPathQuery, array($name => $value), $overwrite); + } + + /** + * Version of setAttribute() that sets multiple attributes to node(s). + * + * This method sets a number of attributes. Existing attributes are overwritten (default) + * with the new values, but setting the last param to FALSE will prevent overwritten. + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $attributes (array) associative array of attributes to set. + * @param $overwrite (bool) If the attributes are already set we overwrite them (see text above) + * @return (bool) TRUE on success, FALSE otherwise + * @see setAttribute(), getAttributes(), removeAttribute() + */ + function setAttributes($xPathQuery, $attributes, $overwrite=TRUE) { + $status = FALSE; + do { // try-block + // The attributes parameter should be an associative array. + if (!is_array($attributes)) break; // try-block + + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'setAttributes'); + foreach($xPathSet as $absoluteXPath) { + // Add the attributes to the node. + $theNode =& $this->nodeIndex[$absoluteXPath]; + if (empty($theNode['attributes'])) { + $this->nodeIndex[$absoluteXPath]['attributes'] = $attributes; + } else { + $theNode['attributes'] = $overwrite ? array_merge($theNode['attributes'],$attributes) : array_merge($attributes, $theNode['attributes']); + } + } + $status = TRUE; + } while(FALSE); // END try-block + + return $status; + } + + /** + * Removes an attribute of a node(s). + * + * This method removes *ALL* attributres per default unless the second parameter $attrList is set. + * $attrList can be either a single attr-name as string OR a vector of attr-names as array. + * E.g. + * removeAttribute(); # will remove *ALL* attributes. + * removeAttribute(, 'A'); # will only remove attributes called 'A'. + * removeAttribute(, array('A_1','A_2')); # will remove attribute 'A_1' and 'A_2'. + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $attrList (mixed) (optional) if not set will delete *all* (see text above) + * @return (bool) TRUE on success, FALSE if the node couldn't be found + * @see getAttributes(), setAttribute() + */ + function removeAttribute($xPathQuery, $attrList=NULL) { + // Check for a valid xPathQuery + $xPathSet = $this->_resolveXPathQuery($xPathQuery, 'removeAttribute'); + + if (!empty($attrList) AND is_string($attrList)) $attrList = array($attrList); + if (!is_array($attrList)) return FALSE; + + foreach($xPathSet as $absoluteXPath) { + // If the attribute parameter wasn't set then remove all the attributes + if ($attrList[0] === NULL) { + $this->nodeIndex[$absoluteXPath]['attributes'] = array(); + continue; + } + // Remove all the elements in the array then. + foreach($attrList as $name) { + unset($this->nodeIndex[$absoluteXPath]['attributes'][$name]); + } + } + return TRUE; + } + + //----------------------------------------------------------------------------------------- + // XPath ------ Text Set/Get ------ + //----------------------------------------------------------------------------------------- + + /** + * Retrieve all the text from a node as a single string. + * + * Sample + * Given is: This is sometext + * Return of getData('/AA[1]') would be: " This is sometext " + * The first param $xPathQuery must be a valid xpath OR a xpath-query that + * results to *one* xpath. + * + * @param $xPathQuery (string) xpath to the node - resolves to *one* xpath. + * @return (mixed) The returned string (see above), FALSE if the node + * couldn't be found or is not unique. + * @see getDataParts() + */ + function getData($xPathQuery) { + $aDataParts = $this->getDataParts($xPathQuery); + if ($aDataParts === FALSE) return FALSE; + return implode('', $aDataParts); + } + + /** + * Retrieve all the text from a node as a vector of strings + * + * Where each element of the array was interrupted by a non-text child element. + * + * Sample + * Given is: This is sometext + * Return of getDataParts('/AA[1]') would be: array([0]=>' This ', [1]=>'is ', [2]=>' some', [3]=>'text '); + * The first param $absoluteXPath must be a valid xpath OR a xpath-query that results + * to *one* xpath. + * + * @param $xPathQuery (string) xpath to the node - resolves to *one* xpath. + * @return (mixed) The returned array (see above), or FALSE if node is not + * found or is not unique. + * @see getData() + */ + function getDataParts($xPathQuery) { + // Resolve xPath argument + $xPathSet = $this->_resolveXPathQuery($xPathQuery, 'getDataParts'); + if (1 !== ($setSize=count($xPathSet))) { + $this->_displayError(sprintf($this->errorStrings['AbsoluteXPathRequired'], $xPathQuery) . "Not unique xpath-query, matched {$setSize}-times.", __LINE__, __FILE__, FALSE); + return FALSE; + } + $absoluteXPath = $xPathSet[0]; + // Is it an attribute node? + if (preg_match(";(.*)/attribute::([^/]*)$;U", $xPathSet[0], $matches)) { + $absoluteXPath = $matches[1]; + $attribute = $matches[2]; + if (!isSet($this->nodeIndex[$absoluteXPath]['attributes'][$attribute])) { + $this->_displayError("The $absoluteXPath/attribute::$attribute value isn't a node in this document.", __LINE__, __FILE__, FALSE); + continue; + } + return array($this->nodeIndex[$absoluteXPath]['attributes'][$attribute]); + } else if (preg_match(":(.*)/text\(\)(\[(.*)\])?$:U", $xPathQuery, $matches)) { + $absoluteXPath = $matches[1]; + $textPartNr = $matches[2]; + return array($this->nodeIndex[$absoluteXPath]['textParts'][$textPartNr]); + } else { + return $this->nodeIndex[$absoluteXPath]['textParts']; + } + } + + /** + * Retrieves a sub string of a text-part OR attribute-value. + * + * This method retrieves the sub string of a specific text-part OR (if the + * $absoluteXPath references an attribute) the the sub string of the attribute value. + * If no 'direct referencing' is used (Xpath ends with text()[]), then + * the first text-part of the node ist returned (if exsiting). + * + * @param $absoluteXPath (string) Xpath to the node (See note above). + * @param $offset (int) (optional, default is 0) Starting offset. (Just like PHP's substr()) + * @param $count (number) (optional, default is ALL) Character count (Just like PHP's substr()) + * @return (mixed) The sub string, FALSE if not found or on error + * @see XPathEngine::wholeText(), PHP's substr() + */ + function substringData($absoluteXPath, $offset = 0, $count = NULL) { + if (!($text = $this->wholeText($absoluteXPath))) return FALSE; + if (is_null($count)) { + return substr($text, $offset); + } else { + return substr($text, $offset, $count); + } + } + + /** + * Replace a sub string of a text-part OR attribute-value. + * + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $replacement (string) The string to replace with. + * @param $offset (int) (optional, default is 0) Starting offset. (Just like PHP's substr_replace ()) + * @param $count (number) (optional, default is 0=ALL) Character count (Just like PHP's substr_replace()) + * @param $textPartNr (int) (optional) (see _getTextSet() ) + * @return (bool) The new string value on success, FALSE if not found or on error + * @see substringData() + */ + function replaceData($xPathQuery, $replacement, $offset = 0, $count = 0, $textPartNr=1) { + if (!($textSet = $this->_getTextSet($xPathQuery, $textPartNr))) return FALSE; + $tSize=sizeOf($textSet); + for ($i=0; $i<$tSize; $i++) { + if ($count) { + $textSet[$i] = substr_replace($textSet[$i], $replacement, $offset, $count); + } else { + $textSet[$i] = substr_replace($textSet[$i], $replacement, $offset); + } + } + return TRUE; + } + + /** + * Insert a sub string in a text-part OR attribute-value. + * + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $data (string) The string to replace with. + * @param $offset (int) (optional, default is 0) Offset at which to insert the data. + * @return (bool) The new string on success, FALSE if not found or on error + * @see replaceData() + */ + function insertData($xPathQuery, $data, $offset=0) { + return $this->replaceData($xPathQuery, $data, $offset, 0); + } + + /** + * Append text data to the end of the text for an attribute OR node text-part. + * + * This method adds content to a node. If it's an attribute node, then + * the value of the attribute will be set, otherwise the passed data will append to + * character data of the node text-part. Per default the first text-part is taken. + * + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) to the node(s) (See note above). + * @param $data (string) String containing the content to be added. + * @param $textPartNr (int) (optional, default is 1) (see _getTextSet()) + * @return (bool) TRUE on success, otherwise FALSE + * @see _getTextSet() + */ + function appendData($xPathQuery, $data, $textPartNr=1) { + if (!($textSet = $this->_getTextSet($xPathQuery, $textPartNr))) return FALSE; + $tSize=sizeOf($textSet); + for ($i=0; $i<$tSize; $i++) { + $textSet[$i] .= $data; + } + return TRUE; + } + + /** + * Delete the data of a node. + * + * This method deletes content of a node. If it's an attribute node, then + * the value of the attribute will be removed, otherwise the node text-part. + * will be deleted. Per default the first text-part is deleted. + * + * NOTE: When passing a xpath-query instead of an abs. Xpath. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) to the node(s) (See note above). + * @param $offset (int) (optional, default is 0) Starting offset. (Just like PHP's substr_replace()) + * @param $count (number) (optional, default is 0=ALL) Character count. (Just like PHP's substr_replace()) + * @param $textPartNr (int) (optional, default is 0) the text part to delete (see _getTextSet()) + * @return (bool) TRUE on success, otherwise FALSE + * @see _getTextSet() + */ + function deleteData($xPathQuery, $offset=0, $count=0, $textPartNr=1) { + if (!($textSet = $this->_getTextSet($xPathQuery, $textPartNr))) return FALSE; + $tSize=sizeOf($textSet); + for ($i=0; $i<$tSize; $i++) { + if (!$count) + $textSet[$i] = ""; + else + $textSet[$i] = substr_replace($textSet[$i],'', $offset, $count); + } + return TRUE; + } + + //----------------------------------------------------------------------------------------- + // XPath ------ Help Stuff ------ + //----------------------------------------------------------------------------------------- + + /** + * Parse the XML to a node-tree. A so called 'document' + * + * @param $xmlString (string) The string to turn into a document node. + * @return (&array) a node-tree + */ + function &_xml2Document($xmlString) { + $xmlOptions = array( + XML_OPTION_CASE_FOLDING => $this->getProperties('caseFolding'), + XML_OPTION_SKIP_WHITE => $this->getProperties('skipWhiteSpaces') + ); + $xmlParser =& new XPathEngine($xmlOptions); + $xmlParser->setVerbose($this->properties['verboseLevel']); + // Parse the XML string + if (!$xmlParser->importFromString($xmlString)) { + $this->_displayError($xmlParser->getLastError(), __LINE__, __FILE__, FALSE); + return FALSE; + } + return $xmlParser->getNode('/'); + } + + /** + * Get a reference-list to node text part(s) or node attribute(s). + * + * If the Xquery references an attribute(s) (Xquery ends with attribute::), + * then the text value of the node-attribute(s) is/are returned. + * Otherwise the Xquery is referencing to text part(s) of node(s). This can be either a + * direct reference to text part(s) (Xquery ends with text()[]) or indirect reference + * (a simple Xquery to node(s)). + * 1) Direct Reference (Xquery ends with text()[]): + * If the 'part-number' is omitted, the first text-part is assumed; starting by 1. + * Negative numbers are allowed, where -1 is the last text-part a.s.o. + * 2) Indirect Reference (a simple Xquery to node(s)): + * Default is to return the first text part(s). Optionally you may pass a parameter + * $textPartNr to define the text-part you want; starting by 1. + * Negative numbers are allowed, where -1 is the last text-part a.s.o. + * + * NOTE I : The returned vector is a set of references to the text parts / attributes. + * This is handy, if you wish to modify the contents. + * NOTE II: text-part numbers out of range will not be in the list + * NOTE III:Instead of an absolute xpath you may also pass a xpath-query. + * Depending on setModMatch() one, none or multiple nodes are affected. + * + * @param $xPathQuery (string) xpath to the node (See note above). + * @param $textPartNr (int) String containing the content to be set. + * @return (mixed) A vector of *references* to the text that match, or + * FALSE on error + * @see XPathEngine::wholeText() + */ + function _getTextSet($xPathQuery, $textPartNr=1) { + $ThisFunctionName = '_getTextSet'; + $bDebugThisFunction = in_array($ThisFunctionName, $this->aDebugFunctions); + $this->_beginDebugFunction($ThisFunctionName, $bDebugThisFunction); + if ($bDebugThisFunction) { + echo "Node: $xPathQuery\n"; + echo "Text Part Number: $textPartNr\n"; + echo "
    "; + } + + $status = FALSE; + $funcName = '_getTextSet'; + $textSet = array(); + + do { // try-block + // Check if it's a Xpath reference to an attribut(s). Xpath ends with attribute::) + if (preg_match(";(.*)/(attribute::|@)([^/]*)$;U", $xPathQuery, $matches)) { + $xPathQuery = $matches[1]; + $attribute = $matches[3]; + // Quick out + if (isSet($this->nodeIndex[$xPathQuery])) { + $xPathSet[] = $xPathQuery; + } else { + // Try to evaluate the absoluteXPath (since it seems to be an Xquery and not an abs. Xpath) + $xPathSet = $this->_resolveXPathQuery("$xPathQuery/attribute::$attribute", $funcName); + } + foreach($xPathSet as $absoluteXPath) { + preg_match(";(.*)/attribute::([^/]*)$;U", $xPathSet[0], $matches); + $absoluteXPath = $matches[1]; + $attribute = $matches[2]; + if (!isSet($this->nodeIndex[$absoluteXPath]['attributes'][$attribute])) { + $this->_displayError("The $absoluteXPath/attribute::$attribute value isn't a node in this document.", __LINE__, __FILE__, FALSE); + continue; + } + $textSet[] =& $this->nodes[$absoluteXPath]['attributes'][$attribute]; + } + $status = TRUE; + break; // try-block + } + + // Check if it's a Xpath reference direct to a text-part(s). (xpath ends with text()[]) + if (preg_match(":(.*)/text\(\)(\[(.*)\])?$:U", $xPathQuery, $matches)) { + $xPathQuery = $matches[1]; + // default to the first text node if a text node was not specified + $textPartNr = isSet($matches[2]) ? substr($matches[2],1,-1) : 1; + // Quick check + if (isSet($this->nodeIndex[$xPathQuery])) { + $xPathSet[] = $xPathQuery; + } else { + // Try to evaluate the absoluteXPath (since it seams to be an Xquery and not an abs. Xpath) + $xPathSet = $this->_resolveXPathQuery("$xPathQuery/text()[$textPartNr]", $funcName); + } + } + else { + // At this point we have been given an xpath with neither a 'text()' or 'attribute::' axis at the end + // So this means to get the text-part of the node. If parameter $textPartNr was not set, use the last + // text-part. + if (isSet($this->nodeIndex[$xPathQuery])) { + $xPathSet[] = $xPathQuery; + } else { + // Try to evaluate the absoluteXPath (since it seams to be an Xquery and not an abs. Xpath) + $xPathSet = $this->_resolveXPathQuery($xPathQuery, $funcName); + } + } + + if ($bDebugThisFunction) { + echo "Looking up paths for:\n"; + print_r($xPathSet); + } + + // Now fetch all text-parts that match. (May be 0,1 or many) + foreach($xPathSet as $absoluteXPath) { + unset($text); + if ($text =& $this->wholeText($absoluteXPath, $textPartNr)) { + $textSet[] =& $text; + } else { + // The node does not yet have any text, so we have to add a '' string so that + // if we insert or replace to it, then we'll actually have something to op on. + $this->nodeIndex[$absoluteXPath]['textParts'][$textPartNr-1] = ''; + $textSet[] =& $this->nodeIndex[$absoluteXPath]['textParts'][$textPartNr-1]; + } + } + + $status = TRUE; + } while (FALSE); // END try-block + + if (!$status) $result = FALSE; + else $result = $textSet; + + $this->_closeDebugFunction($ThisFunctionName, $result, $bDebugThisFunction); + + return $result; + } + + + /** + * Resolves an xPathQuery vector for a node op for modification + * + * It is possible to create a brand new object, and try to append and insert nodes + * into it, so this is a version of _resolveXPathQuery() that will autocreate the + * super root if it detects that it is not present and the $xPathQuery is empty. + * + * Also it demands that there be at least one node returned, and displays a suitable + * error message if the returned xPathSet does not contain any nodes. + * + * @param $xPathQuery (string) An xpath query targeting a single node. If empty() + * returns the root node and auto creates the root node + * if it doesn't exist. + * @param $function (string) The function in which this check was called + * @return (array) Vector of $absoluteXPath's (May be empty) + * @see _resolveXPathQuery() + */ + function _resolveXPathQueryForNodeMod($xPathQuery, $functionName) { + $xPathSet = array(); + if (empty($xPathQuery)) { + // You can append even if the root node doesn't exist. + if (!isset($this->nodeIndex[$xPathQuery])) $this->_createSuperRoot(); + $xPathSet[] = ''; + // However, you can only append to the super root, if there isn't already a root entry. + $rootNodes = $this->_resolveXPathQuery('/*','appendChild'); + if (count($rootNodes) !== 0) { + $this->_displayError(sprintf($this->errorStrings['RootNodeAlreadyExists']), __LINE__, __FILE__, FALSE); + return array(); + } + } else { + $xPathSet = $this->_resolveXPathQuery($xPathQuery,'appendChild'); + if (sizeOf($xPathSet) === 0) { + $this->_displayError(sprintf($this->errorStrings['NoNodeMatch'], $xPathQuery), __LINE__, __FILE__, FALSE); + return array(); + } + } + return $xPathSet; + } + + /** + * Resolves an xPathQuery vector depending on the property['modMatch'] + * + * To: + * - all matches, + * - the first + * - none (If the query matches more then one node.) + * see setModMatch() for details + * + * @param $xPathQuery (string) An xpath query targeting a single node. If empty() + * returns the root node (if it exists). + * @param $function (string) The function in which this check was called + * @return (array) Vector of $absoluteXPath's (May be empty) + * @see setModMatch() + */ + function _resolveXPathQuery($xPathQuery, $function) { + $xPathSet = array(); + do { // try-block + if (isSet($this->nodeIndex[$xPathQuery])) { + $xPathSet[] = $xPathQuery; + break; // try-block + } + if (empty($xPathQuery)) break; // try-block + if (substr($xPathQuery, -1) === '/') break; // If the xPathQuery ends with '/' then it cannot be a good query. + // If this xPathQuery is not absolute then attempt to evaluate it + $xPathSet = $this->match($xPathQuery); + + $resultSize = sizeOf($xPathSet); + switch($this->properties['modMatch']) { + case XPATH_QUERYHIT_UNIQUE : + if ($resultSize >1) { + $xPathSet = array(); + if ($this->properties['verboseLevel']) $this->_displayError("Canceled function '{$function}'. The query '{$xPathQuery}' mached {$resultSize} nodes and 'modMatch' is set to XPATH_QUERYHIT_UNIQUE.", __LINE__, __FILE__, FALSE); + } + break; + case XPATH_QUERYHIT_FIRST : + if ($resultSize >1) { + $xPathSet = array($xPathSet[0]); + if ($this->properties['verboseLevel']) $this->_displayError("Only modified first node in function '{$function}' because the query '{$xPathQuery}' mached {$resultSize} nodes and 'modMatch' is set to XPATH_QUERYHIT_FIRST.", __LINE__, __FILE__, FALSE); + } + break; + default: ; // DO NOTHING + } + } while (FALSE); + + if ($this->properties['verboseLevel'] >= 2) $this->_displayMessage("'{$xPathQuery}' parameter from '{$function}' returned the following nodes: ".(count($xPathSet)?implode('
    ', $xPathSet):'[none]'), __LINE__, __FILE__); + return $xPathSet; + } +} // END OF CLASS XPath + +// ----------------------------------------------------------------------------------------- +// ----------------------------------------------------------------------------------------- +// ----------------------------------------------------------------------------------------- +// ----------------------------------------------------------------------------------------- + +/************************************************************************************************** +// Usage Sample: +// ------------- +// Following code will give you an idea how to work with PHP.XPath. It's a working sample +// to help you get started. :o) +// Take the comment tags away and run this file. +**************************************************************************************************/ + +/** + * Produces a short title line. + */ +function _title($title) { + echo "

    " . htmlspecialchars($title) . "
    \n"; +} + +$self = isSet($_SERVER) ? $_SERVER['PHP_SELF'] : $PHP_SELF; +if (basename($self) == 'XPath.class.php') { + // The sampe source: + $q = '?'; + $xmlSource = <<< EOD + <{$q}Process_Instruction test="© All right reserved" {$q}> + ,,1,, + ..1.. + + ..2.. + ..3.. ..4.. +EOD; + + // The sample code: + $xmlOptions = array(XML_OPTION_CASE_FOLDING => TRUE, XML_OPTION_SKIP_WHITE => TRUE); + $xPath =& new XPath(FALSE, $xmlOptions); + //$xPath->bDebugXmlParse = TRUE; + if (!$xPath->importFromString($xmlSource)) { echo $xPath->getLastError(); exit; } + + _title("Following was imported:"); + echo $xPath->exportAsHtml(); + + _title("Get some content"); + echo "Last text part in <AAA>: '" . $xPath->wholeText('/AAA[1]', -1) ."'
    \n"; + echo "All the text in <AAA>: '" . $xPath->wholeText('/AAA[1]') ."'
    \n"; + echo "The attibute value in <BBB> using getAttributes('/AAA[1]/BBB[1]', 'FOO'): '" . $xPath->getAttributes('/AAA[1]', 'FOO') ."'
    \n"; + echo "The attibute value in <BBB> using getData('/AAA[1]/@FOO'): '" . $xPath->getData('/AAA[1]/@FOO') ."'
    \n"; + + _title("Append some additional XML below /AAA/BBB:"); + $xPath->appendChild('/AAA[1]/BBB[1]', ' Step 1. Append new node ', $afterText=FALSE); + $xPath->appendChild('/AAA[1]/BBB[1]', ' Step 2. Append new node ', $afterText=TRUE); + $xPath->appendChild('/AAA[1]/BBB[1]', ' Step 3. Append new node ', $afterText=TRUE); + echo $xPath->exportAsHtml(); + + _title("Insert some additional XML below :"); + $xPath->reindexNodeTree(); + $xPath->insertChild('/AAA[1]/BBB[1]', ' Step 1. Insert new node ', $shiftRight=TRUE, $afterText=TRUE); + $xPath->insertChild('/AAA[1]/BBB[1]', ' Step 2. Insert new node ', $shiftRight=FALSE, $afterText=TRUE); + $xPath->insertChild('/AAA[1]/BBB[1]', ' Step 3. Insert new node ', $shiftRight=FALSE, $afterText=FALSE); + echo $xPath->exportAsHtml(); + + _title("Replace the last node with new XML data '<DDD> Replaced last BB </DDD>':"); + $xPath->reindexNodeTree(); + $xPath->replaceChild('/AAA[1]/BB[last()]', ' Replaced last BB ', $afterText=FALSE); + echo $xPath->exportAsHtml(); + + _title("Replace second node with normal text"); + $xPath->reindexNodeTree(); + $xPath->replaceChildByData('/AAA[1]/BB[2]', '"Some new text"'); + echo $xPath->exportAsHtml(); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/System/includes/class.Template.inc.php b/oss/vtiger/trunk/modules/System/includes/class.Template.inc.php new file mode 100644 index 00000000..6c7652d1 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/class.Template.inc.php @@ -0,0 +1,449 @@ + remove undefined variables + * 'comment' => replace undefined variables with comments + * 'keep' => keep undefined variables + */ + var $unknowns = 'remove'; + + /* 'yes' => halt, 'report' => report error, continue, 'no' => ignore error quietly */ + var $halt_on_error = 'yes'; + + /* last error message is retained here */ + var $last_error = ''; + + /***************************************************************************/ + /* public: Constructor. + * root: template directory. + * unknowns: how to handle unknown variables. + */ + function Template($root = '.', $unknowns = 'remove') + { + $this->set_root($root); + $this->set_unknowns($unknowns); + } + + /* public: setroot(pathname $root) + * root: new template directory. + */ + function set_root($root) + { + if (!is_dir($root)) + { + $this->halt("set_root: $root is not a directory."); + return false; + } + $this->root = $root; + return true; + } + + /* public: set_unknowns(enum $unknowns) + * unknowns: 'remove', 'comment', 'keep' + * + */ + function set_unknowns($unknowns = 'keep') + { + $this->unknowns = $unknowns; + } + + /* public: set_file(array $filelist) + * filelist: array of handle, filename pairs. + * + * public: set_file(string $handle, string $filename) + * handle: handle for a filename, + * filename: name of template file + */ + function set_file($handle, $filename = '') + { + if (!is_array($handle)) + { + if ($filename == '') + { + $this->halt("set_file: For handle $handle filename is empty."); + return false; + } + $this->file[$handle] = $this->filename($filename); + } + else + { + reset($handle); + while(list($h, $f) = each($handle)) + { + $this->file[$h] = $this->filename($f); + } + } + } + + /* public: set_block(string $parent, string $handle, string $name = '') + * extract the template $handle from $parent, + * place variable {$name} instead. + */ + function set_block($parent, $handle, $name = '') + { + if (!$this->loadfile($parent)) + { + $this->halt("subst: unable to load $parent."); + return false; + } + if ($name == '') + { + $name = $handle; + } + $str = $this->get_var($parent); + $reg = "/(.*)\n\s*/sm"; + preg_match_all($reg, $str, $m); + $str = preg_replace($reg, '{' . "$name}", $str); + $this->set_var($handle, $m[1][0]); + $this->set_var($parent, $str); + } + + /* public: set_var(array $values) + * values: array of variable name, value pairs. + * + * public: set_var(string $varname, string $value) + * varname: name of a variable that is to be defined + * value: value of that variable + */ + function set_var($varname, $value = '') + { + if (!is_array($varname)) + { + if (!empty($varname)) + { + if ($this->debug) + { + print "scalar: set *$varname* to *$value*
    \n"; + } + $this->varkeys[$varname] = $this->varname($varname); + $this->varvals[$varname] = str_replace('phpGroupWare','eGroupWare',$value); + } + } + else + { + reset($varname); + while(list($k, $v) = each($varname)) + { + if (!empty($k)) + { + if ($this->debug) + { + print "array: set *$k* to *$v*
    \n"; + } + $this->varkeys[$k] = $this->varname($k); + $this->varvals[$k] = str_replace('phpGroupWare','eGroupWare',$v); + } + } + } + } + + /* public: subst(string $handle) + * handle: handle of template where variables are to be substituted. + */ + function subst($handle) + { + if (!$this->loadfile($handle)) + { + $this->halt("subst: unable to load $handle."); + return false; + } + + $str = $this->get_var($handle); + reset($this->varkeys); + while (list($k, $v) = each($this->varkeys)) + { + $str = str_replace($v, $this->varvals[$k], $str); + } + return $str; + } + + /* public: psubst(string $handle) + * handle: handle of template where variables are to be substituted. + */ + function psubst($handle) + { + print $this->subst($handle); + return false; + } + + /* public: parse(string $target, string $handle, boolean append) + * public: parse(string $target, array $handle, boolean append) + * target: handle of variable to generate + * handle: handle of template to substitute + * append: append to target handle + */ + function parse($target, $handle, $append = false) + { + if (!is_array($handle)) + { + $str = $this->subst($handle); + if ($append) + { + $this->set_var($target, $this->get_var($target) . $str); + } + else + { + $this->set_var($target, $str); + } + } + else + { + reset($handle); + while(list($i, $h) = each($handle)) + { + $str = $this->subst($h); + $this->set_var($target, $str); + } + } + return $str; + } + + function pparse($target, $handle, $append = false) + { + print $this->parse($target, $handle, $append); + return false; + } + + /* This is short for finish parse */ + function fp($target, $handle, $append = False) + { + return $this->finish($this->parse($target, $handle, $append)); + } + + /* This is a short cut for print finish parse */ + function pfp($target, $handle, $append = False) + { + echo $this->finish($this->parse($target, $handle, $append)); + } + + /* public: get_vars() + */ + function get_vars() + { + reset($this->varkeys); + while(list($k, $v) = each($this->varkeys)) + { + $result[$k] = $this->varvals[$k]; + } + return $result; + } + + /* public: get_var(string varname) + * varname: name of variable. + * + * public: get_var(array varname) + * varname: array of variable names + */ + function get_var($varname) + { + if (!is_array($varname)) + { + return $this->varvals[$varname]; + } + else + { + reset($varname); + while(list($k, $v) = each($varname)) + { + $result[$k] = $this->varvals[$k]; + } + return $result; + } + } + + /* public: get_undefined($handle) + * handle: handle of a template. + */ + function get_undefined($handle) + { + if (!$this->loadfile($handle)) + { + $this->halt("get_undefined: unable to load $handle."); + return false; + } + + preg_match_all("/\{([^}]+)\}/", $this->get_var($handle), $m); + $m = $m[1]; + if (!is_array($m)) + { + return false; + } + reset($m); + while(list($k, $v) = each($m)) + { + if (!isset($this->varkeys[$v])) + { + $result[$v] = $v; + } + } + + if (count($result)) + { + return $result; + } + else + { + return false; + } + } + + /* public: finish(string $str) + * str: string to finish. + */ + function finish($str) + { + switch ($this->unknowns) + { + case 'keep': + break; + case 'remove': + $str = preg_replace('/{[^ \t\r\n}]+}/', '', $str); + break; + case 'comment': + $str = preg_replace('/{([^ \t\r\n}]+)}/', "", $str); + break; + } + + return $str; + } + + /* public: p(string $varname) + * varname: name of variable to print. + */ + function p($varname) + { + print $this->finish($this->get_var($varname)); + } + + function get($varname) + { + return $this->finish($this->get_var($varname)); + } + + /***************************************************************************/ + /* private: filename($filename) + * filename: name to be completed. + */ + function filename($filename,$root='',$time=1) + { + if($root=='') + { + $root=$this->root; + } + if (substr($filename, 0, 1) != '/') + { + $new_filename = $root.'/'.$filename; + } + else + { + $new_filename = $filename; + } + + if (!file_exists($new_filename)) + { + if($time==2) + { + $this->halt("filename: file $new_filename does not exist."); + } + else + { + $new_root = str_replace($GLOBALS['egw_info']['server']['template_set'],'default',$root); + $new_filename = $this->filename(str_replace($root.'/','',$new_filename),$new_root,2); + } + } + return $new_filename; + } + + /* private: varname($varname) + * varname: name of a replacement variable to be protected. + */ + function varname($varname) + { + return '{'.$varname.'}'; + } + + /* private: loadfile(string $handle) + * handle: load file defined by handle, if it is not loaded yet. + */ + function loadfile($handle) + { + if (isset($this->varkeys[$handle]) and !empty($this->varvals[$handle])) + { + return true; + } + if (!isset($this->file[$handle])) + { + $this->halt("loadfile: $handle is not a valid handle."); + return false; + } + $filename = $this->file[$handle]; + + $str = implode('', @file($filename)); + if (empty($str)) + { + $this->halt("loadfile: While loading $handle, $filename does not exist or is empty."); + return false; + } + + $this->set_var($handle, $str); + return true; + } + + /***************************************************************************/ + /* public: halt(string $msg) + * msg: error message to show. + */ + function halt($msg) + { + $this->last_error = $msg; + + if ($this->halt_on_error != 'no') + { + $this->haltmsg($msg); + } + + if ($this->halt_on_error == 'yes') + { + echo('Halted.'); + } + + exit; + } + + /* public, override: haltmsg($msg) + * msg: error message to show. + */ + function haltmsg($msg) + { + printf("Template Error: %s
    \n", $msg); + } + } diff --git a/oss/vtiger/trunk/modules/System/includes/class.error.inc.php b/oss/vtiger/trunk/modules/System/includes/class.error.inc.php new file mode 100644 index 00000000..5e8175b7 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/class.error.inc.php @@ -0,0 +1,107 @@ +arrErrorList[$this->errors]['command'] = $strCommand; + $this->arrErrorList[$this->errors]['message'] = $strMessage; + $this->arrErrorList[$this->errors]['line'] = $intLine; + $this->arrErrorList[$this->errors]['file'] = basename( $strFile ); + $this->errors++; + } + + /** + * + * ErrorsAsHTML() + * + * @param - + * + * @return string string which contains a HTML table which can be used to echo out the errors + * + **/ + function ErrorsAsHTML() { + $strHTMLString = ""; + $strWARNString = ""; + $strHTMLhead = "\n" + . " \n" + . " \n" + . " \n" + . " \n" + . " \n" + . " \n"; + $strHTMLfoot = "
    FileLineCommandMessage
    "; + + if( $this->errors > 0 ) { + foreach( $this->arrErrorList as $arrLine ) { + if( $arrLine['command'] == "WARN" ) { + $strWARNString .= "WARNING: " . htmlspecialchars( $arrLine['message'] ) . "
    \n"; + } else { + $strHTMLString .= " \n" + . " " . htmlspecialchars( $arrLine['file'] ) . "\n" + . " " . $arrLine['line'] . "\n" + . " " . htmlspecialchars( $arrLine['command'] ) . "\n" + . " " . htmlspecialchars( $arrLine['message'] ) . "\n" + . " \n"; + } + } + } + + if( !empty( $strHTMLString ) ) { + $strHTMLString = $strWARNString . $strHTMLhead . $strHTMLString . $strHTMLfoot; + } else { + $strHTMLString = $strWARNString; + } + + return $strHTMLString; + } + + /** + * + * ErrorsExist() + * + * @param - + * + * @return true there are errors logged + * false no errors logged + * + **/ + function ErrorsExist() { + if( $this->errors > 0 ) { + return true; + } else { + return false; + } + } +} +?> diff --git a/oss/vtiger/trunk/modules/System/includes/common_functions.php b/oss/vtiger/trunk/modules/System/includes/common_functions.php new file mode 100644 index 00000000..50412f90 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/common_functions.php @@ -0,0 +1,350 @@ +\n\n"; +} +// usefull during development +error_reporting(E_ALL | E_NOTICE); +// print out the bar graph +// $value as full percentages +// $maximim as current maximum +// $b as scale factor +// $type as filesystem type +function create_bargraph ($value, $maximum, $b, $type = "") +{ + global $webpath; + + $textdir = direction(); + + $imgpath = 'modules/System/templates/' . TEMPLATE_SET . '/images/'; + $maximum == 0 ? $barwidth = 0 : $barwidth = round((100 / $maximum) * $value) * $b; + $red = 90 * $b; + $yellow = 75 * $b; + + if (!file_exists("/modules/System/templates/" . TEMPLATE_SET . "/images/nobar_left.gif")) { + if ($barwidth == 0) { + return '' + . '' + . ''; + } elseif (file_exists("/modules/System/templates/" . TEMPLATE_SET . "/images/yellowbar_left.gif") && $barwidth > $yellow && $barwidth < $red) { + return '' + . '' + . ''; + } elseif (($barwidth < $red) || ($type == "iso9660") || ($type == "CDFS")) { + return '' + . '' + . ''; + } else { + return '' + . '' + . ''; + } + } else { + if ($barwidth == 0) { + return '' + . '' + . ''; + } elseif (file_exists("/modules/System/templates/" . TEMPLATE_SET . "/images/yellowbar_left.gif") && $barwidth > $yellow && $barwidth < $red) { + return '' + . '' + . '' + . ''; + } elseif (($barwidth < $red) || $type == "iso9660" || ($type == "CDFS")) { + return '' + . '' + . '' + . ''; + } elseif ($barwidth == (100 * $b)) { + return '' + . '' + . ''; + } else { + return '' + . '' + . '' + . ''; + } + } +} + +function create_bargraph_grad( $value, $maximum, $b, $type = "" ) { + global $webpath; + + $maximum == 0 ? $barwidth = 0 : $barwidth = round((100 / $maximum) * $value); + $startColor = '0ef424'; // green + $endColor = 'ee200a'; // red + if ($barwidth > 100) { + $barwidth = 0; + } + + return ''; +} + +function direction() { + global $text_dir; + + if(!isset($text_dir) || $text_dir == "ltr") { + $result['direction'] = "ltr"; + $result['left'] = "left"; + $result['right'] = "right"; + } else { + $result['direction'] = "rtl"; + $result['left'] = "right"; + $result['right'] = "left"; + } + + return $result; +} + +// Find a system program. Do path checking +function find_program ($program) +{ + global $addpaths; + + $path = array('/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin'); + + if( isset($addpaths) && is_array($addpaths) ) { + $path = array_merge( $path, $addpaths ); + } + + if (function_exists("is_executable")) { + while ($this_path = current($path)) { + if (is_executable("$this_path/$program")) { + return "$this_path/$program"; + } + next($path); + } + } else { + return strpos($program, '.exe'); + } ; + + return; +} +// Execute a system program. return a trim()'d result. +// does very crude pipe checking. you need ' | ' for it to work +// ie $program = execute_program('netstat', '-anp | grep LIST'); +// NOT $program = execute_program('netstat', '-anp|grep LIST'); +function execute_program ($programname, $args = '', $booErrorRep = true ) +{ + global $error; + $buffer = ''; + $program = find_program($programname); + + if (!$program) { + if( $booErrorRep ) { + $error->addError( 'find_program(' . $programname . ')', 'program not found on the machine', __LINE__, __FILE__); + } + return; + } + + // see if we've gotten a |, if we have we need to do patch checking on the cmd + if ($args) { + $args_list = split(' ', $args); + for ($i = 0; $i < count($args_list); $i++) { + if ($args_list[$i] == '|') { + $cmd = $args_list[$i + 1]; + $new_cmd = find_program($cmd); + $args = ereg_replace("\| $cmd", "| $new_cmd", $args); + } + } + } + // we've finally got a good cmd line.. execute it + if ($fp = popen("($program $args > /dev/null) 3>&1 1>&2 2>&3", 'r')) { + while (!feof($fp)) { + $buffer .= fgets($fp, 4096); + } + pclose($fp); + $buffer = trim($buffer); + if (!empty($buffer)) { + if( $booErrorRep ) { + $error->addError( $program, $buffer, __LINE__, __FILE__); + } + } + } + if ($fp = popen("$program $args", 'r')) { + $buffer = ""; + while (!feof($fp)) { + $buffer .= fgets($fp, 4096); + } + pclose($fp); + } + $buffer = trim($buffer); + return $buffer; +} + +// A helper function, when passed a number representing KB, +// and optionally the number of decimal places required, +// it returns a formated number string, with unit identifier. +function format_bytesize ($kbytes, $dec_places = 2) +{ + global $text; + $spacer = ' '; + if ($kbytes > 1048576) { + $result = sprintf('%.' . $dec_places . 'f', $kbytes / 1048576); + $result .= $spacer . $text['gb']; + } elseif ($kbytes > 1024) { + $result = sprintf('%.' . $dec_places . 'f', $kbytes / 1024); + $result .= $spacer . $text['mb']; + } else { + $result = sprintf('%.' . $dec_places . 'f', $kbytes); + $result .= $spacer . $text['kb']; + } + return $result; +} + +function get_gif_image_height($image) +{ + // gives the height of the given GIF image, by reading it's LSD (Logical Screen Discriptor) + // by Edwin Meester aka MillenniumV3 + // Header: 3bytes Discription + // 3bytes Version + // LSD: 2bytes Logical Screen Width + // 2bytes Logical Screen Height + // 1bit Global Color Table Flag + // 3bits Color Resolution + // 1bit Sort Flag + // 3bits Size of Global Color Table + // 1byte Background Color Index + // 1byte Pixel Aspect Ratio + // Open Image + $fp = fopen($image, 'rb'); + // read Header + LSD + $header_and_lsd = fread($fp, 13); + fclose($fp); + // calc Height from Logical Screen Height bytes + $result = ord($header_and_lsd{8}) + ord($header_and_lsd{9}) * 255; + return $result; +} + +// Check if a string exist in the global $hide_mounts. +// Return true if this is the case. +function hide_mount($mount) { + global $hide_mounts; + if (isset($hide_mounts) && is_array($hide_mounts) && in_array($mount, $hide_mounts)) { + return true; + } + else { + return false; + } +} + +function uptime($timestamp) { + global $text; + $uptime = ''; + + $min = $timestamp / 60; + $hours = $min / 60; + $days = floor($hours / 24); + $hours = floor($hours - ($days * 24)); + $min = floor($min - ($days * 60 * 24) - ($hours * 60)); + + if ($days != 0) { + $uptime .= $days. " " . $text['days'] . " "; + } + + if ($hours != 0) { + $uptime .= $hours . " " . $text['hours'] . " "; + } + + $uptime .= $min . " " . $text['minutes']; + return $uptime; +} + +//Replace some chars which are not valid in xml with iso-8859-1 encoding +function replace_specialchars(&$xmlstring) { + $xmlstring = str_replace( chr(174), "(R)", $xmlstring ); + $xmlstring = str_replace( chr(169), "(C)", $xmlstring ); +} + +// find duplicate entrys and count them, show this value befor the duplicated name +function finddups( $arrInput ) { + $result = array(); + //Pinaki: Fix for ticket #4462 + if($arrInput!=null) + { + $buffer = array_count_values($arrInput); + foreach ($buffer as $key => $value) { + if( $value > 1 ) { + $result[] = "(" . $value . "x) " . $key; + } else { + $result[] = $key; + } + } + } + return $result; +} + +function rfts( $strFileName, $intLines = 0, $intBytes = 4096, $booErrorRep = true ) { + global $error; + $strFile = ""; + $intCurLine = 1; + + if( file_exists( $strFileName ) ) { + if( $fd = fopen( $strFileName, 'r' ) ) { + while( !feof( $fd ) ) { + $strFile .= fgets( $fd, $intBytes ); + if( $intLines <= $intCurLine && $intLines != 0 ) { + break; + } else { + $intCurLine++; + } + } + fclose( $fd ); + } else { + if( $booErrorRep ) { + $error->addError( 'fopen(' . $strFileName . ')', 'file can not read by phpsysinfo', __LINE__, __FILE__ ); + } + return "ERROR"; + } + } else { + if( $booErrorRep ) { + $error->addError( 'file_exists(' . $strFileName . ')', 'the file does not exist on your machine', __LINE__, __FILE__ ); + } + return "ERROR"; + } + + return $strFile; +} + +function gdc( $strPath, $booErrorRep = true ) { + global $error; + $arrDirectoryContent = array(); + + if( is_dir( $strPath ) ) { + if( $handle = opendir( $strPath ) ) { + while( ( $strFile = readdir( $handle ) ) !== false ) { + if( $strFile != "." && $strFile != ".." && $strFile != "CVS" ) { + $arrDirectoryContent[] = $strFile; + } + } + closedir( $handle ); + } else { + if( $booErrorRep ) { + $error->addError( 'opendir(' . $strPath . ')', 'directory can not be read by phpsysinfo', __LINE__, __FILE__ ); + } + } + } else { + if( $booErrorRep ) { + $error->addError( 'is_dir(' . $strPath . ')', 'directory does not exist on your machine', __LINE__, __FILE__ ); + } + } + + return $arrDirectoryContent; +} +?> diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ar_utf8.php b/oss/vtiger/trunk/modules/System/includes/lang/ar_utf8.php new file mode 100644 index 00000000..ee5ebb3f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ar_utf8.php @@ -0,0 +1,110 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/bg.php b/oss/vtiger/trunk/modules/System/includes/lang/bg.php new file mode 100644 index 00000000..be43bfea --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/bg.php @@ -0,0 +1,108 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/big5.php b/oss/vtiger/trunk/modules/System/includes/lang/big5.php new file mode 100644 index 00000000..6ae8607e --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/big5.php @@ -0,0 +1,107 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/br.php b/oss/vtiger/trunk/modules/System/includes/lang/br.php new file mode 100644 index 00000000..ab186f6b --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/br.php @@ -0,0 +1,105 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ca.php b/oss/vtiger/trunk/modules/System/includes/lang/ca.php new file mode 100644 index 00000000..b2b1267e --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ca.php @@ -0,0 +1,107 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/cn.php b/oss/vtiger/trunk/modules/System/includes/lang/cn.php new file mode 100644 index 00000000..26453a87 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/cn.php @@ -0,0 +1,105 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/cs.php b/oss/vtiger/trunk/modules/System/includes/lang/cs.php new file mode 100644 index 00000000..634c74df --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/cs.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ct.php b/oss/vtiger/trunk/modules/System/includes/lang/ct.php new file mode 100644 index 00000000..5cae788c --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ct.php @@ -0,0 +1,103 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/da.php b/oss/vtiger/trunk/modules/System/includes/lang/da.php new file mode 100644 index 00000000..ab6786d4 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/da.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/de.php b/oss/vtiger/trunk/modules/System/includes/lang/de.php new file mode 100644 index 00000000..65be011c --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/de.php @@ -0,0 +1,104 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/en.php b/oss/vtiger/trunk/modules/System/includes/lang/en.php new file mode 100644 index 00000000..4735269c --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/en.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/es.php b/oss/vtiger/trunk/modules/System/includes/lang/es.php new file mode 100644 index 00000000..0bb4e943 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/es.php @@ -0,0 +1,104 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/et.php b/oss/vtiger/trunk/modules/System/includes/lang/et.php new file mode 100644 index 00000000..e491d9a3 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/et.php @@ -0,0 +1,104 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/eu.php b/oss/vtiger/trunk/modules/System/includes/lang/eu.php new file mode 100644 index 00000000..e7680ef5 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/eu.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/fi.php b/oss/vtiger/trunk/modules/System/includes/lang/fi.php new file mode 100644 index 00000000..2544ecc4 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/fi.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/fr.php b/oss/vtiger/trunk/modules/System/includes/lang/fr.php new file mode 100644 index 00000000..01ccf9b4 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/fr.php @@ -0,0 +1,102 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/gr.php b/oss/vtiger/trunk/modules/System/includes/lang/gr.php new file mode 100644 index 00000000..ecb9ea8f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/gr.php @@ -0,0 +1,108 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/he.php b/oss/vtiger/trunk/modules/System/includes/lang/he.php new file mode 100644 index 00000000..fd52cc58 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/he.php @@ -0,0 +1,107 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/hu.php b/oss/vtiger/trunk/modules/System/includes/lang/hu.php new file mode 100644 index 00000000..5cb501fc --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/hu.php @@ -0,0 +1,108 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/id.php b/oss/vtiger/trunk/modules/System/includes/lang/id.php new file mode 100644 index 00000000..23f8da18 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/id.php @@ -0,0 +1,107 @@ + + +$text['title'] = 'Informasi Sistem'; + +$text['vitals'] = 'Informasi Utama'; +$text['hostname'] = 'Hostname Resmi'; +$text['ip'] = 'IP Penerima'; +$text['kversion'] = 'Versi Kernel'; +$text['dversion'] = 'Distro Name'; +$text['uptime'] = 'Aktif Selama'; +$text['users'] = 'Pengguna Saat Ini'; +$text['loadavg'] = 'Beban Rata-rata'; + +$text['hardware'] = 'Informasi Perangkat Keras'; +$text['numcpu'] = 'Prosesor'; +$text['cpumodel'] = 'Model'; +$text['cpuspeed'] = 'CPU Speed'; +$text['busspeed'] = 'BUS Speed'; +$text['cache'] = 'Ukuran Cache'; +$text['bogomips'] = 'Sistem Bogomips'; + +$text['pci'] = 'Perangkat PCI'; +$text['ide'] = 'Perangkat IDE'; +$text['scsi'] = 'Perangkat SCSI'; +$text['usb'] = 'Perangkat USB'; + +$text['netusage'] = 'Status Penggunaan Jaringan'; +$text['device'] = 'Perangkat'; +$text['received'] = 'Diterima'; +$text['sent'] = 'Dikirim'; +$text['errors'] = 'Rusak/Drop'; + +$text['connections'] = 'Koneksi Jaringan Aktif'; + +$text['memusage'] = 'Status Penggunaan Memori'; +$text['phymem'] = 'Memori Fisik'; +$text['swap'] = 'Swap HardDisk'; + +$text['fs'] = 'Status Penggunaan Media Penyimpanan dan Filesystem'; +$text['mount'] = 'Titik Mount'; +$text['partition'] = 'Partisi'; + +$text['percent'] = 'Digunakan (Persen)'; +$text['type'] = 'Tipe'; +$text['free'] = 'Bebas'; +$text['used'] = 'Digunakan'; +$text['size'] = 'Ukuran'; +$text['totals'] = 'Total'; + +$text['kb'] = 'KB'; +$text['mb'] = 'MB'; +$text['gb'] = 'GB'; + +$text['none'] = 'tidak ditemukan'; + +$text['capacity'] = 'Kapasitas'; + +$text['template'] = 'Template'; +$text['language'] = 'Bahasa'; +$text['submit'] = 'Gunakan'; +$text['created'] = 'Dibangun menggunakan'; +$text['locale'] = 'en_US'; +$text['gen_time'] = 'on %b %d, %Y at %I:%M %p'; + +$text['days'] = 'hari'; +$text['hours'] = 'jam'; +$text['minutes'] = 'menit'; + +$text['temperature'] = 'Temperature'; +$text['voltage'] = 'Voltage'; +$text['fans'] = 'Fans'; +$text['s_value'] = 'Value'; +$text['s_min'] = 'Min'; +$text['s_max'] = 'Max'; +$text['s_div'] = 'Div'; +$text['hysteresis'] = 'Hysteresis'; +$text['s_limit'] = 'Limit'; +$text['s_label'] = 'Label'; +$text['degree_mark'] = 'ºC'; +$text['voltage_mark'] = 'V'; +$text['rpm_mark'] = 'RPM'; + +$text['app'] = 'Kernel + applications'; +$text['buffers'] = 'Buffers'; +$text['cached'] = 'Cached'; + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/lang/index.html b/oss/vtiger/trunk/modules/System/includes/lang/index.html new file mode 100644 index 00000000..e69de29b diff --git a/oss/vtiger/trunk/modules/System/includes/lang/is.php b/oss/vtiger/trunk/modules/System/includes/lang/is.php new file mode 100644 index 00000000..b3eb8fa6 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/is.php @@ -0,0 +1,104 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/it.php b/oss/vtiger/trunk/modules/System/includes/lang/it.php new file mode 100644 index 00000000..37c2ccc4 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/it.php @@ -0,0 +1,104 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ja.php b/oss/vtiger/trunk/modules/System/includes/lang/ja.php new file mode 100644 index 00000000..ed1055e8 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ja.php @@ -0,0 +1,3 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/jp.php b/oss/vtiger/trunk/modules/System/includes/lang/jp.php new file mode 100644 index 00000000..da282ad9 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/jp.php @@ -0,0 +1,105 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ko.php b/oss/vtiger/trunk/modules/System/includes/lang/ko.php new file mode 100644 index 00000000..3f2720d6 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ko.php @@ -0,0 +1,107 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/lt.php b/oss/vtiger/trunk/modules/System/includes/lang/lt.php new file mode 100644 index 00000000..66840461 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/lt.php @@ -0,0 +1,109 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/lv.php b/oss/vtiger/trunk/modules/System/includes/lang/lv.php new file mode 100644 index 00000000..896ef451 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/lv.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/nl.php b/oss/vtiger/trunk/modules/System/includes/lang/nl.php new file mode 100644 index 00000000..7e19a2ee --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/nl.php @@ -0,0 +1,110 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/no.php b/oss/vtiger/trunk/modules/System/includes/lang/no.php new file mode 100644 index 00000000..0fbb10cb --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/no.php @@ -0,0 +1,104 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/pl.php b/oss/vtiger/trunk/modules/System/includes/lang/pl.php new file mode 100644 index 00000000..70a8a171 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/pl.php @@ -0,0 +1,107 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/pt-br.php b/oss/vtiger/trunk/modules/System/includes/lang/pt-br.php new file mode 100644 index 00000000..d3fc490b --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/pt-br.php @@ -0,0 +1,110 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/pt.php b/oss/vtiger/trunk/modules/System/includes/lang/pt.php new file mode 100644 index 00000000..14d19364 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/pt.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ro.php b/oss/vtiger/trunk/modules/System/includes/lang/ro.php new file mode 100644 index 00000000..d01863af --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ro.php @@ -0,0 +1,105 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/ru.php b/oss/vtiger/trunk/modules/System/includes/lang/ru.php new file mode 100644 index 00000000..e67dea6f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/ru.php @@ -0,0 +1,108 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/sk.php b/oss/vtiger/trunk/modules/System/includes/lang/sk.php new file mode 100644 index 00000000..4658434d --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/sk.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/sv.php b/oss/vtiger/trunk/modules/System/includes/lang/sv.php new file mode 100644 index 00000000..250c5b69 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/sv.php @@ -0,0 +1,107 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/tr.php b/oss/vtiger/trunk/modules/System/includes/lang/tr.php new file mode 100644 index 00000000..5421c772 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/tr.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/lang/tw.php b/oss/vtiger/trunk/modules/System/includes/lang/tw.php new file mode 100644 index 00000000..0a50ba6f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/lang/tw.php @@ -0,0 +1,106 @@ + diff --git a/oss/vtiger/trunk/modules/System/includes/mb/class.healthd.inc.php b/oss/vtiger/trunk/modules/System/includes/mb/class.healthd.inc.php new file mode 100644 index 00000000..8e7ef730 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/mb/class.healthd.inc.php @@ -0,0 +1,119 @@ +lines)) { + $this->lines = execute_program('healthdc', '-t'); + } + + $ar_buf = preg_split("/\t+/", $this->lines); + + $results[0]['label'] = 'temp1'; + $results[0]['value'] = $ar_buf[1]; + $results[0]['limit'] = '70.0'; + $results[0]['percent'] = $results[0]['value'] * 100 / $results[0]['limit']; + $results[1]['label'] = 'temp2'; + $results[1]['value'] = $ar_buf[2]; + $results[1]['limit'] = '70.0'; + $results[1]['percent'] = $results[1]['value'] * 100 / $results[1]['limit']; + $results[2]['label'] = 'temp3'; + $results[2]['value'] = $ar_buf[3]; + $results[2]['limit'] = '70.0'; + $results[2]['percent'] = $results[2]['value'] * 100 / $results[2]['limit']; + return $results; + } + + function fans() { + $ar_buf = array(); + $results = array(); + + if (!isset($this->lines)) { + $this->lines = execute_program('healthdc', '-t'); + } + + $ar_buf = preg_split("/\t+/", $this->lines); + + $results[0]['label'] = 'fan1'; + $results[0]['value'] = $ar_buf[4]; + $results[0]['min'] = '3000'; + $results[0]['div'] = '2'; + $results[1]['label'] = 'fan2'; + $results[1]['value'] = $ar_buf[5]; + $results[1]['min'] = '3000'; + $results[1]['div'] = '2'; + $results[2]['label'] = 'fan3'; + $results[2]['value'] = $ar_buf[6]; + $results[2]['min'] = '3000'; + $results[2]['div'] = '2'; + + return $results; + } + + function voltage() { + $ar_buf = array(); + $results = array(); + + if (!isset($this->lines)) { + $this->lines = execute_program('healthdc', '-t'); + } + + $ar_buf = preg_split("/\t+/", $this->lines); + + $results[0]['label'] = 'Vcore1'; + $results[0]['value'] = $ar_buf[7]; + $results[0]['min'] = '0.00'; + $results[0]['max'] = '0.00'; + $results[1]['label'] = 'Vcore2'; + $results[1]['value'] = $ar_buf[8]; + $results[1]['min'] = '0.00'; + $results[1]['max'] = '0.00'; + $results[2]['label'] = '3volt'; + $results[2]['value'] = $ar_buf[9]; + $results[2]['min'] = '0.00'; + $results[2]['max'] = '0.00'; + $results[3]['label'] = '+5Volt'; + $results[3]['value'] = $ar_buf[10]; + $results[3]['min'] = '0.00'; + $results[3]['max'] = '0.00'; + $results[4]['label'] = '+12Volt'; + $results[4]['value'] = $ar_buf[11]; + $results[4]['min'] = '0.00'; + $results[4]['max'] = '0.00'; + $results[5]['label'] = '-12Volt'; + $results[5]['value'] = $ar_buf[12]; + $results[5]['min'] = '0.00'; + $results[5]['max'] = '0.00'; + $results[6]['label'] = '-5Volt'; + $results[6]['value'] = $ar_buf[13]; + $results[6]['min'] = '0.00'; + $results[6]['max'] = '0.00'; + + return $results; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/mb/class.hwsensors.inc.php b/oss/vtiger/trunk/modules/System/includes/mb/class.hwsensors.inc.php new file mode 100644 index 00000000..4205c9e9 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/mb/class.hwsensors.inc.php @@ -0,0 +1,102 @@ +lines) ) { + $this->lines = execute_program('sysctl', '-w hw.sensors'); + } + + $lines = explode("\n", $this->lines); + + for ($i = 0, $j = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/[\s,]+/", $lines[$i]); + + if ($ar_buf[2] == 'temp') { + $results[$j]['label'] = $ar_buf[1]; + $results[$j]['value'] = $ar_buf[3]; + $results[$j]['limit'] = '70.0'; + $results[$j]['percent'] = $results[$j]['value'] * 100 / $results[$j]['limit']; + $j++; + } + } + + return $results; + } + + function fans() { + $ar_buf = array(); + $lines = array(); + $results = array(); + + if (!isset($this->lines) ) { + $this->lines = execute_program('sysctl', '-w hw.sensors'); + } + + $lines = explode("\n", $this->lines); + + for ($i = 0, $j = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/[\s,]+/", $lines[$i]); + + if ($ar_buf[2] == 'fanrpm') { + $results[$j]['label'] = $ar_buf[1]; + $results[$j]['value'] = $ar_buf[3]; + $j++; + } + } + + return $results; + } + + function voltage() { + $ar_buf = array(); + $lines = array(); + $results = array(); + + if (!isset($this->lines) ) { + $this->lines = execute_program('sysctl', '-w hw.sensors'); + } + + $lines = explode("\n", $this->lines); + + for ($i = 0, $j = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/[\s,]+/", $lines[$i]); + + if ($ar_buf[2] == 'volts_dc') { + $results[$j]['label'] = $ar_buf[1]; + $results[$j]['value'] = $ar_buf[3]; + $results[$j]['min'] = '0.00'; + $results[$j]['max'] = '0.00'; + $j++; + } + } + + return $results; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/mb/class.lmsensors.inc.php b/oss/vtiger/trunk/modules/System/includes/mb/class.lmsensors.inc.php new file mode 100644 index 00000000..7d057b17 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/mb/class.lmsensors.inc.php @@ -0,0 +1,176 @@ +lines = explode("\n", $lines); + } + + function temperature() { + $ar_buf = array(); + $results = array(); + + $sensors_value = $this->lines; + + foreach($sensors_value as $line) { + $data = array(); + if (ereg("(.*):(.*)\((.*)=(.*),(.*)=(.*)\)(.*)", $line, $data)) ; + elseif (ereg("(.*):(.*)\((.*)=(.*)\)(.*)", $line, $data)) ; + else (ereg("(.*):(.*)", $line, $data)); + if (count($data) > 1) { + $temp = substr(trim($data[2]), -1); + switch ($temp) { + case "C"; + case "F": + array_push($ar_buf, $line); + break; + } + } + } + + $i = 0; + foreach($ar_buf as $line) { + unset($data); + if (ereg("(.*):(.*).C[ ]*\((.*)=(.*).C,(.*)=(.*).C\)(.*)\)", $line, $data)) ; + elseif (ereg("(.*):(.*).C[ ]*\((.*)=(.*).C,(.*)=(.*).C\)(.*)", $line, $data)) ; + elseif (ereg("(.*):(.*).C[ ]*\((.*)=(.*).C\)(.*)", $line, $data)) ; + else (ereg("(.*):(.*).C", $line, $data)); + + $results[$i]['label'] = $data[1]; + $results[$i]['value'] = trim($data[2]); + if ( trim( $data[2] ) > trim( $data[6] ) ) { + $results[$i]['limit'] = "+75"; + $results[$i]['perce'] = "+75"; + } else { + $results[$i]['limit'] = isset($data[4]) ? trim($data[4]) : "+75"; + $results[$i]['perce'] = isset($data[6]) ? trim($data[6]) : "+75"; + } + if ($results[$i]['limit'] < $results[$i]['perce']) { + $results[$i]['limit'] = $results[$i]['perce']; + } + $i++; + } + + asort($results); + return array_values($results); + } + + function fans() { + $ar_buf = array(); + $results = array(); + + $sensors_value = $this->lines; + + foreach($sensors_value as $line) { + $data = array(); + if (ereg("(.*):(.*)\((.*)=(.*),(.*)=(.*)\)(.*)", $line, $data)); + elseif (ereg("(.*):(.*)\((.*)=(.*)\)(.*)", $line, $data)); + else ereg("(.*):(.*)", $line, $data); + + if (count($data) > 1) { + $temp = explode(" ", trim($data[2])); + if (count($temp) == 1) + $temp = explode("\xb0", trim($data[2])); + if(isset($temp[1])) { + switch ($temp[1]) { + case "RPM": + array_push($ar_buf, $line); + break; + } + } + } + } + + $i = 0; + foreach($ar_buf as $line) { + unset($data); + if (ereg("(.*):(.*) RPM \((.*)=(.*) RPM,(.*)=(.*)\)(.*)\)", $line, $data)); + elseif (ereg("(.*):(.*) RPM \((.*)=(.*) RPM,(.*)=(.*)\)(.*)", $line, $data)); + elseif (ereg("(.*):(.*) RPM \((.*)=(.*) RPM\)(.*)", $line, $data)); + else ereg("(.*):(.*) RPM", $line, $data); + + $results[$i]['label'] = trim($data[1]); + $results[$i]['value'] = trim($data[2]); + $results[$i]['min'] = isset($data[4]) ? trim($data[4]) : 0; + $results[$i]['div'] = isset($data[6]) ? trim($data[6]) : 0; + $i++; + } + + asort($results); + return array_values($results); + } + + function voltage() { + $ar_buf = array(); + $results = array(); + + $sensors_value = $this->lines; + + foreach($sensors_value as $line) { + $data = array(); + if (ereg("(.*):(.*)\((.*)=(.*),(.*)=(.*)\)(.*)", $line, $data)); + else ereg("(.*):(.*)", $line, $data); + + if (count($data) > 1) { + $temp = explode(" ", trim($data[2])); + if (count($temp) == 1) + $temp = explode("\xb0", trim($data[2])); + if (isset($temp[1])) { + switch ($temp[1]) { + case "V": + array_push($ar_buf, $line); + break; + } + } + } + } + + $i = 0; + foreach($ar_buf as $line) { + unset($data); + if (ereg("(.*):(.*) V \((.*)=(.*) V,(.*)=(.*) V\)(.*)\)", $line, $data)); + elseif (ereg("(.*):(.*) V \((.*)=(.*) V,(.*)=(.*) V\)(.*)", $line, $data)); + else ereg("(.*):(.*) V$", $line, $data); + if(isset($data[1])) { + $results[$i]['label'] = trim($data[1]); + $results[$i]['value'] = trim($data[2]); + $results[$i]['min'] = isset($data[4]) ? trim($data[4]) : 0; + $results[$i]['max'] = isset($data[6]) ? trim($data[6]) : 0; + $i++; + } + } + return $results; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/mb/class.mbm5.inc.php b/oss/vtiger/trunk/modules/System/includes/mb/class.mbm5.inc.php new file mode 100644 index 00000000..432b2970 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/mb/class.mbm5.inc.php @@ -0,0 +1,127 @@ +buf_label)) { + if ($fp = fopen('MBM5.csv', 'r')) { + $this->buf_label = split(';', fgets($fp)); + $this->buf_value = split(';', fgets($fp)); + fclose($fp); + } + } + + $results[0]['label'] = $this->buf_label[3]; + $results[0]['value'] = $this->buf_value[3]; + $results[0]['limit'] = '70.0'; + $results[0]['percent'] = $results[0]['value'] * 100 / $results[0]['limit']; + $results[1]['label'] = $this->buf_label[4]; + $results[1]['value'] = $this->buf_value[4]; + $results[1]['limit'] = '70.0'; + $results[1]['percent'] = $results[1]['value'] * 100 / $results[1]['limit']; + $results[2]['label'] = $this->buf_label[5]; + $results[2]['value'] = $this->buf_value[5]; + $results[2]['limit'] = '70.0'; + $results[2]['percent'] = $results[2]['value'] * 100 / $results[2]['limit']; + return $results; + } + + function fans() { + $results = array(); + + if (!isset($this->buf_label)) { + if ($fp = fopen('MBM5.csv', 'r')) { + $this->buf_label = split(';', fgets($fp)); + $this->buf_value = split(';', fgets($fp)); + fclose($fp); + } + } + + $results[0]['label'] = $this->buf_label[13]; + $results[0]['value'] = $this->buf_value[13]; + $results[0]['min'] = '3000'; + $results[0]['div'] = '2'; + $results[1]['label'] = $this->buf_label[14]; + $results[1]['value'] = $this->buf_value[14]; + $results[1]['min'] = '3000'; + $results[1]['div'] = '2'; + $results[2]['label'] = $this->buf_label[15]; + $results[2]['value'] = $this->buf_value[15]; + $results[2]['min'] = '3000'; + $results[2]['div'] = '2'; + + return $results; + } + + function voltage() { + $results = array(); + + if (!isset($this->buf_label)) { + if ($fp = fopen('MBM5.csv', 'r')) { + $this->buf_label = split(';', fgets($fp)); + $this->buf_value = split(';', fgets($fp)); + fclose($fp); + } + } + + $results[0]['label'] = $this->buf_label[6]; + $results[0]['value'] = $this->buf_value[6]; + $results[0]['min'] = '0.00'; + $results[0]['max'] = '0.00'; + $results[1]['label'] = $this->buf_label[7]; + $results[1]['value'] = $this->buf_value[7]; + $results[1]['min'] = '0.00'; + $results[1]['max'] = '0.00'; + $results[2]['label'] = $this->buf_label[8]; + $results[2]['value'] = $this->buf_value[8]; + $results[2]['min'] = '0.00'; + $results[2]['max'] = '0.00'; + $results[3]['label'] = $this->buf_label[9]; + $results[3]['value'] = $this->buf_value[9]; + $results[3]['min'] = '0.00'; + $results[3]['max'] = '0.00'; + $results[4]['label'] = $this->buf_label[10]; + $results[4]['value'] = $this->buf_value[10]; + $results[4]['min'] = '0.00'; + $results[4]['max'] = '0.00'; + $results[5]['label'] = $this->buf_label[11]; + $results[5]['value'] = $this->buf_value[11]; + $results[5]['min'] = '0.00'; + $results[5]['max'] = '0.00'; + $results[6]['label'] = $this->buf_label[12]; + $results[6]['value'] = $this->buf_value[12]; + $results[6]['min'] = '0.00'; + $results[6]['max'] = '0.00'; + + return $results; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/mb/class.mbmon.inc.php b/oss/vtiger/trunk/modules/System/includes/mb/class.mbmon.inc.php new file mode 100644 index 00000000..fa574574 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/mb/class.mbmon.inc.php @@ -0,0 +1,100 @@ +lines) ) { + $this->lines = explode("\n", execute_program('mbmon', '-c 1 -r')); + } + + $i = 0; + foreach($this->lines as $line) { + if (preg_match('/^(TEMP\d*)\s*:\s*(.*)$/D', $line, $data)) { + if ($data[2]<>'0') { + $results[$i]['label'] = $data[1]; + $results[$i]['limit'] = '70.0'; + if($data[2] > 250) { + $results[$i]['value'] = 0; + $results[$i]['percent'] = 0; + } else { + $results[$i]['value'] = $data[2]; + $results[$i]['percent'] = $results[$i]['value'] * 100 / $results[$i]['limit']; + } + $i++; + } + } + } + return $results; + } + + function fans() { + $results = array(); + + if (!isset($this->lines) ) { + $this->lines = explode("\n", execute_program('mbmon', '-c 1 -r')); + } + + $i = 0; + foreach($this->lines as $line) { + if (preg_match('/^(FAN\d*)\s*:\s*(.*)$/D', $line, $data)) { + if ($data[2]<>'0') { + $results[$i]['label'] = $data[1]; + $results[$i]['value'] = $data[2]; + $results[$i]['min'] = '3000'; + $results[$i]['div'] = '2'; + $i++; + } + } + } + return $results; + } + + function voltage() { + $results = array(); + + if (!isset($this->lines) ) { + $this->lines = explode("\n", execute_program('mbmon', '-c 1 -r')); + } + + $i = 0; + foreach($this->lines as $line) { + if (preg_match('/^(V.*)\s*:\s*(.*)$/D', $line, $data)) { + if ($data[2]<>'+0.00') { + $results[$i]['label'] = $data[1]; + $results[$i]['value'] = $data[2]; + $results[$i]['min'] = '0.00'; + $results[$i]['max'] = '0.00'; + $i++; + } + } + } + + return $results; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/mb/index.html b/oss/vtiger/trunk/modules/System/includes/mb/index.html new file mode 100644 index 00000000..e69de29b diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.BSD.common.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.BSD.common.inc.php new file mode 100644 index 00000000..8cd02f2b --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.BSD.common.inc.php @@ -0,0 +1,298 @@ +parser = new Parser(); + $this->parser->df_param = ""; + } + + // read /var/run/dmesg.boot, but only if we haven't already. + function read_dmesg () { + if (! $this->dmesg) { + $parts = explode("rebooting", rfts( '/var/run/dmesg.boot' ) ); + $this->dmesg = explode("\n", $parts[count($parts) - 1]); + } + return $this->dmesg; + } + + // grabs a key from sysctl(8) + function grab_key ($key) { + return execute_program('sysctl', "-n $key"); + } + // get our apache SERVER_NAME or vhost + function hostname () { + if (!($result = getenv('SERVER_NAME'))) { + $result = "N.A."; + } + return $result; + } + // get our canonical hostname + function chostname () { + return execute_program('hostname'); + } + // get the IP address of our canonical hostname + function ip_addr () { + if (!($result = getenv('SERVER_ADDR'))) { + $result = gethostbyname($this->chostname()); + } + return $result; + } + + function kernel () { + $s = $this->grab_key('kern.version'); + $a = explode(':', $s); + return $a[0] . $a[1] . ':' . $a[2]; + } + + function uptime () { + $result = $this->get_sys_ticks(); + + return $result; + } + + function users () { + return execute_program('who', '| wc -l'); + } + + function loadavg ($bar = false) { + $s = $this->grab_key('vm.loadavg'); + $s = ereg_replace('{ ', '', $s); + $s = ereg_replace(' }', '', $s); + $results['avg'] = explode(' ', $s); + + if ($bar) { + if ($fd = $this->grab_key('kern.cp_time')) { + // Find out the CPU load + // user + sys = load + // total = total + preg_match($this->cpu_regexp2, $fd, $res ); + $load = $res[2] + $res[3] + $res[4]; // cpu.user + cpu.sys + $total = $res[2] + $res[3] + $res[4] + $res[5]; // cpu.total + + // we need a second value, wait 1 second befor getting (< 1 second no good value will occour) + sleep(1); + $fd = $this->grab_key('kern.cp_time'); + preg_match($this->cpu_regexp2, $fd, $res ); + $load2 = $res[2] + $res[3] + $res[4]; + $total2 = $res[2] + $res[3] + $res[4] + $res[5]; + $results['cpupercent'] = (100*($load2 - $load)) / ($total2 - $total); + } + } + return $results; + } + + function cpu_info () { + $results = array(); + $ar_buf = array(); + + $results['model'] = $this->grab_key('hw.model'); + $results['cpus'] = $this->grab_key('hw.ncpu'); + + for ($i = 0, $max = count($this->read_dmesg()); $i < $max; $i++) { + $buf = $this->dmesg[$i]; + if (preg_match("/$this->cpu_regexp/", $buf, $ar_buf)) { + $results['cpuspeed'] = round($ar_buf[2]); + break; + } + } + return $results; + } + // get the scsi device information out of dmesg + function scsi () { + $results = array(); + $ar_buf = array(); + + for ($i = 0, $max = count($this->read_dmesg()); $i < $max; $i++) { + $buf = $this->dmesg[$i]; + + if (preg_match("/$this->scsi_regexp1/", $buf, $ar_buf)) { + $s = $ar_buf[1]; + $results[$s]['model'] = $ar_buf[2]; + $results[$s]['media'] = 'Hard Disk'; + } elseif (preg_match("/$this->scsi_regexp2/", $buf, $ar_buf)) { + $s = $ar_buf[1]; + $results[$s]['capacity'] = $ar_buf[2] * 2048 * 1.049; + } + } + // return array_values(array_unique($results)); + // 1. more useful to have device names + // 2. php 4.1.1 array_unique() deletes non-unique values. + asort($results); + return $results; + } + + // get the pci device information out of dmesg + function pci () { + $results = array(); + + if( !( is_array($results = $this->parser->parse_lspci()) || is_array($results = $this->parser->parse_pciconf() ))) { + for ($i = 0, $s = 0; $i < count($this->read_dmesg()); $i++) { + $buf = $this->dmesg[$i]; + if(!isset($this->pci_regexp1) && !isset($this->pci_regexp2)) { + $this->pci_regexp1 = '/(.*): <(.*)>(.*) pci[0-9]$/'; + $this->pci_regexp2 = '/(.*): <(.*)>.* at [.0-9]+ irq/'; + } + if (preg_match($this->pci_regexp1, $buf, $ar_buf)) { + $results[$s++] = $ar_buf[1] . ": " . $ar_buf[2]; + } elseif (preg_match($this->pci_regexp2, $buf, $ar_buf)) { + $results[$s++] = $ar_buf[1] . ": " . $ar_buf[2]; + } + } + asort($results); + } + return $results; + } + + // get the ide device information out of dmesg + function ide () { + $results = array(); + + $s = 0; + for ($i = 0, $max = count($this->read_dmesg()); $i < $max; $i++) { + $buf = $this->dmesg[$i]; + + if (preg_match('/^(ad[0-9]+): (.*)MB <(.*)> (.*) (.*)/', $buf, $ar_buf)) { + $s = $ar_buf[1]; + $results[$s]['model'] = $ar_buf[3]; + $results[$s]['media'] = 'Hard Disk'; + $results[$s]['capacity'] = $ar_buf[2] * 2048 * 1.049; + } elseif (preg_match('/^(acd[0-9]+): (.*) <(.*)> (.*)/', $buf, $ar_buf)) { + $s = $ar_buf[1]; + $results[$s]['model'] = $ar_buf[3]; + $results[$s]['media'] = 'CD-ROM'; + } + } + // return array_values(array_unique($results)); + // 1. more useful to have device names + // 2. php 4.1.1 array_unique() deletes non-unique values. + asort($results); + return $results; + } + + // place holder function until we add acual usb detection + function usb () { + return array(); + } + + function sbus () { + $results = array(); + $_results[0] = ""; + // TODO. Nothing here yet. Move along. + $results = $_results; + return $results; + } + + function memory () { + $s = $this->grab_key('hw.physmem'); + + if (PHP_OS == 'FreeBSD' || PHP_OS == 'OpenBSD') { + // vmstat on fbsd 4.4 or greater outputs kbytes not hw.pagesize + // I should probably add some version checking here, but for now + // we only support fbsd 4.4 + $pagesize = 1024; + } else { + $pagesize = $this->grab_key('hw.pagesize'); + } + + $results['ram'] = array(); + + $pstat = execute_program('vmstat'); + $lines = split("\n", $pstat); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i], 19); + if ($i == 2) { + if(PHP_OS == 'NetBSD') { + $results['ram']['free'] = $ar_buf[5]; + } else { + $results['ram']['free'] = $ar_buf[5] * $pagesize / 1024; + } + } + } + + $results['ram']['total'] = $s / 1024; + $results['ram']['shared'] = 0; + $results['ram']['buffers'] = 0; + $results['ram']['used'] = $results['ram']['total'] - $results['ram']['free']; + $results['ram']['cached'] = 0; + $results['ram']['t_used'] = $results['ram']['used']; + $results['ram']['t_free'] = $results['ram']['free']; + + $results['ram']['percent'] = round(($results['ram']['used'] * 100) / $results['ram']['total']); + + if (PHP_OS == 'OpenBSD' || PHP_OS == 'NetBSD') { + $pstat = execute_program('swapctl', '-l -k'); + } else { + $pstat = execute_program('swapinfo', '-k'); + } + + $lines = split("\n", $pstat); + + $results['swap']['total'] = 0; + $results['swap']['used'] = 0; + $results['swap']['free'] = 0; + + for ($i = 1, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i], 6); + + if ($ar_buf[0] != 'Total') { + $results['swap']['total'] = $results['swap']['total'] + $ar_buf[1]; + $results['swap']['used'] = $results['swap']['used'] + $ar_buf[2]; + $results['swap']['free'] = $results['swap']['free'] + $ar_buf[3]; + + $results['devswap'][$i - 1] = array(); + $results['devswap'][$i - 1]['dev'] = $ar_buf[0]; + $results['devswap'][$i - 1]['total'] = $ar_buf[1]; + $results['devswap'][$i - 1]['used'] = $ar_buf[2]; + $results['devswap'][$i - 1]['free'] = ($results['devswap'][$i - 1]['total'] - $results['devswap'][$i - 1]['used']); + $results['devswap'][$i - 1]['percent'] = $ar_buf[2] > 0 ? round(($ar_buf[2] * 100) / $ar_buf[1]) : 0; + } + } + $results['swap']['percent'] = round(($results['swap']['used'] * 100) / $results['swap']['total']); + + if( is_callable( array( 'sysinfo', 'memory_additional' ) ) ) { + $results = $this->memory_additional( $results ); + } + return $results; + } + + function filesystems () { + return $this->parser->parse_filesystems(); + } + + function distro () { + $distro = execute_program('uname', '-s'); + $result = $distro; + return($result); + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.Darwin.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.Darwin.inc.php new file mode 100644 index 00000000..ef9f6f6f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.Darwin.inc.php @@ -0,0 +1,237 @@ +addError("WARN", "The Darwin version of phpSysInfo is work in progress, some things currently don't work"); + +class sysinfo extends bsd_common { + var $cpu_regexp; + var $scsi_regexp; + // Our contstructor + // this function is run on the initialization of this class + function sysinfo () { + // $this->cpu_regexp = "CPU: (.*) \((.*)-MHz (.*)\)"; + // $this->scsi_regexp1 = "^(.*): <(.*)> .*SCSI.*device"; + $this->cpu_regexp2 = "/(.*) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/"; + } + + function grab_key ($key) { + $s = execute_program('sysctl', $key); + $s = ereg_replace($key . ': ', '', $s); + $s = ereg_replace($key . ' = ', '', $s); // fix Apple set keys + + return $s; + } + + function grab_ioreg ($key) { + $s = execute_program('ioreg', '-cls "' . $key . '" | grep "' . $key . '"'); //ioreg -cls "$key" | grep "$key" + $s = ereg_replace('\|', '', $s); + $s = ereg_replace('\+\-\o', '', $s); + $s = ereg_replace('[ ]+', '', $s); + $s = ereg_replace('<[^>]+>', '', $s); // remove possible XML conflicts + + return $s; + } + + function get_sys_ticks () { + $a = execute_program('sysctl', '-n kern.boottime'); // get boottime (value in seconds) + $sys_ticks = time() - $a; + + return $sys_ticks; + } + + function cpu_info () { + $results = array(); + // $results['model'] = $this->grab_key('hw.model'); // need to expand this somehow... + // $results['model'] = $this->grab_key('hw.machine'); + $results['model'] = ereg_replace('Processor type: ', '', execute_program('hostinfo', '| grep "Processor type"')); // get processor type + $results['cpus'] = $this->grab_key('hw.ncpu'); + $results['cpuspeed'] = round($this->grab_key('hw.cpufrequency') / 1000000); // return cpu speed - Mhz + $results['busspeed'] = round($this->grab_key('hw.busfrequency') / 1000000); // return bus speed - Mhz + $results['cache'] = round($this->grab_key('hw.l2cachesize') / 1024); // return l2 cache + + if (($this->grab_key('hw.model') == "PowerMac3,6") && ($results['cpus'] == "2")) { $results['model'] = 'Dual G4 - (PowerPC 7450)';} // is Dual G4 + if (($this->grab_key('hw.model') == "PowerMac7,2") && ($results['cpus'] == "2")) { $results['model'] = 'Dual G5 - (PowerPC 970)';} // is Dual G5 + + return $results; + } + // get the pci device information out of ioreg + function pci () { + $results = array(); + $s = $this->grab_ioreg('IOPCIDevice'); + + $lines = split("\n", $s); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i], 19); + $results[$i] = $ar_buf[0]; + } + asort($results); + return array_values(array_unique($results)); + } + // get the ide device information out of ioreg + function ide () { + $results = array(); + // ioreg | grep "Media " + $s = $this->grab_ioreg('IOATABlockStorageDevice'); + + $lines = split("\n", $s); + $j = 0; + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\/\//", $lines[$i], 19); + + if ($ar_buf[1] == 'class IOMedia' && preg_match('/Media/', $ar_buf[0])) { + $results[$j++]['model'] = $ar_buf[0]; + } + } + asort($results); + return array_values(array_unique($results)); + } + + function memory () { + $s = $this->grab_key('hw.memsize'); + + $results['ram'] = array(); + + $pstat = execute_program('vm_stat'); // use darwin's vm_stat + $lines = split("\n", $pstat); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i], 19); + + if ($i == 1) { + $results['ram']['free'] = $ar_buf[2] * 4; // calculate free memory from page sizes (each page = 4MB) + } + } + + $results['ram']['total'] = $s / 1024; + $results['ram']['shared'] = 0; + $results['ram']['buffers'] = 0; + $results['ram']['used'] = $results['ram']['total'] - $results['ram']['free']; + $results['ram']['cached'] = 0; + $results['ram']['t_used'] = $results['ram']['used']; + $results['ram']['t_free'] = $results['ram']['free']; + + $results['ram']['percent'] = round(($results['ram']['used'] * 100) / $results['ram']['total']); + // need to fix the swap info... + $pstat = execute_program('swapinfo', '-k'); + $lines = split("\n", $pstat); + + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i], 6); + + if ($i == 0) { + $results['swap']['total'] = 0; + $results['swap']['used'] = 0; + $results['swap']['free'] = 0; + } else { + $results['swap']['total'] = $results['swap']['total'] + $ar_buf[1]; + $results['swap']['used'] = $results['swap']['used'] + $ar_buf[2]; + $results['swap']['free'] = $results['swap']['free'] + $ar_buf[3]; + } + } + $results['swap']['percent'] = round(($results['swap']['used'] * 100) / $results['swap']['total']); + + return $results; + } + + function network () { + $netstat = execute_program('netstat', '-nbdi | cut -c1-24,42- | grep Link'); + $lines = split("\n", $netstat); + $results = array(); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i]); + if (!empty($ar_buf[0])) { + $results[$ar_buf[0]] = array(); + + $results[$ar_buf[0]]['rx_bytes'] = $ar_buf[5]; + $results[$ar_buf[0]]['rx_packets'] = $ar_buf[3]; + $results[$ar_buf[0]]['rx_errs'] = $ar_buf[4]; + $results[$ar_buf[0]]['rx_drop'] = $ar_buf[10]; + + $results[$ar_buf[0]]['tx_bytes'] = $ar_buf[8]; + $results[$ar_buf[0]]['tx_packets'] = $ar_buf[6]; + $results[$ar_buf[0]]['tx_errs'] = $ar_buf[7]; + $results[$ar_buf[0]]['tx_drop'] = $ar_buf[10]; + + $results[$ar_buf[0]]['errs'] = $ar_buf[4] + $ar_buf[7]; + $results[$ar_buf[0]]['drop'] = $ar_buf[10]; + } + } + return $results; + } + + function filesystems () { + $df = execute_program('df', '-k'); + $mounts = split("\n", $df); + $fstype = array(); + + $s = execute_program('mount'); + $lines = explode("\n", $s); + + $i = 0; + while (list(, $line) = each($lines)) { + ereg('(.*) \((.*)\)', $line, $a); + + $m = explode(' ', $a[0]); + $fsdev[$m[0]] = $a[2]; + } + + for ($i = 1, $j = 0, $max = sizeof($mounts); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $mounts[$i], 6); + + switch ($ar_buf[0]) { + case 'automount': // skip the automount entries + case 'devfs': // skip the dev filesystem + case 'fdesc': // skip the fdesc + case 'procfs': // skip the proc filesystem + case '': // skip the vol filesystem + continue 2; + break; + } + if (hide_mount($ar_buf[5])) { + continue; + } + + $results[$j] = array(); + + $results[$j]['disk'] = $ar_buf[0]; + $results[$j]['size'] = $ar_buf[1]; + $results[$j]['used'] = $ar_buf[2]; + $results[$j]['free'] = $ar_buf[3]; + $results[$j]['percent'] = $ar_buf[4]; + $results[$j]['mount'] = $ar_buf[5]; + ($fstype[$ar_buf[5]]) ? $results[$j]['fstype'] = $fstype[$ar_buf[5]] : $results[$j]['fstype'] = $fsdev[$ar_buf[0]]; + $j++; + } + return $results; + } + + function distroicon () { + $result = 'Darwin.png'; + return($result); + } + +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.FreeBSD.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.FreeBSD.inc.php new file mode 100644 index 00000000..2d8013ff --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.FreeBSD.inc.php @@ -0,0 +1,108 @@ +bsd_common(); + $this->cpu_regexp = "CPU: (.*) \((.*)-MHz (.*)\)"; + $this->scsi_regexp1 = "^(.*): <(.*)> .*SCSI.*device"; + $this->scsi_regexp2 = "^(da[0-9]): (.*)MB "; + $this->cpu_regexp2 = "/(.*) ([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)/"; + } + + function get_sys_ticks () { + $s = explode(' ', $this->grab_key('kern.boottime')); + $a = ereg_replace('{ ', '', $s[3]); + $sys_ticks = time() - $a; + return $sys_ticks; + } + + function network () { + $netstat = execute_program('netstat', '-nibd | grep Link'); + $lines = split("\n", $netstat); + $results = array(); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i]); + if (!empty($ar_buf[0])) { + $results[$ar_buf[0]] = array(); + + if (strlen($ar_buf[3]) < 15) { + $results[$ar_buf[0]]['rx_bytes'] = $ar_buf[5]; + $results[$ar_buf[0]]['rx_packets'] = $ar_buf[3]; + $results[$ar_buf[0]]['rx_errs'] = $ar_buf[4]; + $results[$ar_buf[0]]['rx_drop'] = $ar_buf[10]; + + $results[$ar_buf[0]]['tx_bytes'] = $ar_buf[8]; + $results[$ar_buf[0]]['tx_packets'] = $ar_buf[6]; + $results[$ar_buf[0]]['tx_errs'] = $ar_buf[7]; + $results[$ar_buf[0]]['tx_drop'] = $ar_buf[10]; + + $results[$ar_buf[0]]['errs'] = $ar_buf[4] + $ar_buf[7]; + $results[$ar_buf[0]]['drop'] = $ar_buf[10]; + } else { + $results[$ar_buf[0]]['rx_bytes'] = $ar_buf[6]; + $results[$ar_buf[0]]['rx_packets'] = $ar_buf[4]; + $results[$ar_buf[0]]['rx_errs'] = $ar_buf[5]; + $results[$ar_buf[0]]['rx_drop'] = $ar_buf[11]; + + $results[$ar_buf[0]]['tx_bytes'] = $ar_buf[9]; + $results[$ar_buf[0]]['tx_packets'] = $ar_buf[7]; + $results[$ar_buf[0]]['tx_errs'] = $ar_buf[8]; + $results[$ar_buf[0]]['tx_drop'] = $ar_buf[11]; + + $results[$ar_buf[0]]['errs'] = $ar_buf[5] + $ar_buf[8]; + $results[$ar_buf[0]]['drop'] = $ar_buf[11]; + } + } + } + return $results; + } + + function distroicon () { + $result = 'FreeBSD.png'; + return($result); + } + + function memory_additional($results) { + $pagesize = $this->grab_key("hw.pagesize"); + $results['ram']['cached'] = $this->grab_key("vm.stats.vm.v_cache_count") * $pagesize / 1024; + $results['ram']['cached_percent'] = round( $results['ram']['cached'] * 100 / $results['ram']['total']); + $results['ram']['app'] = $this->grab_key("vm.stats.vm.v_active_count") * $pagesize / 1024; + $results['ram']['app_percent'] = round( $results['ram']['app'] * 100 / $results['ram']['total']); + $results['ram']['buffers'] = $results['ram']['used'] - $results['ram']['app'] - $results['ram']['cached']; + $results['ram']['buffers_percent'] = round( $results['ram']['buffers'] * 100 / $results['ram']['total']); + return $results; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.HP-UX.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.HP-UX.inc.php new file mode 100644 index 00000000..4fae43dd --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.HP-UX.inc.php @@ -0,0 +1,421 @@ +chostname()); + } + return $result; + } + + function kernel () { + return execute_program('uname', '-srvm'); + } + + function uptime () { + $result = 0; + $ar_buf = array(); + + $buf = execute_program('uptime'); + if (preg_match("/up (\d+) days,\s*(\d+):(\d+),/", $buf, $ar_buf)) { + $min = $ar_buf[3]; + $hours = $ar_buf[2]; + $days = $ar_buf[1]; + $result = $days * 86400 + $hours * 3600 + $min * 60; + } + + return $result; + } + + function users () { + $who = split('=', execute_program('who', '-q')); + $result = $who[1]; + return $result; + } + + function loadavg ($bar = false) { + $ar_buf = array(); + + $buf = execute_program('uptime'); + + if (preg_match("/average: (.*), (.*), (.*)$/", $buf, $ar_buf)) { + $results['avg'] = array($ar_buf[1], $ar_buf[2], $ar_buf[3]); + } else { + $results['avg'] = array('N.A.', 'N.A.', 'N.A.'); + } + return $results; + } + + function cpu_info () { + $results = array(); + $ar_buf = array(); + + $bufr = rfts( '/proc/cpuinfo' ); + if( $bufr != "ERROR" ) { + $bufe = explode( "\n", $bufr ); + foreach( $bufe as $buf ) { + list($key, $value) = preg_split('/\s+:\s+/', trim($buf), 2); + // All of the tags here are highly architecture dependant. + // the only way I could reconstruct them for machines I don't + // have is to browse the kernel source. So if your arch isn't + // supported, tell me you want it written in. + switch ($key) { + case 'model name': + $results['model'] = $value; + break; + case 'cpu MHz': + $results['cpuspeed'] = sprintf('%.2f', $value); + break; + case 'cycle frequency [Hz]': // For Alpha arch - 2.2.x + $results['cpuspeed'] = sprintf('%.2f', $value / 1000000); + break; + case 'clock': // For PPC arch (damn borked POS) + $results['cpuspeed'] = sprintf('%.2f', $value); + break; + case 'cpu': // For PPC arch (damn borked POS) + $results['model'] = $value; + break; + case 'revision': // For PPC arch (damn borked POS) + $results['model'] .= ' ( rev: ' . $value . ')'; + break; + case 'cpu model': // For Alpha arch - 2.2.x + $results['model'] .= ' (' . $value . ')'; + break; + case 'cache size': + $results['cache'] = $value; + break; + case 'bogomips': + $results['bogomips'] += $value; + break; + case 'BogoMIPS': // For alpha arch - 2.2.x + $results['bogomips'] += $value; + break; + case 'BogoMips': // For sparc arch + $results['bogomips'] += $value; + break; + case 'cpus detected': // For Alpha arch - 2.2.x + $results['cpus'] += $value; + break; + case 'system type': // Alpha arch - 2.2.x + $results['model'] .= ', ' . $value . ' '; + break; + case 'platform string': // Alpha arch - 2.2.x + $results['model'] .= ' (' . $value . ')'; + break; + case 'processor': + $results['cpus'] += 1; + break; + } + } + fclose($fd); + } + + $keys = array_keys($results); + $keys2be = array('model', 'cpuspeed', 'cache', 'bogomips', 'cpus'); + + while ($ar_buf = each($keys2be)) { + if (! in_array($ar_buf[1], $keys)) { + $results[$ar_buf[1]] = 'N.A.'; + } + } + return $results; + } + + function pci () { + $results = array(); + + $bufr = rfts( '/proc/pci' ); + if( $bufr != "ERROR" ) { + $bufe = explode( "\n", $bufr ); + foreach( $bufe as $buf ) { + if (preg_match('/Bus/', $buf)) { + $device = true; + continue; + } + + if ($device) { + list($key, $value) = split(': ', $buf, 2); + + if (!preg_match('/bridge/i', $key) && !preg_match('/USB/i', $key)) { + $results[] = preg_replace('/\([^\)]+\)\.$/', '', trim($value)); + } + $device = false; + } + } + } + asort($results); + return $results; + } + + function ide () { + $results = array(); + + $bufd = gdc( '/proc/ide' ); + + foreach( $bufd as $file ) { + if (preg_match('/^hd/', $file)) { + $results[$file] = array(); + // Check if device is CD-ROM (CD-ROM capacity shows as 1024 GB) + $buf = rfts( "/proc/ide/" . $file . "/media", 1 ); + if( $buf != "ERROR" ) { + $results[$file]['media'] = trim( $buf ); + if ($results[$file]['media'] == 'disk') { + $results[$file]['media'] = 'Hard Disk'; + } + if ($results[$file]['media'] == 'cdrom') { + $results[$file]['media'] = 'CD-ROM'; + } + } + + $buf = rfts( "/proc/ide/" . $file . "/model", 1 ); + if( $buf != "ERROR" ) { + $results[$file]['model'] = trim( $buf ); + if (preg_match('/WDC/', $results[$file]['model'])) { + $results[$file]['manufacture'] = 'Western Digital'; + } elseif (preg_match('/IBM/', $results[$file]['model'])) { + $results[$file]['manufacture'] = 'IBM'; + } elseif (preg_match('/FUJITSU/', $results[$file]['model'])) { + $results[$file]['manufacture'] = 'Fujitsu'; + } else { + $results[$file]['manufacture'] = 'Unknown'; + } + } + + $buf = rfts( "/proc/ide/" . $file . "/capacity", 1 ); + if( $buf != "ERROR" ) { + $results[$file]['capacity'] = trim( $buf ); + if ($results[$file]['media'] == 'CD-ROM') { + unset($results[$file]['capacity']); + } + } + } + } + asort($results); + return $results; + } + + function scsi () { + $results = array(); + $dev_vendor = ''; + $dev_model = ''; + $dev_rev = ''; + $dev_type = ''; + $s = 1; + + $bufr = rfts( '/proc/scsi/scsi' ); + if( $bufr != "ERROR" ) { + $bufe = explode( "\n", $bufr ); + foreach( $bufe as $buf ) { + if (preg_match('/Vendor/', $buf)) { + preg_match('/Vendor: (.*) Model: (.*) Rev: (.*)/i', $buf, $dev); + list($key, $value) = split(': ', $buf, 2); + $dev_str = $value; + $get_type = 1; + continue; + } + + if ($get_type) { + preg_match('/Type:\s+(\S+)/i', $buf, $dev_type); + $results[$s]['model'] = "$dev[1] $dev[2] ($dev_type[1])"; + $results[$s]['media'] = "Hard Disk"; + $s++; + $get_type = 0; + } + } + } + asort($results); + return $results; + } + + function usb () { + $results = array(); + $devstring = 0; + $devnum = -1; + + $bufr = rfts( '/proc/bus/usb/devices' ); + if( $bufr != "ERROR" ) { + $bufe = explode( "\n", $bufr ); + foreach( $bufe as $buf ) { + if (preg_match('/^T/', $buf)) { + $devnum += 1; + } + if (preg_match('/^S/', $buf)) { + $devstring = 1; + } + + if ($devstring) { + list($key, $value) = split(': ', $buf, 2); + list($key, $value2) = split('=', $value, 2); + $results[$devnum] .= " " . trim($value2); + $devstring = 0; + } + } + } + return $results; + } + + function sbus () { + $results = array(); + $_results[0] = ""; + // TODO. Nothing here yet. Move along. + $results = $_results; + return $results; + } + + function network () { + $netstat = execute_program('netstat', '-ni | tail -n +2'); + $lines = split("\n", $netstat); + $results = array(); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i]); + if (!empty($ar_buf[0]) && !empty($ar_buf[3])) { + $results[$ar_buf[0]] = array(); + + $results[$ar_buf[0]]['rx_bytes'] = $ar_buf[4]; + $results[$ar_buf[0]]['rx_packets'] = $ar_buf[4]; + $results[$ar_buf[0]]['rx_errs'] = $ar_buf[5]; + $results[$ar_buf[0]]['rx_drop'] = $ar_buf[8]; + + $results[$ar_buf[0]]['tx_bytes'] = $ar_buf[6]; + $results[$ar_buf[0]]['tx_packets'] = $ar_buf[6]; + $results[$ar_buf[0]]['tx_errs'] = $ar_buf[7]; + $results[$ar_buf[0]]['tx_drop'] = $ar_buf[8]; + + $results[$ar_buf[0]]['errs'] = $ar_buf[5] + $ar_buf[7]; + $results[$ar_buf[0]]['drop'] = $ar_buf[8]; + } + } + return $results; + } + function memory () { + $results['ram'] = array(); + $results['swap'] = array(); + $results['devswap'] = array(); + + $bufr = rfts( '/proc/meminfo' ); + if( $bufr != "ERROR" ) { + $bufe = explode( "\n", $bufr ); + foreach( $bufe as $buf ) { + if (preg_match('/Mem:\s+(.*)$/', $buf, $ar_buf)) { + $ar_buf = preg_split('/\s+/', $ar_buf[1], 6); + + $results['ram']['total'] = $ar_buf[0] / 1024; + $results['ram']['used'] = $ar_buf[1] / 1024; + $results['ram']['free'] = $ar_buf[2] / 1024; + $results['ram']['shared'] = $ar_buf[3] / 1024; + $results['ram']['buffers'] = $ar_buf[4] / 1024; + $results['ram']['cached'] = $ar_buf[5] / 1024; + // I don't like this since buffers and cache really aren't + // 'used' per say, but I get too many emails about it. + $results['ram']['t_used'] = $results['ram']['used']; + $results['ram']['t_free'] = $results['ram']['total'] - $results['ram']['t_used']; + $results['ram']['percent'] = round(($results['ram']['t_used'] * 100) / $results['ram']['total']); + } + + if (preg_match('/Swap:\s+(.*)$/', $buf, $ar_buf)) { + $ar_buf = preg_split('/\s+/', $ar_buf[1], 3); + + $results['swap']['total'] = $ar_buf[0] / 1024; + $results['swap']['used'] = $ar_buf[1] / 1024; + $results['swap']['free'] = $ar_buf[2] / 1024; + $results['swap']['percent'] = round(($ar_buf[1] * 100) / $ar_buf[0]); + // Get info on individual swap files + $swaps = rfts( '/proc/swaps' ); + if( $swaps != "ERROR" ) { + $swapdevs = split("\n", $swaps); + + for ($i = 1, $max = (sizeof($swapdevs) - 1); $i < $max; $i++) { + $ar_buf = preg_split('/\s+/', $swapdevs[$i], 6); + $results['devswap'][$i - 1] = array(); + $results['devswap'][$i - 1]['dev'] = $ar_buf[0]; + $results['devswap'][$i - 1]['total'] = $ar_buf[2]; + $results['devswap'][$i - 1]['used'] = $ar_buf[3]; + $results['devswap'][$i - 1]['free'] = ($results['devswap'][$i - 1]['total'] - $results['devswap'][$i - 1]['used']); + $results['devswap'][$i - 1]['percent'] = round(($ar_buf[3] * 100) / $ar_buf[2]); + } + break; + } + } + } + } + return $results; + } + + function filesystems () { + $df = execute_program('df', '-kP'); + $mounts = split("\n", $df); + $fstype = array(); + + $s = execute_program('mount', '-v'); + $lines = explode("\n", $s); + + $i = 0; + while (list(, $line) = each($lines)) { + $a = split(' ', $line); + $fsdev[$a[0]] = $a[4]; + } + + for ($i = 1, $j = 0, $max = sizeof($mounts); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $mounts[$i], 6); + + if (hide_mount($ar_buf[5])) { + continue; + } + + $results[$j] = array(); + + $results[$j]['disk'] = $ar_buf[0]; + $results[$j]['size'] = $ar_buf[1]; + $results[$j]['used'] = $ar_buf[2]; + $results[$j]['free'] = $ar_buf[3]; + $results[$j]['percent'] = $ar_buf[4]; + $results[$j]['mount'] = $ar_buf[5]; + ($fstype[$ar_buf[5]]) ? $results[$j]['fstype'] = $fstype[$ar_buf[5]] : $results[$j]['fstype'] = $fsdev[$ar_buf[0]]; + $j++; + } + return $results; + } + + function distro () { + $result = 'HP-UX'; + return($result); + } + + function distroicon () { + $result = 'unknown.png'; + return($result); + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.Linux.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.Linux.inc.php new file mode 100644 index 00000000..8abc31fa --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.Linux.inc.php @@ -0,0 +1,528 @@ +parser = new Parser(); + $this->parser->df_param = 'P'; + + $list = @parse_ini_file(APP_ROOT . "/" . $this->inifile, true); + if (!$list) { + return; + } + foreach ($list as $section => $distribution) { + if (!isset($distribution["Files"])) { + continue; + } else { + foreach (explode(";", $distribution["Files"]) as $filename) { + if (file_exists($filename)) { + $buf = rfts( $filename ); + $this->icon = isset($distribution["Image"]) ? $distribution["Image"] : $this->icon; + $this->distro = isset($distribution["Name"]) ? $distribution["Name"] . " " . trim($buf) : trim($buf); + break 2; + } + } + } + } + } + + // get our apache SERVER_NAME or vhost + function vhostname () { + if (! ($result = getenv('SERVER_NAME'))) { + $result = 'N.A.'; + } + return $result; + } + // get our canonical hostname + function chostname () { + $result = rfts( '/proc/sys/kernel/hostname', 1 ); + if ( $result == "ERROR" ) { + $result = "N.A."; + } else { + $result = gethostbyaddr( gethostbyname( trim( $result ) ) ); + } + return $result; + } + // get the IP address of our canonical hostname + function ip_addr () { + if (!($result = getenv('SERVER_ADDR'))) { + $result = gethostbyname($this->chostname()); + } + return $result; + } + + function kernel () { + $buf = rfts( '/proc/version', 1 ); + if ( $buf == "ERROR" ) { + $result = "N.A."; + } else { + if (preg_match('/version (.*?) /', $buf, $ar_buf)) { + $result = $ar_buf[1]; + + if (preg_match('/SMP/', $buf)) { + $result .= ' (SMP)'; + } + } + } + return $result; + } + + function uptime () { + $buf = rfts( '/proc/uptime', 1 ); + $ar_buf = split( ' ', $buf ); + $result = trim( $ar_buf[0] ); + + return $result; + } + + function users () { + $who = split('=', execute_program('who', '-q')); + $result = $who[1]; + return $result; + } + + function loadavg ($bar = false) { + $buf = rfts( '/proc/loadavg' ); + if( $buf == "ERROR" ) { + $results['avg'] = array('N.A.', 'N.A.', 'N.A.'); + } else { + $results['avg'] = preg_split("/\s/", $buf, 4); + unset($results['avg'][3]); // don't need the extra values, only first three + } + if ($bar) { + $buf = rfts( '/proc/stat', 1 ); + if( $buf != "ERROR" ) { + sscanf($buf, "%*s %Ld %Ld %Ld %Ld", $ab, $ac, $ad, $ae); + // Find out the CPU load + // user + sys = load + // total = total + $load = $ab + $ac + $ad; // cpu.user + cpu.sys + $total = $ab + $ac + $ad + $ae; // cpu.total + + // we need a second value, wait 1 second befor getting (< 1 second no good value will occour) + sleep(1); + $buf = rfts( '/proc/stat', 1 ); + sscanf($buf, "%*s %Ld %Ld %Ld %Ld", $ab, $ac, $ad, $ae); + $load2 = $ab + $ac + $ad; + $total2 = $ab + $ac + $ad + $ae; + $results['cpupercent'] = (100*($load2 - $load)) / ($total2 - $total); + } + } + return $results; + } + + function cpu_info () { + $bufr = rfts( '/proc/cpuinfo' ); + + if ( $bufr != "ERROR" ) { + $bufe = explode("\n", $bufr); + + $results = array('cpus' => 0, 'bogomips' => 0); + $ar_buf = array(); + + foreach( $bufe as $buf ) { + if(trim($buf) != "") { + list($key, $value) = preg_split('/\s+:\s+/', trim($buf), 2); + // All of the tags here are highly architecture dependant. + // the only way I could reconstruct them for machines I don't + // have is to browse the kernel source. So if your arch isn't + // supported, tell me you want it written in. + switch ($key) { + case 'model name': + $results['model'] = $value; + break; + case 'cpu MHz': + $results['cpuspeed'] = sprintf('%.2f', $value); + break; + case 'cycle frequency [Hz]': // For Alpha arch - 2.2.x + $results['cpuspeed'] = sprintf('%.2f', $value / 1000000); + break; + case 'clock': // For PPC arch (damn borked POS) + $results['cpuspeed'] = sprintf('%.2f', $value); + break; + case 'cpu': // For PPC arch (damn borked POS) + $results['model'] = $value; + break; + case 'L2 cache': // More for PPC + $results['cache'] = $value; + break; + case 'revision': // For PPC arch (damn borked POS) + $results['model'] .= ' ( rev: ' . $value . ')'; + break; + case 'cpu model': // For Alpha arch - 2.2.x + $results['model'] .= ' (' . $value . ')'; + break; + case 'cache size': + $results['cache'] = $value; + break; + case 'bogomips': + $results['bogomips'] += $value; + break; + case 'BogoMIPS': // For alpha arch - 2.2.x + $results['bogomips'] += $value; + break; + case 'BogoMips': // For sparc arch + $results['bogomips'] += $value; + break; + case 'cpus detected': // For Alpha arch - 2.2.x + $results['cpus'] += $value; + break; + case 'system type': // Alpha arch - 2.2.x + $results['model'] .= ', ' . $value . ' '; + break; + case 'platform string': // Alpha arch - 2.2.x + $results['model'] .= ' (' . $value . ')'; + break; + case 'processor': + $results['cpus'] += 1; + break; + case 'Cpu0ClkTck': // Linux sparc64 + $results['cpuspeed'] = sprintf('%.2f', hexdec($value) / 1000000); + break; + case 'Cpu0Bogo': // Linux sparc64 & sparc32 + $results['bogomips'] = $value; + break; + case 'ncpus probed': // Linux sparc64 & sparc32 + $results['cpus'] = $value; + break; + } + } + } + } + + // sparc64 specific code follows + // This adds the ability to display the cache that a CPU has + // Originally made by Sven Blumenstein in 2004 + // Modified by Tom Weustink in 2004 + $sparclist = array('SUNW,UltraSPARC@0,0', 'SUNW,UltraSPARC-II@0,0', 'SUNW,UltraSPARC@1c,0', 'SUNW,UltraSPARC-IIi@1c,0', 'SUNW,UltraSPARC-II@1c,0'); + foreach ($sparclist as $name) { + $buf = rfts( '/proc/openprom/' . $name . '/ecache-size',1 , 32, false ); + if( $buf != "ERROR" ) { + $results['cache'] = base_convert($buf, 16, 10)/1024 . ' KB'; + } + } + // sparc64 specific code ends + + // XScale detection code + if ( $results['cpus'] == 0 ) { + foreach( $bufe as $buf ) { + if($buf != "\n") { + list($key, $value) = preg_split('/\s+:\s+/', trim($buf), 2); + switch($key) { + case 'Processor': + $results['cpus'] += 1; + $results['model'] = $value; + break; + case 'BogoMIPS': //BogoMIPS are not BogoMIPS on this CPU, it's the speed, no BogoMIPS available + $results['cpuspeed'] = $value; + break; + case 'I size': + $results['cache'] = $value; + break; + case 'D size': + $results['cache'] += $value; + break; + } + } + } + $results['cache'] = $results['cache'] / 1024 . " KB"; + } + + $keys = array_keys($results); + $keys2be = array('model', 'cpuspeed', 'cache', 'bogomips', 'cpus'); + + while ($ar_buf = each($keys2be)) { + if (! in_array($ar_buf[1], $keys)) { + $results[$ar_buf[1]] = 'N.A.'; + } + } + return $results; + } + + function pci () { + $results = array(); + + if( !$results = $this->parser->parse_lspci() ) { + $bufr = rfts( '/proc/pci' ); + + //Pinaki : Fix for ticket #4462 and #5147 + if(!is_null($bufr) && is_array($bufr)) { + + foreach( $bufr as $buf ) { + if (preg_match('/Bus/', $buf)) { + $device = true; + continue; + } + + if ($device) { + list($key, $value) = split(': ', $buf, 2); + + if (!preg_match('/bridge/i', $key) && !preg_match('/USB/i', $key)) { + $results[] = preg_replace('/\([^\)]+\)\.$/', '', trim($value)); + } + $device = false; + } + } + asort($results); + } + } + return $results; + } + + function ide () { + $results = array(); + $bufd = gdc( '/proc/ide' ); + //Pinaki: Fix for ticket #4462 + if(!is_null($bufd)){ + foreach( $bufd as $file ) { + if (preg_match('/^hd/', $file)) { + $results[$file] = array(); + $buf = rfts("/proc/ide/" . $file . "/media", 1 ); + if ( $buf != "ERROR" ) { + $results[$file]['media'] = trim($buf); + if ($results[$file]['media'] == 'disk') { + $results[$file]['media'] = 'Hard Disk'; + $buf = rfts( "/proc/ide/" . $file . "/capacity", 1, 4096, false); + if( $buf == "ERROR" ) { + $buf = rfts( "/sys/block/" . $file . "/size", 1, 4096, false); + } + if ( $buf != "ERROR" ) { + $results[$file]['capacity'] = trim( $buf ); + } + } elseif ($results[$file]['media'] == 'cdrom') { + $results[$file]['media'] = 'CD-ROM'; + unset($results[$file]['capacity']); + } + } + + $buf = rfts( "/proc/ide/" . $file . "/model", 1 ); + if ( $buf != "ERROR" ) { + $results[$file]['model'] = trim( $buf ); + if (preg_match('/WDC/', $results[$file]['model'])) { + $results[$file]['manufacture'] = 'Western Digital'; + } elseif (preg_match('/IBM/', $results[$file]['model'])) { + $results[$file]['manufacture'] = 'IBM'; + } elseif (preg_match('/FUJITSU/', $results[$file]['model'])) { + $results[$file]['manufacture'] = 'Fujitsu'; + } else { + $results[$file]['manufacture'] = 'Unknown'; + } + } + + } + } + + asort($results); + } + return $results; + } + + function scsi () { + $results = array(); + $dev_vendor = ''; + $dev_model = ''; + $dev_rev = ''; + $dev_type = ''; + $s = 1; + $get_type = 0; + + $bufr = execute_program('lsscsi', '-c', false); + if( is_null( $bufr )) { + $bufr = rfts( '/proc/scsi/scsi', 0, 4096, false ); + } + if ( $bufr != "ERROR" ) { + $bufe = explode("\n", $bufr); + foreach( $bufe as $buf ) { + if (preg_match('/Vendor/', $buf)) { + preg_match('/Vendor: (.*) Model: (.*) Rev: (.*)/i', $buf, $dev); + list($key, $value) = split(': ', $buf, 2); + $dev_str = $value; + $get_type = true; + continue; + } + + if ($get_type) { + preg_match('/Type:\s+(\S+)/i', $buf, $dev_type); + $results[$s]['model'] = "$dev[1] $dev[2] ($dev_type[1])"; + $results[$s]['media'] = "Hard Disk"; + $s++; + $get_type = false; + } + } + } + asort($results); + return $results; + } + + function usb () { + $results = array(); + $devnum = -1; + + $bufr = execute_program('lsusb', '', false); + if( is_null( $bufr )) { + $bufr = rfts( '/proc/bus/usb/devices' ); + if ( $bufr != "ERROR" ) { + $bufe = explode("\n", $bufr); + foreach( $bufe as $buf ) { + if (preg_match('/^T/', $buf)) { + $devnum += 1; + $results[$devnum] = ""; + } elseif (preg_match('/^S:/', $buf)) { + list($key, $value) = split(': ', $buf, 2); + list($key, $value2) = split('=', $value, 2); + if (trim($key) != "SerialNumber") { + $results[$devnum] .= " " . trim($value2); + $devstring = 0; + } + } + } + } + } else { + $bufe = explode( "\n", $bufr ); + foreach( $bufe as $buf ) { + $device = preg_split("/ /", $buf, 7); + if( isset( $device[6] ) && trim( $device[6] ) != "" ) { + $results[$devnum++] = trim( $device[6] ); + } + } + } + return $results; + } + + function sbus () { + $results = array(); + $_results[0] = ""; + // TODO. Nothing here yet. Move along. + $results = $_results; + return $results; + } + + function network () { + $results = array(); + + $bufr = rfts( '/proc/net/dev' ); + //Pinaki: Fix for ticket #4462 + if ( !is_null($bufr) && $bufr != "ERROR") { + $bufe = explode("\n", $bufr); + foreach( $bufe as $buf ) { + if (preg_match('/:/', $buf)) { + list($dev_name, $stats_list) = preg_split('/:/', $buf, 2); + $stats = preg_split('/\s+/', trim($stats_list)); + $results[$dev_name] = array(); + + $results[$dev_name]['rx_bytes'] = $stats[0]; + $results[$dev_name]['rx_packets'] = $stats[1]; + $results[$dev_name]['rx_errs'] = $stats[2]; + $results[$dev_name]['rx_drop'] = $stats[3]; + + $results[$dev_name]['tx_bytes'] = $stats[8]; + $results[$dev_name]['tx_packets'] = $stats[9]; + $results[$dev_name]['tx_errs'] = $stats[10]; + $results[$dev_name]['tx_drop'] = $stats[11]; + + $results[$dev_name]['errs'] = $stats[2] + $stats[10]; + $results[$dev_name]['drop'] = $stats[3] + $stats[11]; + } + } + } + return $results; + } + + function memory () { + $results['ram'] = array(); + $results['swap'] = array(); + $results['devswap'] = array(); + + $bufr = rfts( '/proc/meminfo' ); + if ( $bufr != "ERROR" ) { + $bufe = explode("\n", $bufr); + foreach( $bufe as $buf ) { + if (preg_match('/^MemTotal:\s+(.*)\s*kB/i', $buf, $ar_buf)) { + $results['ram']['total'] = $ar_buf[1]; + } else if (preg_match('/^MemFree:\s+(.*)\s*kB/i', $buf, $ar_buf)) { + $results['ram']['t_free'] = $ar_buf[1]; + } else if (preg_match('/^Cached:\s+(.*)\s*kB/i', $buf, $ar_buf)) { + $results['ram']['cached'] = $ar_buf[1]; + } else if (preg_match('/^Buffers:\s+(.*)\s*kB/i', $buf, $ar_buf)) { + $results['ram']['buffers'] = $ar_buf[1]; + } else if (preg_match('/^SwapTotal:\s+(.*)\s*kB/i', $buf, $ar_buf)) { + $results['swap']['total'] = $ar_buf[1]; + } else if (preg_match('/^SwapFree:\s+(.*)\s*kB/i', $buf, $ar_buf)) { + $results['swap']['free'] = $ar_buf[1]; + } + } + + $results['ram']['t_used'] = $results['ram']['total'] - $results['ram']['t_free']; + $results['ram']['percent'] = round(($results['ram']['t_used'] * 100) / $results['ram']['total']); + $results['swap']['used'] = $results['swap']['total'] - $results['swap']['free']; + $results['swap']['percent'] = round(($results['swap']['used'] * 100) / $results['swap']['total']); + + // values for splitting memory usage + if (isset($results['ram']['cached']) && isset($results['ram']['buffers'])) { + $results['ram']['app'] = $results['ram']['t_used'] - $results['ram']['cached'] - $results['ram']['buffers']; + $results['ram']['app_percent'] = round(($results['ram']['app'] * 100) / $results['ram']['total']); + $results['ram']['buffers_percent'] = round(($results['ram']['buffers'] * 100) / $results['ram']['total']); + $results['ram']['cached_percent'] = round(($results['ram']['cached'] * 100) / $results['ram']['total']); + } + + $bufr = rfts( '/proc/swaps' ); + //Pinaki: Fix for ticket #4462 + if ( !is_null($bufr) && $bufr != "ERROR") { + $swaps = explode("\n", $bufr); + for ($i = 1; $i < (sizeof($swaps)); $i++) { + if( trim( $swaps[$i] ) != "" ) { + $ar_buf = preg_split('/\s+/', $swaps[$i], 6); + $results['devswap'][$i - 1] = array(); + $results['devswap'][$i - 1]['dev'] = $ar_buf[0]; + $results['devswap'][$i - 1]['total'] = $ar_buf[2]; + $results['devswap'][$i - 1]['used'] = $ar_buf[3]; + $results['devswap'][$i - 1]['free'] = ($results['devswap'][$i - 1]['total'] - $results['devswap'][$i - 1]['used']); + $results['devswap'][$i - 1]['percent'] = round(($ar_buf[3] * 100) / $ar_buf[2]); + } + } + } + } + return $results; + } + + function filesystems () { + return $this->parser->parse_filesystems(); + } + + function distro () { + return $this->distro; + } + + function distroicon () { + return $this->icon; + } + +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.NetBSD.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.NetBSD.inc.php new file mode 100644 index 00000000..288ad9e1 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.NetBSD.inc.php @@ -0,0 +1,111 @@ +bsd_common(); + + $this->cpu_regexp = "^cpu(.*)\, (.*) MHz"; + $this->scsi_regexp1 = "^(.*) at scsibus.*: <(.*)> .*"; + $this->scsi_regexp2 = "^(da[0-9]): (.*)MB "; + $this->cpu_regexp2 = "/user = (.*), nice = (.*), sys = (.*), intr = (.*), idle = (.*)/"; + $this->pci_regexp1 = '/(.*) at pci[0-9] dev [0-9]* function [0-9]*: (.*)$/'; + $this->pci_regexp2 = '/"(.*)" (.*).* at [.0-9]+ irq/'; + } + + function get_sys_ticks () { + $a = $this->grab_key('kern.boottime'); + $sys_ticks = time() - $a; + return $sys_ticks; + } + + function network () { + $netstat_b = execute_program('netstat', '-nbdi | cut -c1-25,44- | grep "^[a-z]*[0-9][ \t].*Link"'); + $netstat_n = execute_program('netstat', '-ndi | cut -c1-25,44- | grep "^[a-z]*[0-9][ \t].*Link"'); + $lines_b = split("\n", $netstat_b); + $lines_n = split("\n", $netstat_n); + $results = array(); + for ($i = 0, $max = sizeof($lines_b); $i < $max; $i++) { + $ar_buf_b = preg_split("/\s+/", $lines_b[$i]); + $ar_buf_n = preg_split("/\s+/", $lines_n[$i]); + if (!empty($ar_buf_b[0]) && !empty($ar_buf_n[3])) { + $results[$ar_buf_b[0]] = array(); + + $results[$ar_buf_b[0]]['rx_bytes'] = $ar_buf_b[3]; + $results[$ar_buf_b[0]]['rx_packets'] = $ar_buf_n[3]; + $results[$ar_buf_b[0]]['rx_errs'] = $ar_buf_n[4]; + $results[$ar_buf_b[0]]['rx_drop'] = $ar_buf_n[8]; + + $results[$ar_buf_b[0]]['tx_bytes'] = $ar_buf_b[4]; + $results[$ar_buf_b[0]]['tx_packets'] = $ar_buf_n[5]; + $results[$ar_buf_b[0]]['tx_errs'] = $ar_buf_n[6]; + $results[$ar_buf_b[0]]['tx_drop'] = $ar_buf_n[8]; + + $results[$ar_buf_b[0]]['errs'] = $ar_buf_n[4] + $ar_buf_n[6]; + $results[$ar_buf_b[0]]['drop'] = $ar_buf_n[8]; + } + } + return $results; + } + + // get the ide device information out of dmesg + function ide () { + $results = array(); + + $s = 0; + for ($i = 0, $max = count($this->read_dmesg()); $i < $max; $i++) { + $buf = $this->dmesg[$i]; + if (preg_match('/^(.*) at (pciide|wdc|atabus|atapibus)[0-9] (.*): <(.*)>/', $buf, $ar_buf)) { + $s = $ar_buf[1]; + $results[$s]['model'] = $ar_buf[4]; + $results[$s]['media'] = 'Hard Disk'; + // now loop again and find the capacity + for ($j = 0, $max1 = count($this->read_dmesg()); $j < $max1; $j++) { + $buf_n = $this->dmesg[$j]; + if (preg_match("/^($s): (.*), (.*), (.*)MB, .*$/", $buf_n, $ar_buf_n)) { + $results[$s]['capacity'] = $ar_buf_n[4] * 2048 * 1.049; + } elseif (preg_match("/^($s): (.*) MB, (.*), (.*), .*$/", $buf_n, $ar_buf_n)) { + $results[$s]['capacity'] = $ar_buf_n[2] * 2048; + } + } + } + } + asort($results); + return $results; + } + + function distroicon () { + $result = 'NetBSD.png'; + return($result); + } + +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.OpenBSD.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.OpenBSD.inc.php new file mode 100644 index 00000000..c572bb6c --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.OpenBSD.inc.php @@ -0,0 +1,110 @@ +bsd_common(); + $this->cpu_regexp = "^cpu(.*) (.*) MHz"; + $this->scsi_regexp1 = "^(.*) at scsibus.*: <(.*)> .*"; + $this->scsi_regexp2 = "^(da[0-9]): (.*)MB "; + $this->cpu_regexp2 = "/(.*),(.*),(.*),(.*),(.*)/"; + $this->pci_regexp1 = '/(.*) at pci[0-9] .* "(.*)"/'; + $this->pci_regexp2 = '/"(.*)" (.*).* at [.0-9]+ irq/'; + } + + function get_sys_ticks () { + $a = $this->grab_key('kern.boottime'); + $sys_ticks = time() - $a; + return $sys_ticks; + } + + function network () { + $netstat_b = execute_program('netstat', '-nbdi | cut -c1-25,44- | grep Link | grep -v \'* \''); + $netstat_n = execute_program('netstat', '-ndi | cut -c1-25,44- | grep Link | grep -v \'* \''); + $lines_b = split("\n", $netstat_b); + $lines_n = split("\n", $netstat_n); + $results = array(); + for ($i = 0, $max = sizeof($lines_b); $i < $max; $i++) { + $ar_buf_b = preg_split("/\s+/", $lines_b[$i]); + $ar_buf_n = preg_split("/\s+/", $lines_n[$i]); + if (!empty($ar_buf_b[0]) && !empty($ar_buf_n[3])) { + $results[$ar_buf_b[0]] = array(); + + $results[$ar_buf_b[0]]['rx_bytes'] = $ar_buf_b[3]; + $results[$ar_buf_b[0]]['rx_packets'] = $ar_buf_n[3]; + $results[$ar_buf_b[0]]['rx_errs'] = $ar_buf_n[4]; + $results[$ar_buf_b[0]]['rx_drop'] = $ar_buf_n[8]; + + $results[$ar_buf_b[0]]['tx_bytes'] = $ar_buf_b[4]; + $results[$ar_buf_b[0]]['tx_packets'] = $ar_buf_n[5]; + $results[$ar_buf_b[0]]['tx_errs'] = $ar_buf_n[6]; + $results[$ar_buf_b[0]]['tx_drop'] = $ar_buf_n[8]; + + $results[$ar_buf_b[0]]['errs'] = $ar_buf_n[4] + $ar_buf_n[6]; + $results[$ar_buf_b[0]]['drop'] = $ar_buf_n[8]; + } + } + return $results; + } + // get the ide device information out of dmesg + function ide () { + $results = array(); + + $s = 0; + for ($i = 0, $max = count($this->read_dmesg()); $i < $max; $i++) { + $buf = $this->dmesg[$i]; + if (preg_match('/^(.*) at pciide[0-9] (.*): <(.*)>/', $buf, $ar_buf)) { + $s = $ar_buf[1]; + $results[$s]['model'] = $ar_buf[3]; + $results[$s]['media'] = 'Hard Disk'; + // now loop again and find the capacity + for ($j = 0, $max1 = count($this->read_dmesg()); $j < $max1; $j++) { + $buf_n = $this->dmesg[$j]; + if (preg_match("/^($s): (.*), (.*), (.*)MB, .*$/", $buf_n, $ar_buf_n)) { + $results[$s]['capacity'] = $ar_buf_n[4] * 2048 * 1.049;; + } + } + } + } + asort($results); + return $results; + } + + function distroicon () { + $result = 'OpenBSD.png'; + return($result); + } + +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.SunOS.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.SunOS.inc.php new file mode 100644 index 00000000..6e0b3746 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.SunOS.inc.php @@ -0,0 +1,238 @@ +addError("WARN", "The SunOS version of phpSysInfo is work in progress, some things currently don't work"); + +class sysinfo { + // Extract kernel values via kstat() interface + function kstat ($key) { + $m = execute_program('kstat', "-p d $key"); + list($key, $value) = split("\t", trim($m), 2); + return $value; + } + + function vhostname () { + if (! ($result = getenv('SERVER_NAME'))) { + $result = 'N.A.'; + } + return $result; + } + // get our canonical hostname + function chostname () { + if ($result = execute_program('uname', '-n')) { + $result = gethostbyaddr(gethostbyname($result)); + } else { + $result = 'N.A.'; + } + return $result; + } + // get the IP address of our canonical hostname + function ip_addr () { + if (!($result = getenv('SERVER_ADDR'))) { + $result = gethostbyname($this->chostname()); + } + return $result; + } + + function kernel () { + $os = execute_program('uname', '-s'); + $version = execute_program('uname', '-r'); + return $os . ' ' . $version; + } + + function uptime () { + $result = time() - $this->kstat('unix:0:system_misc:boot_time'); + + return $result; + } + + function users () { + $who = split('=', execute_program('who', '-q')); + $result = $who[1]; + return $result; + } + + function loadavg ($bar = false) { + $load1 = $this->kstat('unix:0:system_misc:avenrun_1min'); + $load5 = $this->kstat('unix:0:system_misc:avenrun_5min'); + $load15 = $this->kstat('unix:0:system_misc:avenrun_15min'); + $results['avg'] = array( round($load1/256, 2), round($load5/256, 2), round($load15/256, 2) ); + return $results; + } + + function cpu_info () { + $results = array(); + $ar_buf = array(); + + $results['model'] = execute_program('uname', '-i'); + $results['cpuspeed'] = $this->kstat('cpu_info:0:cpu_info0:clock_MHz'); + $results['cache'] = $this->kstat('cpu_info:0:cpu_info0:cpu_type'); + $results['cpus'] = $this->kstat('unix:0:system_misc:ncpus'); + + return $results; + } + + function pci () { + // FIXME + $results = array(); + return $results; + } + + function ide () { + // FIXME + $results = array(); + return $results; + } + + function scsi () { + // FIXME + $results = array(); + return $results; + } + + function usb () { + // FIXME + $results = array(); + return $results; + } + + function sbus () { + $results = array(); + $_results[0] = ""; + // TODO. Nothing here yet. Move along. + $results = $_results; + return $results; + } + + function network () { + $results = array(); + + $netstat = execute_program('netstat', '-ni | awk \'(NF ==10){print;}\''); + $lines = split("\n", $netstat); + $results = array(); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + $ar_buf = preg_split("/\s+/", $lines[$i]); + if ((!empty($ar_buf[0])) && ($ar_buf[0] != 'Name')) { + $results[$ar_buf[0]] = array(); + + $results[$ar_buf[0]]['rx_bytes'] = 0; + $results[$ar_buf[0]]['rx_packets'] = $ar_buf[4]; + $results[$ar_buf[0]]['rx_errs'] = $ar_buf[5]; + $results[$ar_buf[0]]['rx_drop'] = 0; + + $results[$ar_buf[0]]['tx_bytes'] = 0; + $results[$ar_buf[0]]['tx_packets'] = $ar_buf[6]; + $results[$ar_buf[0]]['tx_errs'] = $ar_buf[7]; + $results[$ar_buf[0]]['tx_drop'] = 0; + + $results[$ar_buf[0]]['errs'] = $ar_buf[5] + $ar_buf[ + 7]; + $results[$ar_buf[0]]['drop'] = 0; + + preg_match('/^(\D+)(\d+)$/', $ar_buf[0], $intf); + $prefix = $intf[1] . ':' . $intf[2] . ':' . $intf[1] . $intf[2] . ':'; + $cnt = $this->kstat($prefix . 'drop'); + + if ($cnt > 0) { + $results[$ar_buf[0]]['rx_drop'] = $cnt; + } + $cnt = $this->kstat($prefix . 'obytes64'); + + if ($cnt > 0) { + $results[$ar_buf[0]]['tx_bytes'] = $cnt; + } + $cnt = $this->kstat($prefix . 'rbytes64'); + + if ($cnt > 0) { + $results[$ar_buf[0]]['rx_bytes'] = $cnt; + } + } + } + return $results; + } + + function memory () { + $results['devswap'] = array(); + + $results['ram'] = array(); + + $pagesize = $this->kstat('unix:0:seg_cache:slab_size'); + $results['ram']['total'] = $this->kstat('unix:0:system_pages:pagestotal') * $pagesize / 1024; + $results['ram']['used'] = $this->kstat('unix:0:system_pages:pageslocked') * $pagesize / 1024; + $results['ram']['free'] = $this->kstat('unix:0:system_pages:pagesfree') * $pagesize / 1024; + $results['ram']['shared'] = 0; + $results['ram']['buffers'] = 0; + $results['ram']['cached'] = 0; + + $results['ram']['t_used'] = $results['ram']['used'] - $results['ram']['cached'] - $results['ram']['buffers']; + $results['ram']['t_free'] = $results['ram']['total'] - $results['ram']['t_used']; + $results['ram']['percent'] = round(($results['ram']['used'] * 100) / $results['ram']['total']); + + $results['swap'] = array(); + $results['swap']['total'] = $this->kstat('unix:0:vminfo:swap_avail') / 1024 / 1024; + $results['swap']['used'] = $this->kstat('unix:0:vminfo:swap_alloc') / 1024 / 1024; + $results['swap']['free'] = $this->kstat('unix:0:vminfo:swap_free') / 1024 / 1024; + $results['swap']['percent'] = round(($ar_buf[1] * 100) / $ar_buf[0]); + $results['swap']['percent'] = round(($results['swap']['used'] * 100) / $results['swap']['total']); + return $results; + } + + function filesystems () { + $df = execute_program('df', '-k'); + $mounts = split("\n", $df); + + $dftypes = execute_program('df', '-n'); + $mounttypes = split("\n", $dftypes); + + for ($i = 1, $j = 0, $max = sizeof($mounts); $i < $max; $i++) { + $ar_buf = preg_split('/\s+/', $mounts[$i], 6); + $ty_buf = split(':', $mounttypes[$i-1], 2); + + if (hide_mount($ar_buf[5])) { + continue; + } + + $results[$j] = array(); + + $results[$j]['disk'] = $ar_buf[0]; + $results[$j]['size'] = $ar_buf[1]; + $results[$j]['used'] = $ar_buf[2]; + $results[$j]['free'] = $ar_buf[3]; + $results[$j]['percent'] = round(($results[$j]['used'] * 100) / $results[$j]['size']); + $results[$j]['mount'] = $ar_buf[5]; + $results[$j]['fstype'] = $ty_buf[1]; + $j++; + } + return $results; + } + + function distro () { + $result = 'SunOS'; + return($result); + } + + function distroicon () { + $result = 'SunOS.png'; + return($result); + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.WINNT.inc.bak.php b/oss/vtiger/trunk/modules/System/includes/os/class.WINNT.inc.bak.php new file mode 100644 index 00000000..91906a4f --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.WINNT.inc.bak.php @@ -0,0 +1,295 @@ +wmi = new COM("WinMgmts:\\\\."); + } + // get our apache SERVER_NAME or vhost + function vhostname () + { + if (! ($result = getenv('SERVER_NAME'))) { + $result = 'N.A.'; + } + return $result; + } + // get our canonical hostname + function chostname () + { + if (! ($result = getenv('SERVER_NAME'))) { + $result = 'N.A.'; + } + return $result; + } + // get the IP address of our canonical hostname + function ip_addr () + { + if (!($result = getenv('SERVER_ADDR'))) { + $result = 'N.A.'; + } + return $result; + } + + function kernel () + { + $objInstance = $this->wmi->InstancesOf("Win32_OperatingSystem"); + foreach ($objInstance as $obj) { + $result = $obj->Version; + if ($obj->ServicePackMajorVersion > 0) { + $result .= ' SP' . $obj->ServicePackMajorVersion; + } + } + return $result; + } + + function uptime () + { + $objInstance = $this->wmi->InstancesOf("Win32_OperatingSystem"); + foreach ($objInstance as $obj) { + $result = 0; + + $year = intval(substr($obj->LastBootUpTime, 0, 4)); + $month = intval(substr($obj->LastBootUpTime, 4, 2)); + $day = intval(substr($obj->LastBootUpTime, 6, 2)); + $hour = intval(substr($obj->LastBootUpTime, 8, 2)); + $minute = intval(substr($obj->LastBootUpTime, 10, 2)); + $seconds = intval(substr($obj->LastBootUpTime, 12, 2)); + + $boottime = mktime($hour, $minute, $seconds, $month, $day, $year); + + $diff_seconds = mktime() - $boottime; + + $result = $diff_seconds; + } + return $result; + } + + function users () + { + $objInstance = $this->wmi->InstancesOf("Win32_PerfRawData_TermService_TerminalServices"); + foreach ($objInstance as $obj) { + return $obj->TotalSessions; + } + } + + function loadavg () + { + $objInstance = $this->wmi->InstancesOf("Win32_Processor"); + + $cpuload = array(); + foreach ($objInstance as $obj) { + $cpuload[] = $obj->LoadPercentage; + } + // while + return $cpuload; + } + + function cpu_info () + { + $objInstance = $this->wmi->InstancesOf("Win32_Processor"); + + foreach ($objInstance as $obj) { + // still need bogomips (wtf are bogomips?) + $results['cpus'] = getenv('NUMBER_OF_PROCESSORS'); + $results['model'] = $obj->Name; + $results['cache'] = $obj->L2CacheSize; + $results['mhz'] = $obj->CurrentClockSpeed . "/" . $obj->ExtClock; + } + return $results; + } + + function pci () + { + $objInstance = $this->wmi->InstancesOf("Win32_PnPEntity"); + + $pci = array(); + foreach ($objInstance as $obj) { + if (substr($obj->PNPDeviceID, 0, 4) == "PCI\\") { + $pci[] = $obj->Name; + } + } // while + return $pci; + } + + function ide () + { + $objInstance = $this->wmi->InstancesOf("Win32_PnPEntity"); + + $ide = array(); + foreach ($objInstance as $obj) { + if (substr($obj->PNPDeviceID, 0, 4) == "IDE\\") { + $ide[]['model'] = $obj->Name; + } + } // while + return $ide; + } + + function scsi () + { + $objInstance = $this->wmi->InstancesOf("Win32_PnPEntity"); + + $scsi = array(); + foreach ($objInstance as $obj) { + if (substr($obj->PNPDeviceID, 0, 5) == "SCSI\\") { + $scsi[] = $obj->Name; + } + } // while + return $scsi; + } + + function usb () + { + $objInstance = $this->wmi->InstancesOf("Win32_PnPEntity"); + + $usb = array(); + foreach ($objInstance as $obj) { + if (substr($obj->PNPDeviceID, 0, 4) == "USB\\") { + $usb[] = $obj->Name; + } + } // while + return $usb; + } + + function sbus () + { + $objInstance = $this->wmi->InstancesOf("Win32_PnPEntity"); + + $sbus = array(); + foreach ($objInstance as $obj) { + if (substr($obj->PNPDeviceID, 0, 5) == "SBUS\\") { + $sbus[] = $obj->Name; + } + } // while + return $sbus; + } + + function network () + { + /** + * need this for documentation in case i find some better net stats + * $results[$dev_name]['rx_bytes'] = $stats[0]; + * $results[$dev_name]['rx_packets'] = $stats[1]; + * $results[$dev_name]['rx_errs'] = $stats[2]; + * $results[$dev_name]['rx_drop'] = $stats[3]; + * + * $results[$dev_name]['tx_bytes'] = $stats[8]; + * $results[$dev_name]['tx_packets'] = $stats[9]; + * $results[$dev_name]['tx_errs'] = $stats[10]; + * $results[$dev_name]['tx_drop'] = $stats[11]; + * + * $results[$dev_name]['errs'] = $stats[2] + $stats[10]; + * $results[$dev_name]['drop'] = $stats[3] + $stats[11]; + */ + + $objInstance = $this->wmi->InstancesOf("Win32_PerfRawData_Tcpip_NetworkInterface"); + + $results = array(); + foreach ($objInstance as $obj) { + $results[$obj->Name]['errs'] = $obj->PacketsReceivedErrors; + $results[$obj->Name]['drop'] = $obj->PacketsReceivedDiscarded; + } // while + return $results; + } + + function memory () + { + $objInstance = $this->wmi->InstancesOf("Win32_LogicalMemoryConfiguration"); + foreach ($objInstance as $obj) { + $results['ram']['total'] = $obj->TotalPhysicalMemory; + } + $objInstance = $this->wmi->InstancesOf("Win32_PerfRawData_PerfOS_Memory"); + foreach ($objInstance as $obj) { + $results['ram']['free'] = $obj->AvailableKBytes; + } + $results['ram']['used'] = $results['ram']['total'] - $results['ram']['free']; + $results['ram']['t_used'] = $results['ram']['used']; + $results['ram']['t_free'] = $results['ram']['total'] - $results['ram']['t_used']; + $results['ram']['percent'] = round(($results['ram']['t_used'] * 100) / $results['ram']['total']); + + $results['swap']['total'] = 0; + $results['swap']['used'] = 0; + $results['swap']['free'] = 0; + + $objInstance = $this->wmi->InstancesOf("Win32_PageFileUsage"); + + $k = 0; + foreach ($objInstance as $obj) { + $results['devswap'][$k]['dev'] = $obj->Name; + $results['devswap'][$k]['total'] = $obj->AllocatedBaseSize * 1024; + $results['devswap'][$k]['used'] = $obj->CurrentUsage * 1024; + $results['devswap'][$k]['free'] = ($obj->AllocatedBaseSize - $obj->CurrentUsage) * 1024; + $results['devswap'][$k]['percent'] = $obj->CurrentUsage / $obj->AllocatedBaseSize; + + $results['swap']['total'] += $results['devswap'][$k]['total']; + $results['swap']['used'] += $results['devswap'][$k]['used']; + $results['swap']['free'] += $results['devswap'][$k]['free']; + $k += 1; + } + + $results['swap']['percent'] = round($results['swap']['used'] / $results['swap']['total'] * 100); + + return $results; + } + + function filesystems () + { + $objInstance = $this->wmi->InstancesOf("Win32_LogicalDisk"); + + $k = 0; + foreach ($objInstance as $obj) { + $results[$k]['mount'] = $obj->Name; + $results[$k]['size'] = $obj->Size / 1024; + $results[$k]['used'] = ($obj->Size - $obj->FreeSpace) / 1024; + $results[$k]['free'] = $obj->FreeSpace / 1024; + $results[$k]['percent'] = round($results[$k]['used'] / $results[$k]['size'] * 100); + $results[$k]['fstype'] = $obj->FileSystem; + + $typearray = array("Unknown", "No Root Directory", "Removeable Disk", + "Local Disk", "Network Drive", "Compact Disc", "RAM Disk"); + $floppyarray = array("Unknown", "5 1/4 in.", "3 1/2 in.", "3 1/2 in.", + "3 1/2 in.", "3 1/2 in.", "5 1/4 in.", "5 1/4 in.", "5 1/4 in.", + "5 1/4 in.", "5 1/4 in.", "Other", "HD", "3 1/2 in.", "3 1/2 in.", + "5 1/4 in.", "5 1/4 in.", "3 1/2 in.", "3 1/2 in.", "5 1/4 in.", + "3 1/2 in.", "3 1/2 in.", "8 in."); + + $results[$k]['disk'] = $typearray[$obj->DriveType]; + if ($obj->DriveType == 2) $results[$k]['disk'] .= " (" . $floppyarray[$obj->MediaType] . ")"; + $k += 1; + } + + return $results; + } + + function distro () + { + $objInstance = $this->wmi->InstancesOf("Win32_OperatingSystem"); + foreach ($objInstance as $obj) { + return $obj->Caption; + } + } + + function distroicon () + { + return 'xp.gif'; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.WINNT.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.WINNT.inc.php new file mode 100644 index 00000000..330e3391 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.WINNT.inc.php @@ -0,0 +1,315 @@ +wmi = $objLocator->ConnectServer(); + } else{ + $this->wmi = $objLocator->ConnectServer($strHostname, "rootcimv2", "$strHostname\$strUser", $strPassword); + } + } + + // private function for getting a list of values in the specified context, optionally filter this list, based on the list from second parameter + function _GetWMI($strClass, $strValue = array() ) { + $objWEBM = $this->wmi->Get($strClass); + + if( PHP_VERSION < 5 ) { + $objProp = $objWEBM->Properties_; + $arrProp = $objProp->Next($objProp->Count); + $objWEBMCol = $objWEBM->Instances_(); + $arrWEBMCol = $objWEBMCol->Next($objWEBMCol->Count); + } else { + $arrProp = $objWEBM->Properties_; + $arrWEBMCol = $objWEBM->Instances_(); + } + + foreach($arrWEBMCol as $objItem) + { + @reset($arrProp); + $arrInstance = array(); + foreach($arrProp as $propItem) + { + eval("\$value = \$objItem->" .$propItem->Name .";"); + if( empty( $strValue ) ) { + $arrInstance[$propItem->Name] = trim($value); + } else { + if( in_array( $propItem->Name, $strValue ) ) { + $arrInstance[$propItem->Name] = trim($value); + } + } + } + $arrData[] = $arrInstance; + } + return $arrData; + } + + // private function for getting different device types from the system + function _devicelist ( $strType ) { + if( empty( $this->wmidevices ) ) { + $this->wmidevices = $this->_GetWMI( "Win32_PnPEntity", array( "Name", "PNPDeviceID" ) ); + } + + $list = array(); + foreach ( $this->wmidevices as $device ) { + if ( substr( $device["PNPDeviceID"], 0, strpos( $device["PNPDeviceID"], "\\" ) + 1 ) == ( $strType . "\\" ) ) { + $list[] = $device["Name"]; + } + } + + return $list; + } + + // get our canonical hostname + function chostname () + { + $buffer = $this->_GetWMI( "Win32_ComputerSystem", array( "Name" ) ); + $result = $buffer[0]["Name"]; + return gethostbyaddr(gethostbyname($result)); + } + + // get the IP address of our canonical hostname + function ip_addr () + { + $buffer = $this->_GetWMI( "Win32_ComputerSystem", array( "Name" ) ); + $result = $buffer[0]["Name"]; + return gethostbyname($result); + } + + function kernel () + { + $buffer = $this->_GetWMI( "Win32_OperatingSystem", array( "Version", "ServicePackMajorVersion" ) ); + $result = $buffer[0]["Version"]; + if( $buffer[0]["ServicePackMajorVersion"] > 0 ) { + $result .= " SP" . $buffer[0]["ServicePackMajorVersion"]; + } + return $result; + } + + // get the time the system is running + function uptime () + { + $result = 0; + $buffer = $this->_GetWMI( "Win32_OperatingSystem", array( "LastBootUpTime" ) ); + + $year = intval(substr($buffer[0]["LastBootUpTime"], 0, 4)); + $month = intval(substr($buffer[0]["LastBootUpTime"], 4, 2)); + $day = intval(substr($buffer[0]["LastBootUpTime"], 6, 2)); + $hour = intval(substr($buffer[0]["LastBootUpTime"], 8, 2)); + $minute = intval(substr($buffer[0]["LastBootUpTime"], 10, 2)); + $seconds = intval(substr($buffer[0]["LastBootUpTime"], 12, 2)); + + $hour -= date("Z") / 60 / 60; // GMT-Offset + + $boottime = mktime($hour, $minute, $seconds, $month, $day, $year); + + $result = mktime() - $boottime; + + return $result; + } + + // count the users, which are logged in + function users () + { + if( !stristr( $this->kernel(), "2000 P" ) ) return "N.A."; + $buffer = $this->_GetWMI( "Win32_PerfRawData_TermService_TerminalServices", array( "TotalSessions" ) ); + return $buffer[0]["TotalSessions"]; + } + + // get the load of the processors + function loadavg ($bar = false) + { + $buffer = $this->_GetWMI( "Win32_Processor", array( "LoadPercentage" ) ); + $cpuload = array(); + for( $i = 0; $i < count( $buffer ); $i++ ) { + $cpuload['avg'][] = $buffer[$i]["LoadPercentage"]; + } + if ($bar) { + $cpuload['cpupercent'] = array_sum( $cpuload['avg'] ) / count( $buffer ); + } + return $cpuload; + } + + // get some informations about the cpu's + function cpu_info () + { + $buffer = $this->_GetWMI( "Win32_Processor", array( "Name", "L2CacheSize", "CurrentClockSpeed", "ExtClock" ) ); + $results["cpus"] = 0; + foreach ($buffer as $cpu) { + $results["cpus"]++; + $results["model"] = $cpu["Name"]; + $results["cache"] = $cpu["L2CacheSize"]; + $results["cpuspeed"] = $cpu["CurrentClockSpeed"]; + $results["busspeed"] = $cpu["ExtClock"]; + } + return $results; + } + + // get the pci devices from the system + function pci () + { + $pci = $this->_devicelist( "PCI" ); + return $pci; + } + + // get the ide devices from the system + function ide () + { + $buffer = $this->_devicelist( "IDE" ); + $ide = array(); + foreach ( $buffer as $device ) { + $ide[]['model'] = $device; + } + return $ide; + } + + // get the scsi devices from the system + function scsi () + { + $scsi = $this->_devicelist( "SCSI" ); + return $scsi; + } + + // get the usb devices from the system + function usb () + { + $usb = $this->_devicelist( "USB" ); + return $usb; + } + + // get the sbus devices from the system - currently not called + function sbus () + { + $sbus = $this->_devicelist( "SBUS" ); + return $sbus; + } + + // get the netowrk devices and rx/tx bytes + function network () + { + $buffer = $this->_GetWMI( "Win32_PerfRawData_Tcpip_NetworkInterface" ); + $results = array(); + foreach ( $buffer as $device ) { + $dev_name = $device["Name"]; + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/win32_perfrawdata_tcpip_networkinterface.asp + $results[$dev_name]['rx_bytes'] = $device["BytesReceivedPersec"]; + $results[$dev_name]['rx_packets'] = $device["PacketsReceivedPersec"]; + $results[$dev_name]['rx_errs'] = $device["PacketsReceivedErrors"]; + $results[$dev_name]['rx_drop'] = $device["PacketsReceivedDiscarded"]; + + $results[$dev_name]['tx_bytes'] = $device["BytesSentPersec"]; + $results[$dev_name]['tx_packets'] = $device["PacketsSentPersec"]; + + $results[$dev_name]['errs'] = $device["PacketsReceivedErrors"]; + $results[$dev_name]['drop'] = $device["PacketsReceivedDiscarded"]; + } + return $results; + } + + function memory () + { + $buffer = $this->_GetWMI( "Win32_LogicalMemoryConfiguration", array( "TotalPhysicalMemory" ) ); + $results['ram']['total'] = $buffer[0]["TotalPhysicalMemory"]; + + $buffer = $this->_GetWMI( "Win32_PerfRawData_PerfOS_Memory", array( "AvailableKBytes" ) ); + $results['ram']['free'] = $buffer[0]["AvailableKBytes"]; + + $results['ram']['used'] = $results['ram']['total'] - $results['ram']['free']; + $results['ram']['t_used'] = $results['ram']['used']; + $results['ram']['t_free'] = $results['ram']['total'] - $results['ram']['t_used']; + $results['ram']['percent'] = ceil( ( $results['ram']['t_used'] * 100 ) / $results['ram']['total'] ); + $results['swap']['total'] = 0; + $results['swap']['used'] = 0; + $results['swap']['free'] = 0; + + $buffer = $this->_GetWMI( "Win32_PageFileUsage" ); // no need to filter, using nearly everything from output + $k = 0; + foreach ($buffer as $swapdevice) { + $results['devswap'][$k]['dev'] = $swapdevice["Name"]; + $results['devswap'][$k]['total'] = $swapdevice["AllocatedBaseSize"] * 1024; + $results['devswap'][$k]['used'] = $swapdevice["CurrentUsage"] * 1024; + $results['devswap'][$k]['free'] = ( $swapdevice["AllocatedBaseSize"] - $swapdevice["CurrentUsage"] ) * 1024; + $results['devswap'][$k]['percent'] = ceil( $swapdevice["CurrentUsage"] / $swapdevice["AllocatedBaseSize"] ); + + $results['swap']['total'] += $results['devswap'][$k]['total']; + $results['swap']['used'] += $results['devswap'][$k]['used']; + $results['swap']['free'] += $results['devswap'][$k]['free']; + $k += 1; + } + $results['swap']['percent'] = ceil( $results['swap']['used'] / $results['swap']['total'] * 100 ); + return $results; + } + + // get the filesystem informations + function filesystems () + { + $typearray = array("Unknown", "No Root Directory", "Removeable Disk", + "Local Disk", "Network Drive", "Compact Disc", "RAM Disk"); + $floppyarray = array("Unknown", "5 1/4 in.", "3 1/2 in.", "3 1/2 in.", + "3 1/2 in.", "3 1/2 in.", "5 1/4 in.", "5 1/4 in.", "5 1/4 in.", + "5 1/4 in.", "5 1/4 in.", "Other", "HD", "3 1/2 in.", "3 1/2 in.", + "5 1/4 in.", "5 1/4 in.", "3 1/2 in.", "3 1/2 in.", "5 1/4 in.", + "3 1/2 in.", "3 1/2 in.", "8 in."); + + $buffer = $this->_GetWMI( "Win32_LogicalDisk" , array( "Name", "Size", "FreeSpace", "FileSystem", "DriveType", "MediaType" ) ); + + $k = 0; + foreach ( $buffer as $filesystem ) { + if ( hide_mount( $filesystem["Name"] ) ) { + continue; + } + $results[$k]['mount'] = $filesystem["Name"]; + $results[$k]['size'] = $filesystem["Size"] / 1024; + $results[$k]['used'] = ( $filesystem["Size"] - $filesystem["FreeSpace"] ) / 1024; + $results[$k]['free'] = $filesystem["FreeSpace"] / 1024; + @$results[$k]['percent'] = ceil( $results[$k]['used'] / $results[$k]['size'] * 100 ); // silence this line, nobody is having a floppy in the drive everytime + $results[$k]['fstype'] = $filesystem["FileSystem"]; + $results[$k]['disk'] = $typearray[$filesystem["DriveType"]]; + if ( $filesystem["DriveType"] == 2 ) $results[$k]['disk'] .= " (" . $floppyarray[$filesystem["MediaType"]] . ")"; + $k += 1; + } + return $results; + } + + function distro () + { + $buffer = $this->_GetWMI( "Win32_OperatingSystem", array( "Caption" ) ); + return $buffer[0]["Caption"]; + } + + function distroicon () + { + return 'xp.gif'; + } +} + +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/class.parseProgs.inc.php b/oss/vtiger/trunk/modules/System/includes/os/class.parseProgs.inc.php new file mode 100644 index 00000000..2f6ae78b --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/os/class.parseProgs.inc.php @@ -0,0 +1,133 @@ +debug)) { + $lines = split("\n", $_results); + for ($i = 0, $max = sizeof($lines); $i < $max; $i++) { + list($addr, $name) = explode(' ', trim($lines[$i]), 2); + //if (!preg_match('/bridge/i', $name) && !preg_match('/USB/i', $name)) { + // remove all the version strings + $name = preg_replace('/\(.*\)/', '', $name); + // is addr really usefull for this??? i think it's not + // $results[] = $addr . ' ' . $name; + $results[] = $name; + //} + } + } + + if( empty( $results ) ) { + return false; + } else { + asort( $results ); + return $results; + } + } + + function parse_pciconf() { + + $results = array(); + + if($buf = execute_program("pciconf", "-lv", $this->debug)) { + $buf = explode("\n", $buf); $s = 0; + foreach($buf as $line) { + if (preg_match("/(.*) = '(.*)'/", $line, $strings)) { + if (trim($strings[1]) == "vendor") { + $results[$s] = trim($strings[2]); + } elseif (trim($strings[1]) == "device") { + $results[$s] .= " - " . trim($strings[2]); + $s++; + } + } + } + } + + if( empty( $results ) ) { + return false; + } else { + asort( $results ); + return $results; + } + } + + function parse_filesystems() { + + global $show_bind, $show_inodes; + + $j = 0; + + $df = execute_program('df', '-k' . $this->df_param ); + $df = preg_split("/\n/", $df, -1, PREG_SPLIT_NO_EMPTY); + + if( $show_inodes ) { + $df2 = execute_program('df', '-i' . $this->df_param ); + $df2 = preg_split("/\n/", $df2, -1, PREG_SPLIT_NO_EMPTY); + } + + $mount = execute_program('mount'); + $mount = preg_split("/\n/", $mount, -1, PREG_SPLIT_NO_EMPTY); + + foreach( $df as $df_line) { + $df_buf1 = preg_split("/(\%\s)/", $df_line, 2); + if( count($df_buf1) != 2) { + continue; + } + + preg_match("/(.*)(\s+)(([0-9]+)(\s+)([0-9]+)(\s+)([0-9]+)(\s+)([0-9]+)$)/", $df_buf1[0], $df_buf2); + $df_buf = array($df_buf2[1], $df_buf2[4], $df_buf2[6], $df_buf2[8], $df_buf2[10], $df_buf1[1]); + + if( $show_inodes ) { + preg_match_all("/([0-9]+)%/", $df2[$j + 1], $inode_buf, PREG_SET_ORDER); + } + + if( count($df_buf) == 6 ) { + if( hide_mount( $df_buf[5] ) ) { + continue; + } + + $df_buf[0] = trim( str_replace("\$", "\\$", $df_buf[0] ) ); + $df_buf[5] = trim( $df_buf[5] ); + + $current = 0; + foreach( $mount as $mount_line ) { + $current++; + + if ( preg_match("#" . $df_buf[0] . " on " . $df_buf[5] . " type (.*) \((.*)\)#", $mount_line, $mount_buf) ) { + $mount_buf[1] .= "," . $mount_buf[2]; + } elseif ( !preg_match("#" . $df_buf[0] . "(.*) on " . $df_buf[5] . " \((.*)\)#", $mount_line, $mount_buf) ) { + continue; + } + + if ( $show_bind || !stristr($mount_buf[2], "bind")) { + $results[$j] = array(); + $results[$j]['disk'] = str_replace( "\\$", "\$", $df_buf[0] ); + $results[$j]['size'] = $df_buf[1]; + $results[$j]['used'] = $df_buf[2]; + $results[$j]['free'] = $df_buf[3]; + $results[$j]['percent'] = round(($results[$j]['used'] * 100) / $results[$j]['size']); + $results[$j]['mount'] = $df_buf[5]; + $results[$j]['fstype'] = substr( $mount_buf[1], 0, strpos( $mount_buf[1], "," ) ); + $results[$j]['options'] = substr( $mount_buf[1], strpos( $mount_buf[1], "," ) + 1, strlen( $mount_buf[1] ) ); + if( $show_inodes && isset($inode_buf[ count( $inode_buf ) - 1][1]) ) { + $results[$j]['inodes'] = $inode_buf[ count( $inode_buf ) - 1][1]; + } + $j++; + unset( $mount[$current - 1] ); + sort( $mount ); + break; + } + } + } + } + return $results; + } + +} +?> diff --git a/oss/vtiger/trunk/modules/System/includes/os/index.html b/oss/vtiger/trunk/modules/System/includes/os/index.html new file mode 100644 index 00000000..e69de29b diff --git a/oss/vtiger/trunk/modules/System/includes/system_footer.php b/oss/vtiger/trunk/modules/System/includes/system_footer.php new file mode 100644 index 00000000..fc33a5d1 --- /dev/null +++ b/oss/vtiger/trunk/modules/System/includes/system_footer.php @@ -0,0 +1,107 @@ +"; + + $update_form = "\n" . "\t" . $text['template'] . ": \n" . "\t"; + $temp_relatedfield['fieldid'] = $related_fieldid; + $temp_relatedfield['fieldname'] = $related_fieldname; + $relatedFieldsArray[] = $temp_relatedfield; + } + + $relatedFieldsArray = array_chunk($relatedFieldsArray, 4); + return $relatedFieldsArray; +} + +/** + * function to get the module names + * @return - all module names other than Calendar and Events + */ +function moduleList() { + global $adb; + $sql = "select distinct vtiger_field.tabid,name from vtiger_field inner join vtiger_tab on vtiger_field.tabid=vtiger_tab.tabid where name not in ('Calendar','Events','Users')"; + $result = $adb->pquery($sql, array ()); + while ($moduleinfo = $adb->fetch_array($result)) { + $modulelist[$moduleinfo['name']] = getTranslatedString($moduleinfo['name']); + } + return $modulelist; +} + +/** + * this function determines if a given field has the related field already present in the tooltip + */ +function tooltip_exists($fieldid, $related_fieldid) { + global $adb; + $query = "select * from vtiger_quickview where fieldid=? and related_fieldid=?"; + $result = $adb->pquery($query, array ($fieldid,$related_fieldid)); + + if ($adb->num_rows($result) > 0) { + return true; + } else { + return false; + } +} + +/** + * function to return the tooltip information + * @param int $view - there can be multiple tooltips for a single module; this variable decides which is for which field + * @param int $tabid - tabid of the field for which the tooltip has to be fetched + * @param int $id - this is the crmid of the record + * returns the tooltip string + */ +function getToolTipText($view,$fieldname,$module,$value){ + global $adb,$app_strings; + $keys = array_keys($value[0]); + //getting the quickview list here + $fieldlabel = Array(); + $fieldid = getFieldid(getTabid($module), $fieldname); + $quickview = 'select fieldname,fieldlabel from vtiger_quickview inner join vtiger_field on vtiger_quickview.related_fieldid=vtiger_field.fieldid where vtiger_quickview.fieldid = ? and currentview= ? and vtiger_field.presence in (0,2) order by vtiger_quickview.sequence'; + $result = $adb->pquery($quickview,array($fieldid,$view)); + $count = $adb->num_rows($result); + + $text=''; + $fieldname = Array(); + for($i=0;$i<$count;$i++){ + $fieldname = $adb->query_result($result,$i,"fieldname"); + + if(in_array($fieldname, $keys)){ + $fieldlabel = $adb->query_result($result,$i,"fieldlabel"); + $label = getTranslatedString($fieldlabel); + $fieldvalue = $value[0][$fieldname]; + if(strlen($fieldvalue)>35){ + $fieldvalue = substr($fieldvalue,0,35).'...'; + } + $text[$label] = $fieldvalue; + } + } + return $text; +} + +/** + * this function accepts the tooltip text and returns it after formatting + * @param $text - the tooltip text which is to be formatted + * @param $format - the format in which tooltip has to be formatted; default value will be each entry in single line + */ +function getToolTip($text,$format = "default"){ + require_once('Smarty_setup.php'); + $smarty = new vtigerCRM_Smarty; + $tip = ""; + + if(trim($text) == ""){ + return $tip; + } + + $smarty->assign("TEXT",$text); + $tip = $smarty->fetch("modules/Tooltip/$format.tpl"); + return $tip; +} + +/** + * this function checks if tooltip exists for a given field or not + */ +function ToolTipExists($fieldname,$tabid){ + if(empty($fieldname) || empty($tabid)){ + return false; + }else{ + global $adb; + $sql = "select fieldid from vtiger_field where tabid = ? and fieldname = ? and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($sql,array($tabid,$fieldname)); + $count = $adb->num_rows($result); + if($count > 0){ + $fieldid = $adb->query_result($result,0,'fieldid'); + + $sql = "select * from vtiger_quickview where fieldid = ?"; + $result = $adb->pquery($sql, array($fieldid)); + + if($adb->num_rows($result) > 0){ + return $fieldid; + }else{ + return false; + } + }else{ + return false; + } + } +} + +/** + * this function processes the given result and returns the value :: for now we are getting the values for the + * reference, owner fields, booleans and currency fields; other processing might be added later if required + * @param array $result - the webservices result object + * @param array $descObj - the webservices describe object + * @return array $result - the processes webservices result object + */ +function vttooltip_processResult($result, $descObj){ + global $current_user; + foreach($descObj['fields'] as $field){ + if($field['type']['name'] == 'reference'){ + $name = $field['name']; + $value = $result[0][$name]; + + if(!empty($value)){ + $result[0][$name] = vtws_getName($value,$current_user); + }else{ + $result[0][$name] = ''; + } + }elseif($field['type']['name'] == 'owner'){ + $name = $field['name']; + $value = $result[0][$name]; + list($info, $id) = explode("x",$value); + $result[0][$name] = getOwnerName($id); + }elseif($field['type']['name'] == 'boolean'){ + $name = $field['name']; + if($result[0][$name] == 1){ + $result[0][$name] = "on"; + }else{ + $result[0][$name] = "off"; + } + }elseif($field['type']['name'] == 'picklist'){ + $name = $field['name']; + $temp = ''; + foreach($field['type']['picklistValues'] as $value){ + if(strcmp($value['value'],$result[0][$name])== 0){ + $temp = $value['value']; + } + } + $result[0][$name] = $temp; + } + } + return $result; +} + + +/** + * this function returns the fields for a given module in a select dropdown format + * @param string $module - the module name + * @return the fields in a select dropdown if fields exist else a blank value + */ +function QuickViewFieldList($module){ + global $adb, $app_strings,$mod_strings; + + $tabid = getTabid($module); + + $query = "select * from vtiger_field where tabid = ? and columnname not like 'imagename' and uitype not in (61, 122) and vtiger_field.presence in (0,2)"; + $result = $adb->pquery($query,array($tabid)); + if($adb->num_rows($result)>0){ + $fieldlist = ''; + return $fieldlist; + }else{ + return ''; + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Tooltip/index.php b/oss/vtiger/trunk/modules/Tooltip/index.php new file mode 100644 index 00000000..0b11eea8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Tooltip/index.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Tooltip/language/en_us.lang.php b/oss/vtiger/trunk/modules/Tooltip/language/en_us.lang.php new file mode 100644 index 00000000..fe62bea2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Tooltip/language/en_us.lang.php @@ -0,0 +1,22 @@ + 'ToolTip', +'LBL_TOOLTIP_MANAGEMENT'=>'Tooltip Management', +'LBL_TOOLTIP_MANAGEMENT_DESCRIPTION'=>'Manage the tooltip information from here', +'LBL_FIELDS_IN'=>'Fields in', +'LBL_TOOLTIP_HELP_TEXT'=>'Select the fields that you would like to be displayed as tooltip', +'LBL_FIELD'=>'Field', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Tooltip/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Tooltip/language/zh_cn.lang.php new file mode 100644 index 00000000..1a531b92 --- /dev/null +++ b/oss/vtiger/trunk/modules/Tooltip/language/zh_cn.lang.php @@ -0,0 +1,22 @@ + '提示板', +'LBL_TOOLTIP_MANAGEMENT'=>'提示板管理', +'LBL_TOOLTIP_MANAGEMENT_DESCRIPTION'=>'从这里管理提示板工具', +'LBL_FIELDS_IN'=>'字段', +'LBL_TOOLTIP_HELP_TEXT'=>'选择字段,选中项将在提示板上显示', +'LBL_FIELD'=>'字段', + +); + +?> diff --git a/oss/vtiger/trunk/modules/Tooltip/schema.xml b/oss/vtiger/trunk/modules/Tooltip/schema.xml new file mode 100644 index 00000000..316b6b26 --- /dev/null +++ b/oss/vtiger/trunk/modules/Tooltip/schema.xml @@ -0,0 +1,16 @@ + + + + + vtiger_quickview + +
    +
    +
    diff --git a/oss/vtiger/trunk/modules/Users/AddMailAccount.php b/oss/vtiger/trunk/modules/Users/AddMailAccount.php new file mode 100644 index 00000000..ad404c0f --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/AddMailAccount.php @@ -0,0 +1,115 @@ +assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +if(isset($_REQUEST['record']) && $_REQUEST['record']!='') +{ + $sql = "select * from vtiger_mail_accounts where user_id=?"; + $result = $adb->pquery($sql, array($_REQUEST['record'])); + $rowcount = $adb->num_rows($result); + + if ($rowcount!=0) + { + while($temprow = $adb->fetchByAssoc($result)) + { + $smarty->assign("DISPLAYNAME", $temprow['display_name']); + $smarty->assign("ID", $temprow['user_id']); + $smarty->assign("EMAIL", $temprow['mail_id']); + $smarty->assign("ACCOUNTNAME", $temprow['account_name']); + $smarty->assign($temprow['mail_protocol'],$temprow['mail_protocol']); + $smarty->assign("SERVERUSERNAME", $temprow['mail_username']); + $smarty->assign("SERVERPASSWORD", $temprow['mail_password']); + $smarty->assign("SERVERNAME", $temprow['mail_servername']); + $smarty->assign("RECORD_ID", $temprow['account_id']); + $smarty->assign("BOX_REFRESH", $temprow['box_refresh']); + $smarty->assign("MAILS_PER_PAGE", $temprow['mails_per_page']); + $smarty->assign("EDIT", "TRUE"); + + if(strtolower($temprow['mail_protocol']) == "imap") + $smarty->assign("IMAP", "CHECKED"); + if(strtolower($temprow['mail_protocol']) == "imap2") + $smarty->assign("IMAP2", "CHECKED"); + if(strtolower($temprow['mail_protocol']) == "imap4") + $smarty->assign("IMAP4", "CHECKED"); + if(strtolower($temprow['mail_protocol']) == "imap4rev1") + $smarty->assign("IMAP4R1", "CHECKED"); + if(strtolower($temprow['mail_protocol']) == "pop3") + $smarty->assign("POP3", "CHECKED"); + + if(strtolower($temprow['ssltype']) == "notls") + $smarty->assign("NOTLS", "CHECKED"); + if(strtolower($temprow['ssltype']) == "tls") + $smarty->assign("TLS", "CHECKED"); + if(strtolower($temprow['ssltype']) == "ssl") + $smarty->assign("SSL", "CHECKED"); + if(strtolower($temprow['sslmeth']) == "validate-cert") + $smarty->assign("VALIDATECERT", "CHECKED"); + if(strtolower($temprow['sslmeth']) == "novalidate-cert") + $smarty->assign("NOVALIDATECERT", "CHECKED"); + + if($temprow['int_mailer'] == "1") + $smarty->assign("INT_MAILER_USE", "CHECKED"); + else + $smarty->assign("INT_MAILER_NOUSE", "CHECKED"); + if(strtolower($temprow['box_refresh']) == "60000") + $smarty->assign("BOX_OPT1", " SELECTED"); + if(strtolower($temprow['box_refresh']) == "120000") + $smarty->assign("BOX_OPT2", " SELECTED"); + if(strtolower($temprow['box_refresh']) == "180000") + $smarty->assign("BOX_OPT3", " SELECTED"); + if(strtolower($temprow['box_refresh']) == "240000") + $smarty->assign("BOX_OPT4", " SELECTED"); + if(strtolower($temprow['box_refresh']) == "300000") + $smarty->assign("BOX_OPT5", " SELECTED"); + } + } +} +$qry_res = $adb->pquery("select * from vtiger_mail_accounts where user_id=?", array($current_user->id)); +$count = $adb->num_rows($qry_res); +if($count > 0) + $field = '';//""; +else + $field = ''; +$smarty->assign('CHANGE_PW_BUTTON',$field); + +$return_module = vtlib_purify($_REQUEST['return_module']); +if(empty($return_module)) $return_module = 'Settings'; +else $return_module = htmlspecialchars($return_module, ENT_QUOTES, $default_charset); + +$return_action = vtlib_purify($_REQUEST['return_action']); +if(empty($return_action)) $return_action = 'index'; +else $return_action = htmlspecialchars($return_action, ENT_QUOTES, $default_charset); + +$smarty->assign("RETURN_MODULE",$return_module); +$smarty->assign("RETURN_ACTION",$return_action); +$smarty->assign("JAVASCRIPT", get_validate_record_js()); +$smarty->assign("USERID", $current_user->id); + +$smarty->display('AddMailAccount.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/Announcements.php b/oss/vtiger/trunk/modules/Users/Announcements.php new file mode 100644 index 00000000..59aeb2ee --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Announcements.php @@ -0,0 +1,36 @@ +pquery($query, array($current_user->id)); +$announcement=$adb->query_result($result,0,'announcement'); +$title_prev=$adb->query_result($result,0,'title'); +$id=$adb->query_result($result,0,'creatorid'); + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("ANNOUNCE",$announcement); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +$smarty->display("Settings/Announcements.tpl"); + +?> diff --git a/oss/vtiger/trunk/modules/Users/Authenticate.php b/oss/vtiger/trunk/modules/Users/Authenticate.php new file mode 100644 index 00000000..42fc5daf --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Authenticate.php @@ -0,0 +1,145 @@ +column_fields["user_name"] = to_html($_REQUEST['user_name']); +$user_password = vtlib_purify($_REQUEST['user_password']); + +$focus->load_user($user_password); + +if($focus->is_authenticated()) +{ + + //Inserting entries for audit trail during login + + if($audit_trail == 'true') + { + if($record == '') + $auditrecord = ''; + else + $auditrecord = $record; + + $date_var = $adb->formatDate(date('Y-m-d H:i:s'), true); + $query = "insert into vtiger_audit_trial values(?,?,?,?,?,?)"; + $params = array($adb->getUniqueID('vtiger_audit_trial'), $focus->id, 'Users','Authenticate','',$date_var); + $adb->pquery($query, $params); + } + + + // Recording the login info + $usip=$_SERVER['REMOTE_ADDR']; + $intime=date("Y/m/d H:i:s"); + require_once('modules/Users/LoginHistory.php'); + $loghistory=new LoginHistory(); + $Signin = $loghistory->user_login($focus->column_fields["user_name"],$usip,$intime); + + //Security related entries start + require_once('include/utils/UserInfoUtil.php'); + + createUserPrivilegesfile($focus->id); + + //Security related entries end + session_unregister('login_password'); + session_unregister('login_error'); + session_unregister('login_user_name'); + + $_SESSION['authenticated_user_id'] = $focus->id; + $_SESSION['app_unique_key'] = $application_unique_key; + + // store the user's theme in the session + if (isset($_REQUEST['login_theme'])) { + $authenticated_user_theme = $_REQUEST['login_theme']; + } + elseif (isset($_REQUEST['ck_login_theme'])) { + $authenticated_user_theme = $_REQUEST['ck_login_theme']; + } + else { + $authenticated_user_theme = $default_theme; + } + + // store the user's language in the session + if (isset($_REQUEST['login_language'])) { + $authenticated_user_language = $_REQUEST['login_language']; + } + elseif (isset($_REQUEST['ck_login_language'])) { + $authenticated_user_language = $_REQUEST['ck_login_language']; + } + else { + $authenticated_user_language = $default_language; + } + + // If this is the default user and the default user theme is set to reset, reset it to the default theme value on each login + if($reset_theme_on_default_user && $focus->user_name == $default_user_name) + { + $authenticated_user_theme = $default_theme; + } + if(isset($reset_language_on_default_user) && $reset_language_on_default_user && $focus->user_name == $default_user_name) + { + $authenticated_user_language = $default_language; + } + + $_SESSION['vtiger_authenticated_user_theme'] = $authenticated_user_theme; + $_SESSION['authenticated_user_language'] = $authenticated_user_language; + + $log->debug("authenticated_user_theme is $authenticated_user_theme"); + $log->debug("authenticated_user_language is $authenticated_user_language"); + $log->debug("authenticated_user_id is ". $focus->id); + $log->debug("app_unique_key is $application_unique_key"); + + +// Clear all uploaded import files for this user if it exists + + global $import_dir; + + $tmp_file_name = $import_dir. "IMPORT_".$focus->id; + + if (file_exists($tmp_file_name)) + { + unlink($tmp_file_name); + } + $arr = $_SESSION['lastpage']; + if(isset($_SESSION['lastpage'])) + header("Location: index.php?".$arr[0]); + else + header("Location: index.php"); +} +else +{ + $_SESSION['login_user_name'] = $focus->column_fields["user_name"]; + $_SESSION['login_password'] = $user_password; + $_SESSION['login_error'] = $mod_strings['ERR_INVALID_PASSWORD']; + + // go back to the login screen. + // create an error message for the user. + header("Location: index.php"); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/ChangePassword.php b/oss/vtiger/trunk/modules/Users/ChangePassword.php new file mode 100644 index 00000000..b7d81e15 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/ChangePassword.php @@ -0,0 +1,111 @@ + + + + + + + + + + + +"; + echo "\n"; + echo "\n"; + echo ""; + echo "\n"; +} +else echo ""; +?> + + + + + + + + + +
    ".$mod_strings['LBL_OLD_PASSWORD']."
    +
    + + + + + + + +
    ' accessKey='' class='crmbutton small save' LANGUAGE=javascript onclick='if (set_password(this.form)) window.close(); else return false;' type='submit' name='button' value=' '>' accessyKey='' class='crmbutton small cancel' LANGUAGE=javascript onclick='window.close()' type='submit' name='button' value=' '>
    + +
    + diff --git a/oss/vtiger/trunk/modules/Users/CreateProfile.php b/oss/vtiger/trunk/modules/Users/CreateProfile.php new file mode 100644 index 00000000..d0adb793 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/CreateProfile.php @@ -0,0 +1,68 @@ +pquery($query, array($profilename)); + + if($adb->num_rows($result) > 0) + { + echo $mod_strings['LBL_PROFILENAME_EXIST']; + die; + }else + { + echo 'SUCCESS'; + die; + } + +} + + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty = new vtigerCRM_Smarty; + +if(isset($_REQUEST['parent_profile']) && $_REQUEST['parent_profile'] != '') + $smarty->assign("PARENT_PROFILE",vtlib_purify($_REQUEST['parent_profile'])); +if(isset($_REQUEST['radio_button']) && $_REQUEST['radio_button'] != '') + $smarty->assign("RADIO_BUTTON",vtlib_purify($_REQUEST['radio_button'])); +if(isset($_REQUEST['profile_name']) && $_REQUEST['profile_name'] != '') + $smarty->assign("PROFILE_NAME",vtlib_purify($_REQUEST['profile_name'])); +if(isset($_REQUEST['profile_description']) && $_REQUEST['profile_description'] != '') + $smarty->assign("PROFILE_DESCRIPTION",vtlib_purify($_REQUEST['profile_description'])); +if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != '') + $smarty->assign("MODE",vtlib_purify($_REQUEST['mode'])); + +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +$sql = "select * from vtiger_profile"; +$result = $adb->pquery($sql, array()); +$profilelist = array(); +$temprow = $adb->fetch_array($result); +do +{ + $name=$temprow["profilename"]; + $profileid=$temprow["profileid"]; + $profilelist[] = array($name,$profileid); +}while($temprow = $adb->fetch_array($result)); +$smarty->assign("PROFILE_LISTS", $profilelist); +$smarty->display("CreateProfile.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/CreateUserPrivilegeFile.php b/oss/vtiger/trunk/modules/Users/CreateUserPrivilegeFile.php new file mode 100644 index 00000000..7e1551e4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/CreateUserPrivilegeFile.php @@ -0,0 +1,1780 @@ +retrieve_entity_info($userid,"Users"); + $userInfo=Array(); + $user_focus->column_fields["id"] = ''; + $user_focus->id = $userid; + foreach($user_focus->column_fields as $field=>$value_iter) + { + $userInfo[$field]= $user_focus->$field; + } + + if($user_focus->is_admin == 'on') + { + $newbuf .= "\$is_admin=true;\n"; + $newbuf .="\n"; + $newbuf .= "\$user_info=".constructSingleStringKeyValueArray($userInfo).";\n"; + $newbuf .= "\n"; + $newbuf .= "?>"; + fputs($handle, $newbuf); + fclose($handle); + return; + } + else + { + $newbuf .= "\$is_admin=false;\n"; + $newbuf .= "\n"; + + $globalPermissionArr=getCombinedUserGlobalPermissions($userid); + $tabsPermissionArr=getCombinedUserTabsPermissions($userid); + //$tabsPermissionArr=getCombinedUserTabsPermissions($userid); + $actionPermissionArr=getCombinedUserActionPermissions($userid); + $user_role=fetchUserRole($userid); + $user_role_info=getRoleInformation($user_role); + $user_role_parent=$user_role_info[$user_role][1]; + $userGroupFocus=new GetUserGroups(); + $userGroupFocus->getAllUserGroups($userid); + $subRoles=getRoleSubordinates($user_role); + $subRoleAndUsers=getSubordinateRoleAndUsers($user_role); + $def_org_share=getDefaultSharingAction(); + $parentRoles=getParentRole($user_role); + + + + + $newbuf .= "\$current_user_roles='".$user_role."';\n"; + $newbuf .= "\n"; + $newbuf .= "\$current_user_parent_role_seq='".$user_role_parent."';\n"; + $newbuf .= "\n"; + $newbuf .= "\$current_user_profiles=".constructSingleArray(getUserProfile($userid)).";\n"; + $newbuf .= "\n"; + $newbuf .= "\$profileGlobalPermission=".constructArray($globalPermissionArr).";\n"; + $newbuf .="\n"; + $newbuf .= "\$profileTabsPermission=".constructArray($tabsPermissionArr).";\n"; + $newbuf .="\n"; + $newbuf .= "\$profileActionPermission=".constructTwoDimensionalArray($actionPermissionArr).";\n"; + $newbuf .="\n"; + $newbuf .= "\$current_user_groups=".constructSingleArray($userGroupFocus->user_groups).";\n"; + $newbuf .="\n"; + $newbuf .= "\$subordinate_roles=".constructSingleCharArray($subRoles).";\n"; + $newbuf .="\n"; + $newbuf .= "\$parent_roles=".constructSingleCharArray($parentRoles).";\n"; + $newbuf .="\n"; + $newbuf .= "\$subordinate_roles_users=".constructTwoDimensionalCharIntSingleArray($subRoleAndUsers).";\n"; + $newbuf .="\n"; + $newbuf .= "\$user_info=".constructSingleStringKeyValueArray($userInfo).";\n"; + + $newbuf .= "?>"; + fputs($handle, $newbuf); + fclose($handle); + } + } +} + +/** Creates a file with all the organization default sharing permissions and custom sharing permissins specific for the specified user. In this file the information of the other users whose data is shared with the specified user is stored. + * @param $userid -- user id:: Type integer + * @returns sharing_privileges_userid file under the user_privileges directory + */ +function createUserSharingPrivilegesfile($userid) +{ + global $adb, $root_directory; + require('user_privileges/user_privileges_'.$userid.'.php'); + $handle=@fopen($root_directory.'user_privileges/sharing_privileges_'.$userid.'.php',"w+"); + +if($handle) + { + $newbuf=''; + $newbuf .="retrieve_entity_info($userid,"Users"); + if($user_focus->is_admin == 'on') + { + $newbuf .= "\n"; + $newbuf .= "?>"; + fputs($handle, $newbuf); + fclose($handle); + return; + } + else + { + //Constructig the Default Org Share Array + $def_org_share=getAllDefaultSharingAction(); + $newbuf .= "\$defaultOrgSharingPermission=".constructArray($def_org_share).";\n"; + $newbuf .= "\n"; + + //Constructing the Related Module Sharing Array + $relModSharArr=Array(); + $query ="select * from vtiger_datashare_relatedmodules"; + $result=$adb->pquery($query, array()); + $num_rows = $adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $parTabId=$adb->query_result($result,$i,'tabid'); + $relTabId=$adb->query_result($result,$i,'relatedto_tabid'); + if(is_array($relModSharArr[$relTabId])) + { + $temArr=$relModSharArr[$relTabId]; + $temArr[]=$parTabId; + } + else + { + $temArr=Array(); + $temArr[]=$parTabId; + } + $relModSharArr[$relTabId]=$temArr; + } + + $newbuf .= "\$related_module_share=".constructTwoDimensionalValueArray($relModSharArr).";\n\n"; + + //Constructing Lead Sharing Rules + $lead_share_per_array=getUserModuleSharingObjects("Leads",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $lead_share_read_per=$lead_share_per_array['read']; + $lead_share_write_per=$lead_share_per_array['write']; + $lead_sharingrule_members=$lead_share_per_array['sharingrules']; + + $newbuf .= "\$Leads_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($lead_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($lead_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Leads_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($lead_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($lead_share_write_per['GROUP']).");\n\n"; + + //Constructing the Lead Email Related Module Sharing Array + $lead_related_email=getRelatedModuleSharingArray("Leads","Emails",$lead_sharingrule_members,$lead_share_read_per,$lead_share_write_per,$def_org_share); + + $lead_email_share_read_per=$lead_related_email['read']; + $lead_email_share_write_per=$lead_related_email['write']; + + $newbuf .= "\$Leads_Emails_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($lead_email_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($lead_email_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Leads_Emails_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($lead_email_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($lead_email_share_write_per['GROUP']).");\n\n"; + + + + //Constructing Account Sharing Rules + $account_share_per_array=getUserModuleSharingObjects("Accounts",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $account_share_read_per=$account_share_per_array['read']; + $account_share_write_per=$account_share_per_array['write']; + $account_sharingrule_members=$account_share_per_array['sharingrules']; + /*echo '
    ';
    +			print_r($account_share_read_per['GROUP']);
    +			echo '
    ';*/ + $newbuf .= "\$Accounts_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($account_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($account_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($account_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($account_share_write_per['GROUP']).");\n\n"; + + //Constructing Contact Sharing Rules + $newbuf .= "\$Contacts_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($account_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($account_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Contacts_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($account_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($account_share_write_per['GROUP']).");\n\n"; + + + + + + //Constructing the Account Potential Related Module Sharing Array + $acct_related_pot=getRelatedModuleSharingArray("Accounts","Potentials",$account_sharingrule_members,$account_share_read_per,$account_share_write_per,$def_org_share); + + $acc_pot_share_read_per=$acct_related_pot['read']; + $acc_pot_share_write_per=$acct_related_pot['write']; + + $newbuf .= "\$Accounts_Potentials_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_pot_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_pot_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_Potentials_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_pot_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_pot_share_write_per['GROUP']).");\n\n"; + + //Constructing the Account Ticket Related Module Sharing Array + $acct_related_tkt=getRelatedModuleSharingArray("Accounts","HelpDesk",$account_sharingrule_members,$account_share_read_per,$account_share_write_per,$def_org_share); + + $acc_tkt_share_read_per=$acct_related_tkt['read']; + $acc_tkt_share_write_per=$acct_related_tkt['write']; + + $newbuf .= "\$Accounts_HelpDesk_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_tkt_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_tkt_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_HelpDesk_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_tkt_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_tkt_share_write_per['GROUP']).");\n\n"; + + //Constructing the Account Email Related Module Sharing Array + $acct_related_email=getRelatedModuleSharingArray("Accounts","Emails",$account_sharingrule_members,$account_share_read_per,$account_share_write_per,$def_org_share); + + $acc_email_share_read_per=$acct_related_email['read']; + $acc_email_share_write_per=$acct_related_email['write']; + + $newbuf .= "\$Accounts_Emails_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_email_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_email_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_Emails_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_email_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_email_share_write_per['GROUP']).");\n\n"; + + //Constructing the Account Quote Related Module Sharing Array + $acct_related_qt=getRelatedModuleSharingArray("Accounts","Quotes",$account_sharingrule_members,$account_share_read_per,$account_share_write_per,$def_org_share); + + $acc_qt_share_read_per=$acct_related_qt['read']; + $acc_qt_share_write_per=$acct_related_qt['write']; + + $newbuf .= "\$Accounts_Quotes_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_qt_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_qt_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_Quotes_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_qt_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_qt_share_write_per['GROUP']).");\n\n"; + + //Constructing the Account SalesOrder Related Module Sharing Array + $acct_related_so=getRelatedModuleSharingArray("Accounts","SalesOrder",$account_sharingrule_members,$account_share_read_per,$account_share_write_per,$def_org_share); + + $acc_so_share_read_per=$acct_related_so['read']; + $acc_so_share_write_per=$acct_related_so['write']; + + $newbuf .= "\$Accounts_SalesOrder_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_so_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_so_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_SalesOrder_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_so_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_so_share_write_per['GROUP']).");\n\n"; + + + //Constructing the Account Invoice Related Module Sharing Array + $acct_related_inv=getRelatedModuleSharingArray("Accounts","Invoice",$account_sharingrule_members,$account_share_read_per,$account_share_write_per,$def_org_share); + + $acc_inv_share_read_per=$acct_related_inv['read']; + $acc_inv_share_write_per=$acct_related_inv['write']; + + $newbuf .= "\$Accounts_Invoice_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_inv_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_inv_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Accounts_Invoice_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($acc_inv_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($acc_inv_share_write_per['GROUP']).");\n\n"; + + + //Constructing Potential Sharing Rules + $pot_share_per_array=getUserModuleSharingObjects("Potentials",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $pot_share_read_per=$pot_share_per_array['read']; + $pot_share_write_per=$pot_share_per_array['write']; + $pot_sharingrule_members=$pot_share_per_array['sharingrules']; + $newbuf .= "\$Potentials_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($pot_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($pot_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Potentials_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($pot_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($pot_share_write_per['GROUP']).");\n\n"; + + //Constructing the Potential Quotes Related Module Sharing Array + $pot_related_qt=getRelatedModuleSharingArray("Potentials","Quotes",$pot_sharingrule_members,$pot_share_read_per,$pot_share_write_per,$def_org_share); + + $pot_qt_share_read_per=$pot_related_qt['read']; + $pot_qt_share_write_per=$pot_related_qt['write']; + + $newbuf .= "\$Potentials_Quotes_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($pot_qt_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($pot_qt_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Potentials_Quotes_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($pot_qt_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($pot_qt_share_write_per['GROUP']).");\n\n"; + + //Constructing the Potential SalesOrder Related Module Sharing Array + $pot_related_inv=getRelatedModuleSharingArray("Potentials","SalesOrder",$pot_sharingrule_members,$pot_share_read_per,$pot_share_write_per,$def_org_share); + + + + $pot_inv_share_read_per=$pot_related_inv['read']; + $pot_inv_share_write_per=$pot_related_inv['write']; + + $newbuf .= "\$Potentials_SalesOrder_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($pot_inv_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($pot_inv_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Potentials_SalesOrder_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($pot_inv_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($pot_inv_share_write_per['GROUP']).");\n\n"; + + + + + //Constructing HelpDesk Sharing Rules + $hd_share_per_array=getUserModuleSharingObjects("HelpDesk",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $hd_share_read_per=$hd_share_per_array['read']; + $hd_share_write_per=$hd_share_per_array['write']; + $newbuf .= "\$HelpDesk_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($hd_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($hd_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$HelpDesk_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($hd_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($hd_share_write_per['GROUP']).");\n\n"; + + //Constructing Emails Sharing Rules + $email_share_per_array=getUserModuleSharingObjects("Emails",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $email_share_read_per=$email_share_per_array['read']; + $email_share_write_per=$email_share_per_array['write']; + $newbuf .= "\$Emails_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($email_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($email_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Emails_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($email_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($email_share_write_per['GROUP']).");\n\n"; + + //Constructing Campaigns Sharing Rules + $campaign_share_per_array=getUserModuleSharingObjects("Campaigns",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $campaign_share_read_per=$campaign_share_per_array['read']; + $campaign_share_write_per=$campaign_share_per_array['write']; + $newbuf .= "\$Campaigns_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($campaign_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($campaign_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Campaigns_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($campaign_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($campaign_share_write_per['GROUP']).");\n\n"; + + + //Constructing Quotes Sharing Rules + $quotes_share_per_array=getUserModuleSharingObjects("Quotes",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $quotes_share_read_per=$quotes_share_per_array['read']; + $quotes_share_write_per=$quotes_share_per_array['write']; + $quotes_sharingrule_members=$quotes_share_per_array['sharingrules']; + $newbuf .= "\$Quotes_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($quotes_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($quotes_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Quotes_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($quotes_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($quotes_share_write_per['GROUP']).");\n\n"; + + //Constructing the Quote SalesOrder Related Module Sharing Array + $qt_related_so=getRelatedModuleSharingArray("Quotes","SalesOrder",$quotes_sharingrule_members,$quotes_share_read_per,$quotes_share_write_per,$def_org_share); + + $qt_so_share_read_per=$qt_related_so['read']; + $qt_so_share_write_per=$qt_related_so['write']; + + $newbuf .= "\$Quotes_SalesOrder_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($qt_so_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($qt_so_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Quotes_SalesOrder_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($qt_so_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($qt_so_share_write_per['GROUP']).");\n\n"; + + + + + //Constructing Orders Sharing Rules + $po_share_per_array=getUserModuleSharingObjects("PurchaseOrder",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $po_share_read_per=$po_share_per_array['read']; + $po_share_write_per=$po_share_per_array['write']; + $newbuf .= "\$PurchaseOrder_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($po_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($po_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$PurchaseOrder_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($po_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($po_share_write_per['GROUP']).");\n\n"; + + //Constructing Sales Order Sharing Rules + $so_share_per_array=getUserModuleSharingObjects("SalesOrder",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $so_share_read_per=$so_share_per_array['read']; + $so_share_write_per=$so_share_per_array['write']; + $so_sharingrule_members=$so_share_per_array['sharingrules']; + $newbuf .= "\$SalesOrder_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($so_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($so_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$SalesOrder_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($so_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($so_share_write_per['GROUP']).");\n\n"; + + //Constructing the SalesOrder Invoice Related Module Sharing Array + $so_related_inv=getRelatedModuleSharingArray("SalesOrder","Invoice",$so_sharingrule_members,$so_share_read_per,$so_share_write_per,$def_org_share); + + $so_inv_share_read_per=$so_related_inv['read']; + $so_inv_share_write_per=$so_related_inv['write']; + + $newbuf .= "\$SalesOrder_Invoice_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($so_inv_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($so_inv_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$SalesOrder_Invoice_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($so_inv_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalValueArray($so_inv_share_write_per['GROUP']).");\n\n"; + + + + //Constructing Invoice Sharing Rules + $inv_share_per_array=getUserModuleSharingObjects("Invoice",$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + $inv_share_read_per=$inv_share_per_array['read']; + $inv_share_write_per=$inv_share_per_array['write']; + $newbuf .= "\$Invoice_share_read_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($inv_share_read_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($inv_share_read_per['GROUP']).");\n\n"; + $newbuf .= "\$Invoice_share_write_permission=array('ROLE'=>".constructTwoDimensionalCharIntSingleValueArray($inv_share_write_per['ROLE']).",'GROUP'=>".constructTwoDimensionalArray($inv_share_write_per['GROUP']).");\n\n"; + + // Writing Sharing Rules For Custom Modules. + // TODO: We are ignoring rules that has already been calculated above, it is good to add GENERIC logic here. + $custom_modules = getSharingModuleList( + Array('Leads', 'Accounts', 'Contacts', 'Potentials', 'HelpDesk', + 'Emails', 'Campaigns','Quotes', 'PurchaseOrder', 'SalesOrder', 'Invoice')); + + for($idx = 0; $idx < count($custom_modules); ++$idx) { + $module_name = $custom_modules[$idx]; + $mod_share_perm_array = getUserModuleSharingObjects($module_name,$userid, + $def_org_share,$current_user_roles,$parent_roles,$current_user_groups); + + $mod_share_read_perm = $mod_share_perm_array['read']; + $mod_share_write_perm= $mod_share_perm_array['write']; + $newbuf .= '$'.$module_name."_share_read_permission=array('ROLE'=>". + constructTwoDimensionalCharIntSingleValueArray($mod_share_read_perm['ROLE']).",'GROUP'=>". + constructTwoDimensionalArray($mod_share_read_perm['GROUP']).");\n\n"; + $newbuf .= '$'.$module_name."_share_write_permission=array('ROLE'=>". + constructTwoDimensionalCharIntSingleValueArray($mod_share_write_perm['ROLE']).",'GROUP'=>". + constructTwoDimensionalArray($mod_share_write_perm['GROUP']).");\n\n"; + } + // END + + $newbuf .= "?>"; + fputs($handle, $newbuf); + fclose($handle); + + //Populating Temp Tables + populateSharingtmptables($userid); + } + } +} + +/** Gives an array which contains the information for what all roles, groups and user data is to be shared with the spcified user for the specified module + + * @param $module -- module name:: Type varchar + * @param $userid -- user id:: Type integer + * @param $def_org_share -- default organization sharing permission array:: Type array + * @param $current_user_roles -- roleid:: Type varchar + * @param $parent_roles -- parent roles:: Type varchar + * @param $current_user_groups -- user id:: Type integer + * @returns $mod_share_permission -- array which contains the id of roles,group and users data shared with specifed user for the specified module + */ +function getUserModuleSharingObjects($module,$userid,$def_org_share,$current_user_roles,$parent_roles,$current_user_groups) +{ + global $adb; + + $mod_tabid=getTabid($module); + + $mod_share_permission; + $mod_share_read_permission=Array(); + $mod_share_write_permission=Array(); + $mod_share_read_permission['ROLE']=Array(); + $mod_share_write_permission['ROLE']=Array(); + $mod_share_read_permission['GROUP']=Array(); + $mod_share_write_permission['GROUP']=Array(); + + $share_id_members=Array(); + $share_id_groupmembers=Array(); + //If Sharing of leads is Private + if($def_org_share[$mod_tabid] == 3 || $def_org_share[$mod_tabid] == 0) + { + $role_read_per=Array(); + $role_write_per=Array(); + $rs_read_per=Array(); + $rs_write_per=Array(); + $grp_read_per=Array(); + $grp_write_per=Array(); + //Retreiving from vtiger_role to vtiger_role + $query="select vtiger_datashare_role2role.* from vtiger_datashare_role2role inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_role2role.shareid where vtiger_datashare_module_rel.tabid=? and vtiger_datashare_role2role.to_roleid=?"; + $result=$adb->pquery($query, array($mod_tabid, $current_user_roles)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_roleid=$adb->query_result($result,$i,'share_roleid'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_role_members=Array(); + $share_id_roles=Array(); + $share_id_roles[]=$share_roleid; + $share_id_role_members['ROLE']=$share_id_roles; + $share_id_members[$shareid]=$share_id_role_members; + + $share_permission=$adb->query_result($result,$i,'permission'); + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + } + if(! array_key_exists($share_roleid,$role_write_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_write_per[$share_roleid]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + + } + + } + + + + //Retreiving from role to rs + $parRoleList = array(); + foreach($parent_roles as $par_role_id) + { + array_push($parRoleList, $par_role_id); + } + array_push($parRoleList, $current_user_roles); + $query="select vtiger_datashare_role2rs.* from vtiger_datashare_role2rs inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_role2rs.shareid where vtiger_datashare_module_rel.tabid=? and vtiger_datashare_role2rs.to_roleandsubid in (". generateQuestionMarks($parRoleList) .")"; + $result=$adb->pquery($query, array($mod_tabid, $parRoleList)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_roleid=$adb->query_result($result,$i,'share_roleid'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_role_members=Array(); + $share_id_roles=Array(); + $share_id_roles[]=$share_roleid; + $share_id_role_members['ROLE']=$share_id_roles; + $share_id_members[$shareid]=$share_id_role_members; + + $share_permission=$adb->query_result($result,$i,'permission'); + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + } + if(! array_key_exists($share_roleid,$role_write_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_write_per[$share_roleid]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + + } + + } + + //Get roles from Role2Grp + $grpIterator=false; + $groupList = $current_user_groups; + + $query="select vtiger_datashare_role2group.* from vtiger_datashare_role2group inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_role2group.shareid where vtiger_datashare_module_rel.tabid=?"; + $qparams = array($mod_tabid); + if (count($groupList) > 0) { + $query .= " and vtiger_datashare_role2group.to_groupid in (". generateQuestionMarks($groupList) .")"; + array_push($qparams, $groupList); + } + $result=$adb->pquery($query, $qparams); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_roleid=$adb->query_result($result,$i,'share_roleid'); + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_role_members=Array(); + $share_id_roles=Array(); + $share_id_roles[]=$share_roleid; + $share_id_role_members['ROLE']=$share_id_roles; + $share_id_members[$shareid]=$share_id_role_members; + + $share_permission=$adb->query_result($result,$i,'permission'); + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + } + if(! array_key_exists($share_roleid,$role_write_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_write_per[$share_roleid]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + + } + + } + + + + //Retreiving from rs to vtiger_role + $query="select vtiger_datashare_rs2role.* from vtiger_datashare_rs2role inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_rs2role.shareid where vtiger_datashare_module_rel.tabid=? and vtiger_datashare_rs2role.to_roleid=?"; + $result=$adb->pquery($query, array($mod_tabid, $current_user_roles)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_rsid=$adb->query_result($result,$i,'share_roleandsubid'); + $share_roleids=getRoleAndSubordinatesRoleIds($share_rsid); + $share_permission=$adb->query_result($result,$i,'permission'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_role_members=Array(); + $share_id_roles=Array(); + foreach($share_roleids as $share_roleid) + { + $share_id_roles[]=$share_roleid; + + + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + } + if(! array_key_exists($share_roleid,$role_write_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_write_per[$share_roleid]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + + } + } + $share_id_role_members['ROLE']=$share_id_roles; + $share_id_members[$shareid]=$share_id_role_members; + + } + + + //Retreiving from rs to rs + $parRoleList = array(); + foreach($parent_roles as $par_role_id) + { + array_push($parRoleList, $par_role_id); + } + array_push($parRoleList, $current_user_roles); + $query="select vtiger_datashare_rs2rs.* from vtiger_datashare_rs2rs inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_rs2rs.shareid where vtiger_datashare_module_rel.tabid=? and vtiger_datashare_rs2rs.to_roleandsubid in (". generateQuestionMarks($parRoleList) .")"; + $result=$adb->pquery($query, array($mod_tabid, $parRoleList)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_rsid=$adb->query_result($result,$i,'share_roleandsubid'); + $share_roleids=getRoleAndSubordinatesRoleIds($share_rsid); + $share_permission=$adb->query_result($result,$i,'permission'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_role_members=Array(); + $share_id_roles=Array(); + foreach($share_roleids as $share_roleid) + { + + $share_id_roles[]=$share_roleid; + + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + } + if(! array_key_exists($share_roleid,$role_write_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_write_per[$share_roleid]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + + } + } + $share_id_role_members['ROLE']=$share_id_roles; + $share_id_members[$shareid]=$share_id_role_members; + + } + + //Get roles from Rs2Grp + + $query="select vtiger_datashare_rs2grp.* from vtiger_datashare_rs2grp inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_rs2grp.shareid where vtiger_datashare_module_rel.tabid=?"; + $qparams = array($mod_tabid); + if (count($groupList) > 0) { + $query .= " and vtiger_datashare_rs2grp.to_groupid in (". generateQuestionMarks($groupList) .")"; + array_push($qparams, $groupList); + } + $result=$adb->pquery($query, $qparams); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_rsid=$adb->query_result($result,$i,'share_roleandsubid'); + $share_roleids=getRoleAndSubordinatesRoleIds($share_rsid); + $share_permission=$adb->query_result($result,$i,'permission'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_role_members=Array(); + $share_id_roles=Array(); + + foreach($share_roleids as $share_roleid) + { + + $share_id_roles[]=$share_roleid; + + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + } + if(! array_key_exists($share_roleid,$role_write_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_write_per[$share_roleid]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_roleid,$role_read_per)) + { + + $share_role_users=getRoleUserIds($share_roleid); + $role_read_per[$share_roleid]=$share_role_users; + } + + } + } + $share_id_role_members['ROLE']=$share_id_roles; + $share_id_members[$shareid]=$share_id_role_members; + + + + } + $mod_share_read_permission['ROLE']=$role_read_per; + $mod_share_write_permission['ROLE']=$role_write_per; + + //Retreiving from the grp2role sharing + $query="select vtiger_datashare_grp2role.* from vtiger_datashare_grp2role inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_grp2role.shareid where vtiger_datashare_module_rel.tabid=? and vtiger_datashare_grp2role.to_roleid=?"; + $result=$adb->pquery($query, array($mod_tabid, $current_user_roles)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_grpid=$adb->query_result($result,$i,'share_groupid'); + $share_permission=$adb->query_result($result,$i,'permission'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_grp_members=Array(); + $share_id_grps=Array(); + $share_id_grps[]=$share_grpid; + + + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_grpid,$grp_read_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $share_grp_subgroups=$focusGrpUsers->group_subgroups; + $grp_read_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + } + } + if(! array_key_exists($share_grpid,$grp_write_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_write_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_write_per)) + { + $grp_write_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_grpid,$grp_read_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_read_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + } + + } + $share_id_grp_members['GROUP']=$share_id_grps; + $share_id_members[$shareid]=$share_id_grp_members; + + } + + //Retreiving from the grp2rs sharing + + $query="select vtiger_datashare_grp2rs.* from vtiger_datashare_grp2rs inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_grp2rs.shareid where vtiger_datashare_module_rel.tabid=? and vtiger_datashare_grp2rs.to_roleandsubid in (". generateQuestionMarks($parRoleList) .")"; + $result=$adb->pquery($query, array($mod_tabid, $parRoleList)); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_grpid=$adb->query_result($result,$i,'share_groupid'); + $share_permission=$adb->query_result($result,$i,'permission'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_grp_members=Array(); + $share_id_grps=Array(); + $share_id_grps[]=$share_grpid; + + + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_grpid,$grp_read_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_read_per[$share_grpid]=$share_grp_users; + + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + } + } + if(! array_key_exists($share_grpid,$grp_write_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_write_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_write_per)) + { + $grp_write_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_grpid,$grp_read_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_read_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + } + + } + $share_id_grp_members['GROUP']=$share_id_grps; + $share_id_members[$shareid]=$share_id_grp_members; + + } + + //Retreiving from the grp2grp sharing + + $query="select vtiger_datashare_grp2grp.* from vtiger_datashare_grp2grp inner join vtiger_datashare_module_rel on vtiger_datashare_module_rel.shareid=vtiger_datashare_grp2grp.shareid where vtiger_datashare_module_rel.tabid=?"; + $qparams = array($mod_tabid); + if (count($groupList) > 0) { + $query .= " and vtiger_datashare_grp2grp.to_groupid in (". generateQuestionMarks($groupList) .")"; + array_push($qparams, $groupList); + } + $result=$adb->pquery($query, $qparams); + $num_rows=$adb->num_rows($result); + for($i=0;$i<$num_rows;$i++) + { + $share_grpid=$adb->query_result($result,$i,'share_groupid'); + $share_permission=$adb->query_result($result,$i,'permission'); + + $shareid=$adb->query_result($result,$i,'shareid'); + $share_id_grp_members=Array(); + $share_id_grps=Array(); + $share_id_grps[]=$share_grpid; + + if($share_permission == 1) + { + if($def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_grpid,$grp_read_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_read_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + + } + } + } + if(! array_key_exists($share_grpid,$grp_write_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_write_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_write_per)) + { + $grp_write_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + + } + } + elseif($share_permission == 0 && $def_org_share[$mod_tabid] == 3) + { + if(! array_key_exists($share_grpid,$grp_read_per)) + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($share_grpid); + $share_grp_users=$focusGrpUsers->group_users; + $grp_read_per[$share_grpid]=$share_grp_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + if(! in_array($subgrpid,$share_id_grps)) + { + $share_id_grps[]=$subgrpid; + } + + } + } + + } + $share_id_grp_members['GROUP']=$share_id_grps; + $share_id_members[$shareid]=$share_id_grp_members; + + } + $mod_share_read_permission['GROUP']=$grp_read_per; + $mod_share_write_permission['GROUP']=$grp_write_per; + } + $mod_share_permission['read']=$mod_share_read_permission; + $mod_share_permission['write']=$mod_share_write_permission; + $mod_share_permission['sharingrules']=$share_id_members; + return $mod_share_permission; +} + +/** Gives an array which contains the information for what all roles, groups and user's related module data that is to be shared for the specified parent module and shared module + + * @param $par_mod -- parent module name:: Type varchar + * @param $share_mod -- shared module name:: Type varchar + * @param $userid -- user id:: Type integer + * @param $def_org_share -- default organization sharing permission array:: Type array + * @param $mod_sharingrule_members -- Sharing Rule Members array:: Type array + * @param $$mod_share_read_per -- Sharing Module Read Permission array:: Type array + * @param $$mod_share_write_per -- Sharing Module Write Permission array:: Type array + * @returns $related_mod_sharing_permission; -- array which contains the id of roles,group and users related module data to be shared + */ +function getRelatedModuleSharingArray($par_mod,$share_mod,$mod_sharingrule_members,$mod_share_read_per,$mod_share_write_per,$def_org_share) +{ + + global $adb; + $related_mod_sharing_permission=Array(); + $mod_share_read_permission=Array(); + $mod_share_write_permission=Array(); + + $mod_share_read_permission['ROLE']=Array(); + $mod_share_write_permission['ROLE']=Array(); + $mod_share_read_permission['GROUP']=Array(); + $mod_share_write_permission['GROUP']=Array(); + + $par_mod_id=getTabid($par_mod); + $share_mod_id=getTabid($share_mod); + + if($def_org_share[$share_mod_id] == 3 || $def_org_share[$share_mod_id] == 0) + { + + $role_read_per=Array(); + $role_write_per=Array(); + $grp_read_per=Array(); + $grp_write_per=Array(); + + + + foreach($mod_sharingrule_members as $sharingid => $sharingInfoArr) + { + $query = "select vtiger_datashare_relatedmodule_permission.* from vtiger_datashare_relatedmodule_permission inner join vtiger_datashare_relatedmodules on vtiger_datashare_relatedmodules.datashare_relatedmodule_id=vtiger_datashare_relatedmodule_permission.datashare_relatedmodule_id where vtiger_datashare_relatedmodule_permission.shareid=? and vtiger_datashare_relatedmodules.tabid=? and vtiger_datashare_relatedmodules.relatedto_tabid=?"; + $result=$adb->pquery($query, array($sharingid, $par_mod_id, $share_mod_id)); + $share_permission=$adb->query_result($result,0,'permission'); + + foreach($sharingInfoArr as $shareType => $shareEntArr) + { + foreach($shareEntArr as $key=>$shareEntId) + { + if($shareType == 'ROLE') + { + if($share_permission == 1) + { + if($def_org_share[$share_mod_id] == 3) + { + if(! array_key_exists($shareEntId,$role_read_per)) + { + if(array_key_exists($shareEntId,$mod_share_read_per['ROLE'])) + { + $share_role_users=$mod_share_read_per['ROLE'][$shareEntId]; + } + elseif(array_key_exists($shareEntId,$mod_share_write_per['ROLE'])) + { + $share_role_users=$mod_share_write_per['ROLE'][$shareEntId]; + } + else + { + + $share_role_users=getRoleUserIds($shareEntId); + } + + $role_read_per[$shareEntId]=$share_role_users; + + } + } + if(! array_key_exists($shareEntId,$role_write_per)) + { + if(array_key_exists($shareEntId,$mod_share_read_per['ROLE'])) + { + $share_role_users=$mod_share_read_per['ROLE'][$shareEntId]; + } + elseif(array_key_exists($shareEntId,$mod_share_write_per['ROLE'])) + { + $share_role_users=$mod_share_write_per['ROLE'][$shareEntId]; + } + else + { + + $share_role_users=getRoleUserIds($shareEntId); + + } + + $role_write_per[$shareEntId]=$share_role_users; + } + } + elseif($share_permission == 0 && $def_org_share[$share_mod_id] == 3) + { + if(! array_key_exists($shareEntId,$role_read_per)) + { + if(array_key_exists($shareEntId,$mod_share_read_per['ROLE'])) + { + $share_role_users=$mod_share_read_per['ROLE'][$shareEntId]; + } + elseif(array_key_exists($shareEntId,$mod_share_write_per['ROLE'])) + { + $share_role_users=$mod_share_write_per['ROLE'][$shareEntId]; + } + else + { + + $share_role_users=getRoleUserIds($shareEntId); + } + + $role_read_per[$shareEntId]=$share_role_users; + + } + + + } + + } + elseif($shareType == 'GROUP') + { + if($share_permission == 1) + { + if($def_org_share[$share_mod_id] == 3) + { + + if(! array_key_exists($shareEntId,$grp_read_per)) + { + if(array_key_exists($shareEntId,$mod_share_read_per['GROUP'])) + { + $share_grp_users=$mod_share_read_per['GROUP'][$shareEntId]; + } + elseif(array_key_exists($shareEntId,$mod_share_write_per['GROUP'])) + { + $share_grp_users=$mod_share_write_per['GROUP'][$shareEntId]; + } + else + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($shareEntId); + $share_grp_users=$focusGrpUsers->group_users; + + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + + } + + } + + $grp_read_per[$shareEntId]=$share_grp_users; + + } + } + if(! array_key_exists($shareEntId,$grp_write_per)) + { + if(! array_key_exists($shareEntId,$grp_write_per)) + { + if(array_key_exists($shareEntId,$mod_share_read_per['GROUP'])) + { + $share_grp_users=$mod_share_read_per['GROUP'][$shareEntId]; + } + elseif(array_key_exists($shareEntId,$mod_share_write_per['GROUP'])) + { + $share_grp_users=$mod_share_write_per['GROUP'][$shareEntId]; + } + else + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($shareEntId); + $share_grp_users=$focusGrpUsers->group_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_write_per)) + { + $grp_write_per[$subgrpid]=$subgrpusers; + } + + } + + } + + $grp_write_per[$shareEntId]=$share_grp_users; + + } + } + } + elseif($share_permission == 0 && $def_org_share[$share_mod_id] == 3) + { + if(! array_key_exists($shareEntId,$grp_read_per)) + { + if(array_key_exists($shareEntId,$mod_share_read_per['GROUP'])) + { + $share_grp_users=$mod_share_read_per['GROUP'][$shareEntId]; + } + elseif(array_key_exists($shareEntId,$mod_share_write_per['GROUP'])) + { + $share_grp_users=$mod_share_write_per['GROUP'][$shareEntId]; + } + else + { + $focusGrpUsers = new GetGroupUsers(); + $focusGrpUsers->getAllUsersInGroup($shareEntId); + $share_grp_users=$focusGrpUsers->group_users; + foreach($focusGrpUsers->group_subgroups as $subgrpid=>$subgrpusers) + { + if(! array_key_exists($subgrpid,$grp_read_per)) + { + $grp_read_per[$subgrpid]=$subgrpusers; + } + + } + + } + + $grp_read_per[$shareEntId]=$share_grp_users; + + } + + + } + } + } + } + } + $mod_share_read_permission['ROLE']=$role_read_per; + $mod_share_write_permission['ROLE']=$role_write_per; + $mod_share_read_permission['GROUP']=$grp_read_per; + $mod_share_write_permission['GROUP']=$grp_write_per; + } + + $related_mod_sharing_permission['read']=$mod_share_read_permission; + $related_mod_sharing_permission['write']=$mod_share_write_permission; + return $related_mod_sharing_permission; + + +} + + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructArray($var) +{ + if (is_array($var)) + { + $code = 'array('; + foreach ($var as $key => $value) + { + $code .= "'".$key."'=>".$value.','; + } + $code .= ')'; + return $code; + } +} + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructSingleStringValueArray($var) +{ + + $size = sizeof($var); + $i=1; + if (is_array($var)) + { + $code = 'array('; + foreach ($var as $key => $value) + { + if($i<$size) + { + $code .= $key."=>'".$value."',"; + } + else + { + $code .= $key."=>'".$value."'"; + } + $i++; + } + $code .= ')'; + return $code; + } +} + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructSingleStringKeyAndValueArray($var) +{ + + $size = sizeof($var); + $i=1; + if (is_array($var)) + { + $code = 'array('; + foreach ($var as $key => $value) + { + if($i<$size) + { + $code .= "'".$key."'=>".$value.","; + } + else + { + $code .= "'".$key."'=>".$value; + } + $i++; + } + $code .= ')'; + return $code; + } +} + + + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructSingleStringKeyValueArray($var) { + global $adb; + $size = sizeof($var); + $i=1; + if (is_array($var)) { + $code = 'array('; + foreach ($var as $key => $value) { + //fix for signatue quote(') issue + $value=$adb->sql_escape_string($value); + if($i<$size) { + $code .= "'".$key."'=>'".$value."',"; + } else { + $code .= "'".$key."'=>'".$value."'"; + } + $i++; + } + $code .= ')'; + return $code; + } +} + + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructSingleArray($var) +{ + if (is_array($var)) + { + $code = 'array('; + foreach ($var as $value) + { + $code .= $value.','; + } + $code .= ')'; + return $code; + } +} + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructSingleCharArray($var) +{ + if (is_array($var)) + { + $code = "array("; + foreach ($var as $value) + { + $code .="'".$value."',"; + } + $code .= ")"; + return $code; + } +} + + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructTwoDimensionalArray($var) +{ + if (is_array($var)) + { + $code = 'array('; + foreach ($var as $key => $secarr) + { + $code .= $key.'=>array('; + foreach($secarr as $seckey => $secvalue) + { + $code .= $seckey.'=>'.$secvalue.','; + } + $code .= '),'; + } + $code .= ')'; + return $code; + } +} + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructTwoDimensionalValueArray($var) +{ + if (is_array($var)) + { + $code = 'array('; + foreach ($var as $key => $secarr) + { + $code .= $key.'=>array('; + foreach($secarr as $seckey => $secvalue) + { + $code .= $secvalue.','; + } + $code .= '),'; + } + $code .= ')'; + return $code; + } +} + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructTwoDimensionalCharIntSingleArray($var) +{ + if (is_array($var)) + { + $code = "array("; + foreach ($var as $key => $secarr) + { + $code .= "'".$key."'=>array("; + foreach($secarr as $seckey => $secvalue) + { + $code .= $seckey.","; + } + $code .= "),"; + } + $code .= ")"; + return $code; + } +} + +/** Converts the input array to a single string to facilitate the writing of the input array in a flat file + + * @param $var -- input array:: Type array + * @returns $code -- contains the whole array in a single string:: Type array + */ +function constructTwoDimensionalCharIntSingleValueArray($var) +{ + if (is_array($var)) + { + $code = "array("; + foreach ($var as $key => $secarr) + { + $code .= "'".$key."'=>array("; + foreach($secarr as $seckey => $secvalue) + { + $code .= $secvalue.","; + } + $code .= "),"; + } + $code .= ")"; + return $code; + } +} + + +/** Function to populate the read/wirte Sharing permissions data of user/groups for the specified user into the database + * @param $userid -- user id:: Type integer + */ + +function populateSharingtmptables($userid) +{ + global $adb; + require('user_privileges/sharing_privileges_'.$userid.'.php'); + //Deleting from the existing vtiger_tables + $table_arr=Array('vtiger_tmp_read_user_sharing_per', 'vtiger_tmp_write_user_sharing_per','vtiger_tmp_read_group_sharing_per','vtiger_tmp_write_group_sharing_per','vtiger_tmp_read_user_rel_sharing_per','vtiger_tmp_write_user_rel_sharing_per','vtiger_tmp_read_group_rel_sharing_per','vtiger_tmp_write_group_rel_sharing_per'); + foreach($table_arr as $tabname) + { + $query = "delete from ".$tabname." where userid=?"; + $adb->pquery($query, array($userid)); + } + + // Look up for modules for which sharing access is enabled. + $sharingArray = Array('Emails'); + $otherModules = getSharingModuleList(); + $sharingArray = array_merge($sharingArray, $otherModules); + + foreach($sharingArray as $module) + { + $module_sharing_read_permvar = $module.'_share_read_permission'; + $module_sharing_write_permvar = $module.'_share_write_permission'; + + populateSharingPrivileges('USER',$userid,$module,'read', $$module_sharing_read_permvar ); + populateSharingPrivileges('USER',$userid,$module,'write', $$module_sharing_write_permvar ); + populateSharingPrivileges('GROUP',$userid,$module,'read', $$module_sharing_read_permvar ); + populateSharingPrivileges('GROUP',$userid,$module,'write', $$module_sharing_write_permvar ); + } + //Populating Values into the temp related sharing tables + foreach($related_module_share as $rel_tab_id => $tabid_arr) + { + $rel_tab_name=getTabname($rel_tab_id); + foreach($tabid_arr as $taid) + { + $tab_name=getTabname($taid); + + $relmodule_sharing_read_permvar = $tab_name.'_'.$rel_tab_name.'_share_read_permission'; + $relmodule_sharing_write_permvar = $tab_name.'_'.$rel_tab_name.'_share_write_permission'; + + populateRelatedSharingPrivileges('USER',$userid,$tab_name,$rel_tab_name,'read', $$relmodule_sharing_read_permvar); + populateRelatedSharingPrivileges('USER',$userid,$tab_name,$rel_tab_name,'write', $$relmodule_sharing_write_permvar); + populateRelatedSharingPrivileges('GROUP',$userid,$tab_name,$rel_tab_name,'read', $$relmodule_sharing_read_permvar); + populateRelatedSharingPrivileges('GROUP',$userid,$tab_name,$rel_tab_name,'write', $$relmodule_sharing_write_permvar); + } + } +} + +/** Function to populate the read/wirte Sharing permissions data for the specified user into the database + * @param $userid -- user id:: Type integer + * @param $enttype -- can have the value of User or Group:: Type varchar + * @param $module -- module name:: Type varchar + * @param $pertype -- can have the value of read or write:: Type varchar + * @param $var_name_arr - Variable to use instead of including the sharing access again + */ +function populateSharingPrivileges($enttype,$userid,$module,$pertype, $var_name_arr=false) +{ + global $adb; + $tabid=getTabid($module); + + if(!$var_name_arr) { + require('user_privileges/sharing_privileges_'.$userid.'.php'); + } + + if($enttype=='USER') + { + if($pertype =='read') + { + $table_name='vtiger_tmp_read_user_sharing_per'; + $var_name=$module.'_share_read_permission'; + } + elseif($pertype == 'write') + { + $table_name='vtiger_tmp_write_user_sharing_per'; + $var_name=$module.'_share_write_permission'; + } + // Lookup for the variable if not set through function argument + if(!$var_name_arr) $var_name_arr=$$var_name; + $user_arr=Array(); + if(sizeof($var_name_arr['ROLE']) > 0) + { + foreach($var_name_arr['ROLE'] as $roleid=>$roleusers) + { + + foreach($roleusers as $user_id) + { + if(! in_array($user_id,$user_arr)) + { + $query="insert into ".$table_name." values(?,?,?)"; + $adb->pquery($query, array($userid, $tabid, $user_id)); + $user_arr[]=$user_id; + } + } + } + } + if(sizeof($var_name_arr['GROUP']) > 0) + { + foreach($var_name_arr['GROUP'] as $grpid=>$grpusers) + { + foreach($grpusers as $user_id) + { + if(! in_array($user_id,$user_arr)) + { + $query="insert into ".$table_name." values(?,?,?)"; + $adb->pquery($query, array($userid, $tabid, $user_id)); + $user_arr[]=$user_id; + } + } + } + } + + + } + elseif($enttype=='GROUP') + { + if($pertype =='read') + { + $table_name='vtiger_tmp_read_group_sharing_per'; + $var_name=$module.'_share_read_permission'; + } + elseif($pertype == 'write') + { + $table_name='vtiger_tmp_write_group_sharing_per'; + $var_name=$module.'_share_write_permission'; + } + // Lookup for the variable if not set through function argument + if(!$var_name_arr) $var_name_arr=$$var_name; + $grp_arr=Array(); + if(sizeof($var_name_arr['GROUP']) > 0) + { + + foreach($var_name_arr['GROUP'] as $grpid=>$grpusers) + { + if(! in_array($grpid,$grp_arr)) + { + $query="insert into ".$table_name." values(?,?,?)"; + $adb->pquery($query, array($userid, $tabid, $grpid)); + $grp_arr[]=$grpid; + } + } + } + + } + +} + + +/** Function to populate the read/wirte Sharing permissions related module data for the specified user into the database + * @param $userid -- user id:: Type integer + * @param $enttype -- can have the value of User or Group:: Type varchar + * @param $module -- module name:: Type varchar + * @param $relmodule -- related module name:: Type varchar + * @param $pertype -- can have the value of read or write:: Type varchar + * @param $var_name_arr - Variable to use instead of including the sharing access again + */ + +function populateRelatedSharingPrivileges($enttype,$userid,$module,$relmodule,$pertype, $var_name_arr=false) +{ + global $adb; + $tabid=getTabid($module); + $reltabid=getTabid($relmodule); + + if(!$var_name_arr) { + require('user_privileges/sharing_privileges_'.$userid.'.php'); + } + + if($enttype=='USER') + { + if($pertype =='read') + { + $table_name='vtiger_tmp_read_user_rel_sharing_per'; + $var_name=$module.'_'.$relmodule.'_share_read_permission'; + } + elseif($pertype == 'write') + { + $table_name='vtiger_tmp_write_user_rel_sharing_per'; + $var_name=$module.'_'.$relmodule.'_share_write_permission'; + } + // Lookup for the variable if not set through function argument + if(!$var_name_arr) $var_name_arr=$$var_name; + $user_arr=Array(); + if(sizeof($var_name_arr['ROLE']) > 0) + { + foreach($var_name_arr['ROLE'] as $roleid=>$roleusers) + { + + foreach($roleusers as $user_id) + { + if(! in_array($user_id,$user_arr)) + { + $query="insert into ".$table_name." values(?,?,?,?)"; + $adb->pquery($query, array($userid, $tabid, $reltabid, $user_id)); + $user_arr[]=$user_id; + } + } + } + } + if(sizeof($var_name_arr['GROUP']) > 0) + { + foreach($var_name_arr['GROUP'] as $grpid=>$grpusers) + { + foreach($grpusers as $user_id) + { + if(! in_array($user_id,$user_arr)) + { + $query="insert into ".$table_name." values(?,?,?,?)"; + $adb->pquery($query, array($userid, $tabid, $reltabid, $user_id)); + $user_arr[]=$user_id; + } + } + } + } + + + } + elseif($enttype=='GROUP') + { + if($pertype =='read') + { + $table_name='vtiger_tmp_read_group_rel_sharing_per'; + $var_name=$module.'_'.$relmodule.'_share_read_permission'; + } + elseif($pertype == 'write') + { + $table_name='vtiger_tmp_write_group_rel_sharing_per'; + $var_name=$module.'_'.$relmodule.'_share_write_permission'; + } + // Lookup for the variable if not set through function argument + if(!$var_name_arr) $var_name_arr=$$var_name; + $grp_arr=Array(); + if(sizeof($var_name_arr['GROUP']) > 0) + { + + foreach($var_name_arr['GROUP'] as $grpid=>$grpusers) + { + if(! in_array($grpid,$grp_arr)) + { + $query="insert into ".$table_name." values(?,?,?,?)"; + $adb->pquery($query, array($userid, $tabid, $reltabid, $grpid)); + $grp_arr[]=$grpid; + } + } + } + + } + +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DefaultDataPopulator.php b/oss/vtiger/trunk/modules/Users/DefaultDataPopulator.php new file mode 100644 index 00000000..73da4be5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DefaultDataPopulator.php @@ -0,0 +1,2541 @@ +log = LoggerManager::getLogger('DefaultDataPopulator'); + $this->db = PearDatabase::getInstance(); + } + + var $new_schema = true; + + /** Function to populate the default required data during installation + */ + function create_tables () { + global $app_strings; + + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (3,'Home',0,1,'Home',0,1,0)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (7,'Leads',0,4,'Leads',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (6,'Accounts',0,5,'Accounts',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (4,'Contacts',0,6,'Contacts',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (2,'Potentials',0,7,'Potentials',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (8,'Documents',0,9,'Documents',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (9,'Calendar',0,3,'Calendar',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (10,'Emails',0,10,'Emails',0,1,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (13,'HelpDesk',0,11,'HelpDesk',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (14,'Products',0,8,'Products',0,1,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (1,'Dashboard',0,12,'Dashboards',0,1,0)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (15,'Faq',0,14,'Faq',0,1,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (16,'Events',2,13,'Events',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (18,'Vendors',0,15,'Vendors',0,1,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (19,'PriceBooks',0,16,'PriceBooks',0,1,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (20,'Quotes',0,17,'Quotes',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (21,'PurchaseOrder',0,18,'PurchaseOrder',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (22,'SalesOrder',0,19,'SalesOrder',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (23,'Invoice',0,20,'Invoice',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (24,'Rss',0,21,'Rss',0,1,0)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (25,'Reports',0,22,'Reports',0,1,0)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (26,'Campaigns',0,23,'Campaigns',0,0,1)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (27,'Portal',0,24,'Portal',0,1,0)"); + $this->db->query("INSERT INTO vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) VALUES (28,'Webmails',0,25,'Webmails',0,1,1)"); + $this->db->query("insert into vtiger_tab(tabid,name,presence,tabsequence,tablabel,customized,ownedby,isentitytype) values (29,'Users',0,26,'Users',0,1,0)"); + + // Populate the vtiger_blocks vtiger_table + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",2,'LBL_OPPORTUNITY_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",2,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",2,'LBL_DESCRIPTION_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",4,'LBL_CONTACT_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",4,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",4,'LBL_CUSTOMER_PORTAL_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",4,'LBL_ADDRESS_INFORMATION',4,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",4,'LBL_DESCRIPTION_INFORMATION',5,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",6,'LBL_ACCOUNT_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",6,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",6,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",6,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",7,'LBL_LEAD_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",7,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",7,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",7,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",8,'LBL_NOTE_INFORMATION',1,0,0,0,0,0,1,0)"); + $fileblockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$fileblockid.",8,'LBL_FILE_INFORMATION',3,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",9,'LBL_TASK_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",9,'',2,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",10,'LBL_EMAIL_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",10,'',2,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",10,'',3,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",10,'',4,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",13,'LBL_TICKET_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",13,'',2,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",13,'LBL_CUSTOM_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",13,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",13,'LBL_TICKET_RESOLUTION',5,0,0,1,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",13,'LBL_COMMENTS',6,0,0,1,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",14,'LBL_PRODUCT_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",14,'LBL_PRICING_INFORMATION',2,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",14,'LBL_STOCK_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",14,'LBL_CUSTOM_INFORMATION',4,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",14,'LBL_IMAGE_INFORMATION',5,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",14,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",15,'LBL_FAQ_INFORMATION',1,0,0,0,0,0,1,0)"); + //$this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",15,'',2,1,0,0,0,0,1,0)"); + //$this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",15,'',3,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",15,'LBL_COMMENT_INFORMATION',4,0,0,1,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",16,'LBL_EVENT_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",16,'',2,1,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",16,'',3,1,0,0,0,0,1,0)"); + $vendorbasicinfo = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$vendorbasicinfo.",18,'LBL_VENDOR_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",18,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $vendoraddressblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$vendoraddressblock.",18,'LBL_VENDOR_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + $vendordescriptionblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$vendordescriptionblock.",18,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0,1,0)"); + $pricebookbasicblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$pricebookbasicblock.",19,'LBL_PRICEBOOK_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",19,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $pricebookdescription = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$pricebookdescription.",19,'LBL_DESCRIPTION_INFORMATION',3,0,0,0,0,0,1,0)"); + $quotesbasicblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$quotesbasicblock.",20,'LBL_QUOTE_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",20,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $quotesaddressblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$quotesaddressblock.",20,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",20,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0,1,0)"); + $quotetermsblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$quotetermsblock.",20,'LBL_TERMS_INFORMATION',5,0,0,0,0,0,1,0)"); + $quotedescription = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$quotedescription.",20,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0,1,0)"); + $pobasicblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$pobasicblock.",21,'LBL_PO_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",21,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $poaddressblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$poaddressblock.",21,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",21,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0,1,0)"); + $potermsblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$potermsblock.",21,'LBL_TERMS_INFORMATION',5,0,0,0,0,0,1,0)"); + $podescription = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$podescription.",21,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0,1,0)"); + $sobasicblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$sobasicblock .",22,'LBL_SO_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",22,'LBL_CUSTOM_INFORMATION',3,0,0,0,0,0,1,0)"); + $soaddressblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$soaddressblock.",22,'LBL_ADDRESS_INFORMATION',4,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",22,'LBL_RELATED_PRODUCTS',5,0,0,0,0,0,1,0)"); + $sotermsblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$sotermsblock.",22,'LBL_TERMS_INFORMATION',6,0,0,0,0,0,1,0)"); + $sodescription = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$sodescription.",22,'LBL_DESCRIPTION_INFORMATION',7,0,0,0,0,0,1,0)"); + $invoicebasicblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$invoicebasicblock.",23,'LBL_INVOICE_INFORMATION',1,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",23,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $invoiceaddressblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$invoiceaddressblock.",23,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",23,'LBL_RELATED_PRODUCTS',4,0,0,0,0,0,1,0)"); + $invoicetermsblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$invoicetermsblock.",23,'LBL_TERMS_INFORMATION',5,0,0,0,0,0,1,0)"); + $invoicedescription = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$invoicedescription.",23,'LBL_DESCRIPTION_INFORMATION',6,0,0,0,0,0,1,0)"); + $imageblockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$imageblockid.",4,'LBL_IMAGE_INFORMATION',6,0,0,0,0,0,1,0)"); + $campaignbasicblockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$campaignbasicblockid.",26,'LBL_CAMPAIGN_INFORMATION',1,0,0,0,0,0,1,0)"); + $campaigncustomblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$campaigncustomblock.",26,'LBL_CUSTOM_INFORMATION',2,0,0,0,0,0,1,0)"); + $campaignexpectedandactualsblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$campaignexpectedandactualsblock.",26,'LBL_EXPECTATIONS_AND_ACTUALS',3,0,0,0,0,0,1,0)"); + $userloginandroleblockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$userloginandroleblockid.",29,'LBL_USERLOGIN_ROLE',1,0,0,0,0,0,1,0)"); + $usermoreinfoblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$usermoreinfoblock.",29,'LBL_MORE_INFORMATION',2,0,0,0,0,0,1,0)"); + $useraddressblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$useraddressblock.",29,'LBL_ADDRESS_INFORMATION',3,0,0,0,0,0,1,0)"); + //Added an extra block for new UI Settings in Campaigns module + $campaidndescriptionblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$campaidndescriptionblock.",26,'LBL_DESCRIPTION_INFORMATION',4,0,0,0,0,0,1,0)"); + $userblockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$userblockid.",29,'LBL_USER_IMAGE_INFORMATION',4,0,0,0,0,0,1,0)"); //Added a New Block User Image Info in Users Module + $useradvanceblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$useradvanceblock .",29,'LBL_USER_ADV_OPTIONS',5,0,0,0,0,0,1,0)"); //Added a New Block User Image Info in Users Module + //Added block 'File Information' to Documents module + $desc_blockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$desc_blockid.",8,'LBL_DESCRIPTION',2,0,0,0,0,0,1,0)"); + //Added block for storing the Recurring Inovice Informaiton in SalesOrder + $sorecurringinvoiceblock = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("insert into vtiger_blocks values (".$sorecurringinvoiceblock.",22,'Recurring Invoice Information',2,0,0,0,0,0,1,0)"); + //Added to support custom fields for Calendar + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",9,'LBL_CUSTOM_INFORMATION',3,0,0,0,0,0,1,0)"); + $this->db->query("insert into vtiger_blocks values (".$this->db->getUniqueID('vtiger_blocks').",16,'LBL_CUSTOM_INFORMATION',4,0,0,0,0,0,1,0)"); + + //Account Details -- START + //Block9 + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'accountname','vtiger_account',1,'2','accountname','Account Name',1,0,0,100,1,9,1,'V~M',0,1,'BAS',0)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'account_no','vtiger_account',1,'4','account_no','Account No',1,0,0,100,2,9,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'phone','vtiger_account',1,'11','phone','Phone',1,2,0,100,4,9,1,'V~O',2,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'website','vtiger_account',1,'17','website','Website',1,2,0,100,3,9,1,'V~O',2,3,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'fax','vtiger_account',1,'1','fax','Fax',1,2,0,100,6,9,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'tickersymbol','vtiger_account',1,'1','tickersymbol','Ticker Symbol',1,2,0,100,5,9,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'otherphone','vtiger_account',1,'11','otherphone','Other Phone',1,2,0,100,8,9,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'parentid','vtiger_account',1,'51','account_id','Member Of',1,2,0,100,7,9,1,'I~O',1,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'email1','vtiger_account',1,'13','email1','Email',1,2,0,100,10,9,1,'E~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'employees','vtiger_account',1,'7','employees','Employees',1,2,0,100,9,9,1,'I~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'email2','vtiger_account',1,'13','email2','Other Email',1,2,0,100,11,9,1,'E~O',1,null,'ADV',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ownership','vtiger_account',1,'1','ownership','Ownership',1,2,0,100,12,9,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'rating','vtiger_account',1,'15','rating','Rating',1,2,0,100,14,9,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'industry','vtiger_account',1,'15','industry','industry',1,2,0,100,13,9,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'siccode','vtiger_account',1,'1','siccode','SIC Code',1,2,0,100,16,9,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'account_type','vtiger_account',1,'15','accounttype','Type',1,2,0,100,15,9,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'annualrevenue','vtiger_account',1,'71','annual_revenue','Annual Revenue',1,2,0,100,18,9,1,'I~O',1,null,'ADV',1)"); + //Added vtiger_field emailoptout for vtiger_accounts -- after 4.2 patch2 + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'emailoptout','vtiger_account',1,'56','emailoptout','Email Opt Out',1,2,0,100,17,9,1,'C~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'notify_owner','vtiger_account',1,56,'notify_owner','Notify Owner',1,2,0,10,20,9,1,'C~O',1,NULL,'ADV',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,19,9,1,'V~M',0,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,22,9,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,21,9,2,'T~O',3,null,'BAS',0)"); + + //Block 11 + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'bill_street','vtiger_accountbillads',1,'21','bill_street','Billing Address',1,2,0,100,1,11,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ship_street','vtiger_accountshipads',1,'21','ship_street','Shipping Address',1,2,0,100,2,11,1,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'bill_city','vtiger_accountbillads',1,'1','bill_city','Billing City',1,2,0,100,5,11,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ship_city','vtiger_accountshipads',1,'1','ship_city','Shipping City',1,2,0,100,6,11,1,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'bill_state','vtiger_accountbillads',1,'1','bill_state','Billing State',1,2,0,100,7,11,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ship_state','vtiger_accountshipads',1,'1','ship_state','Shipping State',1,2,0,100,8,11,1,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'bill_code','vtiger_accountbillads',1,'1','bill_code','Billing Code',1,2,0,100,9,11,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ship_code','vtiger_accountshipads',1,'1','ship_code','Shipping Code',1,2,0,100,10,11,1,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'bill_country','vtiger_accountbillads',1,'1','bill_country','Billing Country',1,2,0,100,11,11,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ship_country','vtiger_accountshipads',1,'1','ship_country','Shipping Country',1,2,0,100,12,11,1,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'bill_pobox','vtiger_accountbillads',1,'1','bill_pobox','Billing Po Box',1,2,0,100,3,11,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'ship_pobox','vtiger_accountshipads',1,'1','ship_pobox','Shipping Po Box',1,2,0,100,4,11,1,'V~O',1,null,'BAS',1)"); + + //Block12 + $this->db->query("insert into vtiger_field values (6,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,12,1,'V~O',1,null,'BAS',1)"); + + //Account Details -- END + + //Lead Details --- START + //Block13 -- Start + + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'salutation','vtiger_leaddetails',1,'55','salutationtype','Salutation',1,0,0,100,1,13,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'firstname','vtiger_leaddetails',1,'55','firstname','First Name',1,2,0,100,2,13,1,'V~O',2,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'lead_no','vtiger_leaddetails',1,'4','lead_no','Lead No',1,0,0,100,3,13,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'phone','vtiger_leadaddress',1,'11','phone','Phone',1,2,0,100,5,13,1,'V~O',2,4,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'lastname','vtiger_leaddetails',1,'255','lastname','Last Name',1,0,0,100,4,13,1,'V~M',0,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'mobile','vtiger_leadaddress',1,'1','mobile','Mobile',1,2,0,100,7,13,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'company','vtiger_leaddetails',1,'2','company','Company',1,2,0,100,6,13,1,'V~M',2,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'fax','vtiger_leadaddress',1,'1','fax','Fax',1,2,0,100,9,13,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'designation','vtiger_leaddetails',1,'1','designation','Designation',1,2,0,100,8,13,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'email','vtiger_leaddetails',1,'13','email','Email',1,2,0,100,11,13,1,'E~O',2,5,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'leadsource','vtiger_leaddetails',1,'15','leadsource','Lead Source',1,2,0,100,10,13,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'website','vtiger_leadsubdetails',1,'17','website','Website',1,2,0,100,13,13,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'industry','vtiger_leaddetails',1,'15','industry','Industry',1,2,0,100,12,13,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'leadstatus','vtiger_leaddetails',1,'15','leadstatus','Lead Status',1,2,0,100,15,13,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'annualrevenue','vtiger_leaddetails',1,'71','annualrevenue','Annual Revenue',1,2,0,100,14,13,1,'I~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'rating','vtiger_leaddetails',1,'15','rating','Rating',1,2,0,100,17,13,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'noofemployees','vtiger_leaddetails',1,'1','noofemployees','No Of Employees',1,2,0,100,16,13,1,'I~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,19,13,1,'V~M',0,6,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'yahooid','vtiger_leaddetails',1,'13','yahooid','Yahoo Id',1,2,0,100,18,13,1,'E~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,21,13,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,20,13,2,'T~O',3,null,'BAS',0)"); + //Block13 -- End + + //Block15 -- Start + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'lane','vtiger_leadaddress',1,'21','lane','Street',1,2,0,100,1,15,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'code','vtiger_leadaddress',1,'1','code','Postal Code',1,2,0,100,3,15,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'city','vtiger_leadaddress',1,'1','city','City',1,2,0,100,4,15,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'country','vtiger_leadaddress',1,'1','country','Country',1,2,0,100,5,15,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'state','vtiger_leadaddress',1,'1','state','State',1,2,0,100,6,15,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'pobox','vtiger_leadaddress',1,'1','pobox','Po Box',1,2,0,100,2,15,1,'V~O',1,null,'BAS',1)"); + //Block15 --End + + //Block16 -- Start + $this->db->query("insert into vtiger_field values (7,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,16,1,'V~O',1,null,'BAS',1)"); + //Block16 -- End + + //Lead Details -- END + + //Contact Details -- START + //Block4 -- Start + + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'salutation','vtiger_contactdetails',1,'55','salutationtype','Salutation',1,0,0,100,1,4,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'firstname','vtiger_contactdetails',1,'55','firstname','First Name',1,2,0,100,2,4,1,'V~O',2,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'contact_no','vtiger_contactdetails',1,'4','contact_no','Contact Id',1,0,0,100,3,4,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'phone','vtiger_contactdetails',1,'11','phone','Office Phone',1,2,0,100,5,4,1,'V~O',2,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'lastname','vtiger_contactdetails',1,'255','lastname','Last Name',1,0,0,100,4,4,1,'V~M',0,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mobile','vtiger_contactdetails',1,'1','mobile','Mobile',1,2,0,100,7,4,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'accountid','vtiger_contactdetails',1,'51','account_id','Account Name',1,0,0,100,6,4,1,'I~O',2,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'homephone','vtiger_contactsubdetails',1,'11','homephone','Home Phone',1,2,0,100,9,4,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'leadsource','vtiger_contactsubdetails',1,'15','leadsource','Lead Source',1,2,0,100,8,4,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'otherphone','vtiger_contactsubdetails',1,'11','otherphone','Other Phone',1,2,0,100,11,4,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'title','vtiger_contactdetails',1,'1','title','Title',1,2,0,100,10,4,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'fax','vtiger_contactdetails',1,'1','fax','Fax',1,2,0,100,13,4,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'department','vtiger_contactdetails',1,'1','department','Department',1,2,0,100,12,4,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'birthday','vtiger_contactsubdetails',1,'5','birthday','Birthdate',1,2,0,100,16,4,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'email','vtiger_contactdetails',1,'13','email','Email',1,2,0,100,15,4,1,'E~O',2,5,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'reportsto','vtiger_contactdetails',1,'57','contact_id','Reports To',1,2,0,100,18,4,1,'V~O',1,null,'ADV',0)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'assistant','vtiger_contactsubdetails',1,'1','assistant','Assistant',1,2,0,100,17,4,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'yahooid','vtiger_contactdetails',1,'13','yahooid','Yahoo Id',1,2,0,100,20,4,1,'E~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'assistantphone','vtiger_contactsubdetails',1,'11','assistantphone','Assistant Phone',1,2,0,100,19,4,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'donotcall','vtiger_contactdetails',1,'56','donotcall','Do Not Call',1,2,0,100,22,4,1,'C~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'emailoptout','vtiger_contactdetails',1,'56','emailoptout','Email Opt Out',1,2,0,100,21,4,1,'C~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,24,4,1,'V~M',0,6,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'reference','vtiger_contactdetails',1,'56','reference','Reference',1,2,0,10,23,4,1,'C~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'notify_owner','vtiger_contactdetails',1,'56','notify_owner','Notify Owner',1,2,0,10,26,4,1,'C~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,25,4,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,27,4,2,'T~O',3,null,'BAS',0)"); + //Block4 -- End + + //Block6 - Begin Customer Portal + + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'portal','vtiger_customerdetails',1,'56','portal','Portal User',1,2,0,100,1,6,1,'C~O',1,null,'ADV',0)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'support_start_date','vtiger_customerdetails',1,'5','support_start_date','Support Start Date',1,2,0,100,2,6,1,'D~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'support_end_date','vtiger_customerdetails',1,'5','support_end_date','Support End Date',1,2,0,100,3,6,1,'D~O~OTH~GE~support_start_date~Support Start Date',1,null,'ADV',1)"); + + //Block6 - End Customer Portal + + //Block 7 -- Start + + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mailingstreet','vtiger_contactaddress',1,'21','mailingstreet','Mailing Street',1,2,0,100,1,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'otherstreet','vtiger_contactaddress',1,'21','otherstreet','Other Street',1,2,0,100,2,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mailingcity','vtiger_contactaddress',1,'1','mailingcity','Mailing City',1,2,0,100,5,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'othercity','vtiger_contactaddress',1,'1','othercity','Other City',1,2,0,100,6,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mailingstate','vtiger_contactaddress',1,'1','mailingstate','Mailing State',1,2,0,100,7,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'otherstate','vtiger_contactaddress',1,'1','otherstate','Other State',1,2,0,100,8,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mailingzip','vtiger_contactaddress',1,'1','mailingzip','Mailing Zip',1,2,0,100,9,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'otherzip','vtiger_contactaddress',1,'1','otherzip','Other Zip',1,2,0,100,10,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mailingcountry','vtiger_contactaddress',1,'1','mailingcountry','Mailing Country',1,2,0,100,11,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'othercountry','vtiger_contactaddress',1,'1','othercountry','Other Country',1,2,0,100,12,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'mailingpobox','vtiger_contactaddress',1,'1','mailingpobox','Mailing Po Box',1,2,0,100,3,7,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'otherpobox','vtiger_contactaddress',1,'1','otherpobox','Other Po Box',1,2,0,100,4,7,1,'V~O',1,null,'BAS',1)"); + //Block7 -- End + + //ContactImageInformation + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'imagename','vtiger_contactdetails',1,'69','imagename','Contact Image',1,2,0,100,1,$imageblockid,1,'V~O',3,null,'ADV',0)"); + + + //Block8 -- Start + $this->db->query("insert into vtiger_field values (4,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,8,1,'V~O',1,null,'BAS',1)"); + //Block8 -- End + //Contact Details -- END + + //Potential Details -- START + //Block1 -- Start + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'potentialname','vtiger_potential',1,'2','potentialname','Potential Name',1,0,0,100,1,1,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'potential_no','vtiger_potential',1,'4','potential_no','Potential No',1,0,0,100,2,1,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'amount','vtiger_potential',1,71,'amount','Amount',1,2,0,100,4,1,1,'N~O',2,5,'BAS',1)"); + //changed for b2c model + $fieldid = $this->db->getUniqueID("vtiger_field"); + $this->db->query("insert into vtiger_field values (2,$fieldid,'related_to','vtiger_potential',1,'10','related_to','Related To',1,0,0,100,3,1,1,'V~M',0,2,'BAS',1)"); + $this->db->query("insert into vtiger_fieldmodulerel (fieldid, module, relmodule, status, sequence) values ($fieldid, 'Potentials', 'Accounts', NULL, 0), ($fieldid, 'Potentials', 'Contacts', NULL, 1)"); + //b2c model changes end + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'closingdate','vtiger_potential',1,'23','closingdate','Expected Close Date',1,2,0,100,7,1,1,'D~M',2,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'potentialtype','vtiger_potential',1,'15','opportunity_type','Type',1,2,0,100,6,1,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'nextstep','vtiger_potential',1,'1','nextstep','Next Step',1,2,0,100,9,1,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'leadsource','vtiger_potential',1,'15','leadsource','Lead Source',1,2,0,100,8,1,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'sales_stage','vtiger_potential',1,'15','sales_stage','Sales Stage',1,2,0,100,11,1,1,'V~M',2,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,2,0,100,10,1,1,'V~M',0,6,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'probability','vtiger_potential',1,'9','probability','Probability',1,2,0,100,13,1,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'campaignid','vtiger_potential',1,'58','campaignid','Campaign Source',1,2,0,100,12,1,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,15,1,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,14,1,2,'T~O',3,null,'BAS',0)"); + + //Block1 -- End + + //Block3 -- Start + $this->db->query("insert into vtiger_field values (2,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,3,1,'V~O',1,null,'BAS',1)"); + //Block3 -- End + //Potential Details -- END + + //campaign entries being added + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'campaignname','vtiger_campaign',1,'2','campaignname','Campaign Name',1,0,0,100,1,$campaignbasicblockid,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'campaign_no','vtiger_campaign',1,'4','campaign_no','Campaign No',1,0,0,100,2,$campaignbasicblockid,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'campaigntype','vtiger_campaign',1,15,'campaigntype','Campaign Type',1,2,0,100,5,$campaignbasicblockid,1,'V~O',2,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'product_id','vtiger_campaign',1,59,'product_id','Product',1,2,0,100,6,$campaignbasicblockid,1,'I~O',2,5,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'campaignstatus','vtiger_campaign',1,15,'campaignstatus','Campaign Status',1,2,0,100,4,$campaignbasicblockid,1,'V~O',2,6,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'closingdate','vtiger_campaign',1,'23','closingdate','Expected Close Date',1,2,0,100,8,$campaignbasicblockid,1,'D~M',2,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,3,$campaignbasicblockid,1,'V~M',0,7,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'numsent','vtiger_campaign',1,'9','numsent','Num Sent',1,2,0,100,12,$campaignbasicblockid,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'sponsor','vtiger_campaign',1,'1','sponsor','Sponsor',1,2,0,100,9,$campaignbasicblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'targetaudience','vtiger_campaign',1,'1','targetaudience','Target Audience',1,2,0,100,7,$campaignbasicblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'targetsize','vtiger_campaign',1,'1','targetsize','TargetSize',1,2,0,100,10,$campaignbasicblockid,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,11,$campaignbasicblockid,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,13,$campaignbasicblockid,2,'T~O',3,null,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'expectedresponse','vtiger_campaign',1,'15','expectedresponse','Expected Response',1,2,0,100,3,$campaignexpectedandactualsblock,1,'V~O',2,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'expectedrevenue','vtiger_campaign',1,'1','expectedrevenue','Expected Revenue',1,2,0,100,4,$campaignexpectedandactualsblock,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'budgetcost','vtiger_campaign',1,'1','budgetcost','Budget Cost',1,2,0,100,1,$campaignexpectedandactualsblock,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'actualcost','vtiger_campaign',1,'1','actualcost','Actual Cost',1,2,0,100,2,$campaignexpectedandactualsblock,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'expectedresponsecount','vtiger_campaign',1,'1','expectedresponsecount','Expected Response Count',1,2,0,100,7,$campaignexpectedandactualsblock,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'expectedsalescount','vtiger_campaign',1,'1','expectedsalescount','Expected Sales Count',1,2,0,100,5,$campaignexpectedandactualsblock,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'expectedroi','vtiger_campaign',1,'1','expectedroi','Expected ROI',1,2,0,100,9,$campaignexpectedandactualsblock,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'actualresponsecount','vtiger_campaign',1,'1','actualresponsecount','Actual Response Count',1,2,0,100,8,$campaignexpectedandactualsblock,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'actualsalescount','vtiger_campaign',1,'1','actualsalescount','Actual Sales Count',1,2,0,100,6,$campaignexpectedandactualsblock,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(26,".$this->db->getUniqueID("vtiger_field").",'actualroi','vtiger_campaign',1,'1','actualroi','Actual ROI',1,2,0,100,10,$campaignexpectedandactualsblock,1,'N~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (26,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$campaidndescriptionblock,1,'V~O',1,null,'BAS',1)"); + //Campaign entries end + + //Ticket Details -- START + //Block25 -- Start + + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'ticket_no','vtiger_troubletickets',1,'4','ticket_no','Ticket No',1,0,0,100,13,25,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,4,25,1,'V~M',0,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'parent_id','vtiger_troubletickets',1,'68','parent_id','Related To',1,0,0,100,2,25,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'priority','vtiger_troubletickets',1,'15','ticketpriorities','Priority',1,2,0,100,6,25,1,'V~O',2,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'product_id','vtiger_troubletickets',1,'59','product_id','Product Name',1,2,0,100,5,25,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'severity','vtiger_troubletickets',1,'15','ticketseverities','Severity',1,2,0,100,8,25,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'status','vtiger_troubletickets',1,'15','ticketstatus','Status',1,2,0,100,7,25,1,'V~M',1,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'category','vtiger_troubletickets',1,'15','ticketcategories','Category',1,2,0,100,10,25,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'update_log','vtiger_troubletickets',1,'19','update_log','Update History',1,0,0,100,11,25,3,'V~O',1,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'hours','vtiger_troubletickets',1,'1','hours','Hours',1,2,0,100,9,25,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'days','vtiger_troubletickets',1,'1','days','Days',1,2,0,100,10,25,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,9,25,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,12,25,2,'T~O',3,null,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'title','vtiger_troubletickets',1,'22','ticket_title','Title',1,0,0,100,1,25,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,28,1,'V~O',2,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'solution','vtiger_troubletickets',1,'19','solution','Solution',1,0,0,100,1,29,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (13,".$this->db->getUniqueID("vtiger_field").",'comments','vtiger_ticketcomments',1,'19','comments','Add Comment',1,0,0,100,1,30,1,'V~O',3,null,'BAS',0)"); + + //Block25-30 -- End + //Ticket Details -- END + + //Product Details -- START + //Block31-36 -- Start + + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'productname','vtiger_products',1,'2','productname','Product Name',1,0,0,100,1,31,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'product_no','vtiger_products',1,'4','product_no','Product No',1,0,0,100,2,31,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'productcode','vtiger_products',1,'1','productcode','Part Number',1,2,0,100,4,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'discontinued','vtiger_products',1,'56','discontinued','Product Active',1,2,0,100,3,31,1,'V~O',2,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'manufacturer','vtiger_products',1,'15','manufacturer','Manufacturer',1,2,0,100,6,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'productcategory','vtiger_products',1,'15','productcategory','Product Category',1,2,0,100,6,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'sales_start_date','vtiger_products',1,'5','sales_start_date','Sales Start Date',1,2,0,100,5,31,1,'D~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'sales_end_date','vtiger_products',1,'5','sales_end_date','Sales End Date',1,2,0,100,8,31,1,'D~O~OTH~GE~sales_start_date~Sales Start Date',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'start_date','vtiger_products',1,'5','start_date','Support Start Date',1,2,0,100,7,31,1,'D~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'expiry_date','vtiger_products',1,'5','expiry_date','Support Expiry Date',1,2,0,100,10,31,1,'D~O~OTH~GE~start_date~Start Date',1,null,'BAS',1)"); + + + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'website','vtiger_products',1,'17','website','Website',1,2,0,100,14,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'vendor_id','vtiger_products',1,'75','vendor_id','Vendor Name',1,2,0,100,13,31,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'mfr_part_no','vtiger_products',1,'1','mfr_part_no','Mfr PartNo',1,2,0,100,16,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'vendor_part_no','vtiger_products',1,'1','vendor_part_no','Vendor PartNo',1,2,0,100,15,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'serialno','vtiger_products',1,'1','serial_no','Serial No',1,2,0,100,18,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'productsheet','vtiger_products',1,'1','productsheet','Product Sheet',1,2,0,100,17,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'glacct','vtiger_products',1,'15','glacct','GL Account',1,2,0,100,20,31,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,19,31,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,21,31,2,'T~O',3,null,'BAS',0)"); + + + //Block32 Pricing Information + + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'unit_price','vtiger_products',1,'71','unit_price','Unit Price',1,2,0,100,1,32,1,'N~O',2,3,'BAS',0)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'commissionrate','vtiger_products',1,'9','commissionrate','Commission Rate',1,2,0,100,2,32,1,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'taxclass','vtiger_products',1,'83','taxclass','Tax Class',1,2,0,100,4,32,1,'V~O',3,null,'BAS',1)"); + + + //Block 33 stock info + + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'usageunit','vtiger_products',1,'15','usageunit','Usage Unit',1,2,0,100,1,33,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'qty_per_unit','vtiger_products',1,'1','qty_per_unit','Qty/Unit',1,2,0,100,2,33,1,'N~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'qtyinstock','vtiger_products',1,'1','qtyinstock','Qty In Stock',1,2,0,100,3,33,1,'NN~O',0,4,'ADV',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'reorderlevel','vtiger_products',1,'1','reorderlevel','Reorder Level',1,2,0,100,4,33,1,'I~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'handler','vtiger_products',1,'52','assigned_user_id','Handler',1,0,0,100,5,33,1,'I~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'qtyindemand','vtiger_products',1,'1','qtyindemand','Qty In Demand',1,2,0,100,6,33,1,'I~O',1,null,'ADV',1)"); + + //ProductImageInformation + + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'imagename','vtiger_products',1,'69','imagename','Product Image',1,2,0,100,1,35,1,'V~O',3,null,'ADV',1)"); + + //Block 36 Description Info + $this->db->query("insert into vtiger_field values (14,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,36,1,'V~O',1,null,'BAS',1)"); + + //Product Details -- END + + //Documents Details -- START + //Block17 -- Start + + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'title','vtiger_notes',1,'2','notes_title','Title',1,0,0,100,1,17,1,'V~M',0,1,'BAS',0)"); + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,5,17,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,6,17,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'filename','vtiger_notes',1,'28','filename','File Name',1,2,0,100,3,".$fileblockid.",1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,4,17,1,'V~M',0,3,'BAS',0)"); + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'notecontent','vtiger_notes',1,'19','notecontent','Note',1,2,0,100,1,$desc_blockid,1,'V~O',1,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'filetype','vtiger_notes',1,1,'filetype','File Type',1,2,0,100,5,".$fileblockid.",2,'V~O',3,'','BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'filesize','vtiger_notes',1,1,'filesize','File Size',1,2,0,100,4,".$fileblockid.",2,'V~O',3,'','BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'filelocationtype','vtiger_notes',1,27,'filelocationtype','Download Type',1,0,0,100,1,".$fileblockid.",1,'V~O',1,'','BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'fileversion','vtiger_notes',1,1,'fileversion','Version',1,2,0,100,6,$fileblockid,1,'V~O',1,'','BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'filestatus','vtiger_notes',1,56,'filestatus','Active',1,2,0,100,2,".$fileblockid.",1,'V~O',1,'','BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'filedownloadcount','vtiger_notes',1,1,'filedownloadcount','Download Count',1,2,0,100,7,".$fileblockid.",2,'I~O',3,'','BAS',0)"); + $this->db->query("insert into vtiger_field values(8,".$this->db->getUniqueID("vtiger_field").",'folderid','vtiger_notes',1,26,'folderid','Folder Name',1,2,0,100,2,17,1,'V~O',2,2,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (8,".$this->db->getUniqueID("vtiger_field").",'note_no','vtiger_notes',1,'4','note_no','Document No',1,0,0,100,3,17,1,'V~0',3,null,'BAS',0)"); + + //Block17 -- End + //Documents Details -- END + + //Email Details -- START + //Block21 -- Start + + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'date_start','vtiger_activity',1,'6','date_start','Date & Time Sent',1,0,0,100,1,21,1,'DT~M~time_start~Time Start',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'semodule','vtiger_activity',1,'2','parent_type','Sales Enity Module',1,0,0,100,2,21,3,'',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'activitytype','vtiger_activity',1,'2','activitytype','Activtiy Type',1,0,0,100,3,21,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'crmid','vtiger_seactivityrel',1,'357','parent_id','Related To',1,0,0,100,1,22,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,5,21,1,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_activity',1,'2','subject','Subject',1,0,0,100,1,23,1,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'name','vtiger_attachments',1,'61','filename','Attachment',1,0,0,100,2,23,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,0,0,100,1,24,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'time_start','vtiger_activity',1,'2','time_start','Time Start',1,0,0,100,9,23,1,'T~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,10,22,1,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (10,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,11,21,2,'T~O',3,null,'BAS',0)"); + $this->db->query("INSERT INTO vtiger_field VALUES (10,".$this->db->getUniqueID("vtiger_field").", 'access_count', 'vtiger_email_track', '1', '25', 'access_count', 'Access Count', '1', '0', '0', '100', '6', '21', '3', 'V~O', '1', NULL, 'BAS', 0)"); + + //Block21 -- End + //Email Details -- END + + //Task Details --START + //Block19 -- Start + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_activity',1,'2','subject','Subject',1,0,0,100,1,19,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,2,19,1,'V~M',0,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'date_start','vtiger_activity',1,'6','date_start','Start Date & Time',1,0,0,100,3,19,1,'DT~M~time_start',0,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'time_start','vtiger_activity',1,'2','time_start','Time Start',1,0,0,100,4,19,3,'T~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'time_end','vtiger_activity',1,'2','time_end','End Time',1,0,0,100,4,19,3,'T~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'due_date','vtiger_activity',1,'23','due_date','Due Date',1,0,0,100,5,19,1,'D~M~OTH~GE~date_start~Start Date & Time',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'crmid','vtiger_seactivityrel',1,'66','parent_id','Related To',1,0,0,100,7,19,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'contactid','vtiger_cntactivityrel',1,'57','contact_id','Contact Name',1,0,0,100,8,19,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'status','vtiger_activity',1,'15','taskstatus','Status',1,0,0,100,8,19,1,'V~M',0,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'eventstatus','vtiger_activity',1,'15','eventstatus','Status',1,0,0,100,9,19,3,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'priority','vtiger_activity',1,'15','taskpriority','Priority',1,0,0,100,10,19,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'sendnotification','vtiger_activity',1,'56','sendnotification','Send Notification',1,0,0,100,11,19,1,'C~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,14,19,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,15,19,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'activitytype','vtiger_activity',1,'15','activitytype','Activity Type',1,0,0,100,16,19,3,'V~O',1,null,'BAS',1)"); + $this->db->query("Insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'visibility','vtiger_activity',1,'16','visibility','Visibility',1,0,0,100,17,19,3,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,0,0,100,1,20,1,'V~O',1,null,'BAS',1)"); + + + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'duration_hours','vtiger_activity',1,'63','duration_hours','Duration',1,0,0,100,17,19,3,'T~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'duration_minutes','vtiger_activity',1,'16','duration_minutes','Duration Minutes',1,0,0,100,18,19,3,'T~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'location','vtiger_activity',1,'1','location','Location',1,0,0,100,19,19,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'reminder_time','vtiger_activity_reminder',1,'30','reminder_time','Send Reminder',1,0,0,100,1,19,3,'I~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'recurringtype','vtiger_activity',1,'16','recurringtype','Recurrence',1,0,0,100,6,19,3,'O~O',1,null,'BAS',1)"); + + $this->db->query("Insert into vtiger_field values (9,".$this->db->getUniqueID("vtiger_field").",'notime','vtiger_activity',1,56,'notime','No Time',1,0,0,100,20,19,3,'C~O',1,null,'BAS',1)"); + //Block19 -- End + //Task Details -- END + + //Event Details --START + //Block41-43-- Start + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_activity',1,'2','subject','Subject',1,0,0,100,1,41,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,2,41,1,'V~M',0,6,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'date_start','vtiger_activity',1,'6','date_start','Start Date & Time',1,0,0,100,3,41,1,'DT~M~time_start',0,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'time_start','vtiger_activity',1,'2','time_start','Time Start',1,0,0,100,4,41,3,'T~M',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'due_date','vtiger_activity',1,'23','due_date','End Date',1,0,0,100,5,41,1,'D~M~OTH~GE~date_start~Start Date & Time',0,5,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'time_end','vtiger_activity',1,'2','time_end','End Time',1,0,0,100,5,41,3,'T~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'recurringtype','vtiger_activity',1,'16','recurringtype','Recurrence',1,0,0,100,6,41,1,'O~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'duration_hours','vtiger_activity',1,'63','duration_hours','Duration',1,0,0,100,7,41,1,'I~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'duration_minutes','vtiger_activity',1,'16','duration_minutes','Duration Minutes',1,0,0,100,8,41,3,'O~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'crmid','vtiger_seactivityrel',1,'66','parent_id','Related To',1,0,0,100,9,41,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'eventstatus','vtiger_activity',1,'15','eventstatus','Status',1,0,0,100,10,41,1,'V~M',0,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'sendnotification','vtiger_activity',1,'56','sendnotification','Send Notification',1,0,0,100,11,41,1,'C~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'activitytype','vtiger_activity',1,'15','activitytype','Activity Type',1,0,0,100,12,41,1,'V~M',0,4,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'location','vtiger_activity',1,'1','location','Location',1,0,0,100,13,41,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,14,41,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,15,41,2,'T~O',3,null,'BAS',0)"); + $this->db->query("Insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'priority','vtiger_activity',1,15,'taskpriority','Priority',1,0,0,100,16,41,1,'V~O',1,null,'BAS',1)"); + $this->db->query("Insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'notime','vtiger_activity',1,56,'notime','No Time',1,0,0,100,17,41,1,'C~O',1,null,'BAS',1)"); + $this->db->query("Insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'visibility','vtiger_activity',1,'16','visibility','Visibility',1,0,0,100,18,41,1,'V~O',1,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,0,0,100,1,41,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'reminder_time','vtiger_activity_reminder',1,'30','reminder_time','Send Reminder',1,0,0,100,1,40,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (16,".$this->db->getUniqueID("vtiger_field").",'contactid','vtiger_cntactivityrel',1,'57','contact_id','Contact Name',1,0,0,100,1,19,1,'I~O',1,null,'BAS',1)"); + + //Block41-43 -- End + //Event Details -- END + + //Faq Details -- START + //Block37-40 -- Start + + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'product_id','vtiger_faq',1,'59','product_id','Product Name',1,2,0,100,1,37,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'faq_no','vtiger_faq',1,'4','faq_no','Faq No',1,0,0,100,2,37,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'category','vtiger_faq',1,'15','faqcategories','Category',1,2,0,100,4,37,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'status','vtiger_faq',1,'15','faqstatus','Status',1,2,0,100,3,37,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'question','vtiger_faq',1,'20','question','Question',1,2,0,100,7,37,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'answer','vtiger_faq',1,'20','faq_answer','Answer',1,2,0,100,8,37,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'comments','vtiger_faqcomments',1,'19','comments','Add Comment',1,0,0,100,1,38,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,5,37,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (15,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,6,37,2,'T~O',3,null,'BAS',0)"); + + + //Block37-40 -- End + //Ticket Details -- END + + //Vendor Details --START + //Block44-47 + + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'vendorname','vtiger_vendor',1,'2','vendorname','Vendor Name',1,0,0,100,1,$vendorbasicinfo,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'vendor_no','vtiger_vendor',1,'4','vendor_no','Vendor No',1,0,0,100,2,$vendorbasicinfo,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'phone','vtiger_vendor',1,'1','phone','Phone',1,2,0,100,4,$vendorbasicinfo,1,'V~O',2,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'email','vtiger_vendor',1,'13','email','Email',1,2,0,100,3,$vendorbasicinfo,1,'E~O',2,3,'BAS',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'website','vtiger_vendor',1,'17','website','Website',1,2,0,100,6,$vendorbasicinfo,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'glacct','vtiger_vendor',1,'15','glacct','GL Account',1,2,0,100,5,$vendorbasicinfo,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'category','vtiger_vendor',1,'1','category','Category',1,2,0,100,8,$vendorbasicinfo,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,7,$vendorbasicinfo,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,9,$vendorbasicinfo,2,'T~O',3,null,'BAS',0)"); + + //Block 46 + + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'street','vtiger_vendor',1,'21','street','Street',1,2,0,100,1,$vendoraddressblock,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'pobox','vtiger_vendor',1,'1','pobox','Po Box',1,2,0,100,2,$vendoraddressblock,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'city','vtiger_vendor',1,'1','city','City',1,2,0,100,3,$vendoraddressblock,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'state','vtiger_vendor',1,'1','state','State',1,2,0,100,4,$vendoraddressblock,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'postalcode','vtiger_vendor',1,'1','postalcode','Postal Code',1,2,0,100,5,$vendoraddressblock,1,'V~O',1,null,'ADV',1)"); + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'country','vtiger_vendor',1,'1','country','Country',1,2,0,100,6,$vendoraddressblock,1,'V~O',1,null,'ADV',1)"); + + //Block 47 + + $this->db->query("insert into vtiger_field values (18,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$vendordescriptionblock,1,'V~O',1,null,'ADV',1)"); + + //Vendor Details -- END + + //PriceBook Details Start + //Block48 + + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'bookname','vtiger_pricebook',1,'2','bookname','Price Book Name',1,0,0,100,1,$pricebookbasicblock,1,'V~M',0,1,'BAS',1)"); + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'pricebook_no','vtiger_pricebook',1,'4','pricebook_no','PriceBook No',1,0,0,100,3,$pricebookbasicblock,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'active','vtiger_pricebook',1,'56','active','Active',1,2,0,100,2,$pricebookbasicblock,1,'C~O',2,2,'BAS',1)"); + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,4,$pricebookbasicblock,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,5,$pricebookbasicblock,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'currency_id','vtiger_pricebook',1,'117','currency_id','Currency',1,0,0,100,5,$pricebookbasicblock,1,'I~M',0,3,'BAS',0)"); + //Block50 + + $this->db->query("insert into vtiger_field values (19,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$pricebookdescription,1,'V~O',1,null,'BAS',1)"); + + //PriceBook Details End + + + //Quote Details -- START + //Block51 + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'quote_no','vtiger_quotes',1,'4','quote_no','Quote No',1,0,0,100,3,$quotesbasicblock,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_quotes',1,'2','subject','Subject',1,0,0,100,1,$quotesbasicblock,1,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'potentialid','vtiger_quotes',1,'76','potential_id','Potential Name',1,2,0,100,2,$quotesbasicblock,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'quotestage','vtiger_quotes',1,'15','quotestage','Quote Stage',1,2,0,100,4,$quotesbasicblock,1,'V~M',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'validtill','vtiger_quotes',1,'5','validtill','Valid Till',1,2,0,100,5,$quotesbasicblock,1,'D~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'contactid','vtiger_quotes',1,'57','contact_id','Contact Name',1,2,0,100,6,$quotesbasicblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'carrier','vtiger_quotes',1,'15','carrier','Carrier',1,2,0,100,8,$quotesbasicblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'subtotal','vtiger_quotes',1,'1','hdnSubTotal','Sub Total',1,2,0,100,9,$quotesbasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'shipping','vtiger_quotes',1,'1','shipping','Shipping',1,2,0,100,10,$quotesbasicblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'inventorymanager','vtiger_quotes',1,'77','assigned_user_id1','Inventory Manager',1,2,0,100,11,$quotesbasicblock,1,'I~O',3,null,'BAS',1)"); + //$this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'tax','vtiger_quotes',1,'1','txtTax','Sales Tax',1,0,0,100,13,51,3,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'adjustment','vtiger_quotes',1,'1','txtAdjustment','Adjustment',1,2,0,100,20,$quotesbasicblock,3,'NN~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'total','vtiger_quotes',1,'1','hdnGrandTotal','Total',1,2,0,100,14,$quotesbasicblock,3,'N~O',3,null,'BAS',1)"); + //Added fields taxtype, discount percent, discount amount and S&H amount for Tax process + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'taxtype','vtiger_quotes',1,'16','hdnTaxType','Tax Type',1,2,0,100,14,$quotesbasicblock,3,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'discount_percent','vtiger_quotes',1,'1','hdnDiscountPercent','Discount Percent',1,2,0,100,14,$quotesbasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'discount_amount','vtiger_quotes',1,'1','hdnDiscountAmount','Discount Amount',1,2,0,100,14,$quotesbasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'s_h_amount','vtiger_quotes',1,'1','hdnS_H_Amount','S&H Amount',1,2,0,100,14,$quotesbasicblock,3,'N~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'accountid','vtiger_quotes',1,'73','account_id','Account Name',1,2,0,100,16,$quotesbasicblock,1,'I~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,17,$quotesbasicblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,18,$quotesbasicblock,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,19,$quotesbasicblock,2,'T~O',3,null,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'currency_id','vtiger_quotes',1,'117','currency_id','Currency',1,2,1,100,20,$quotesbasicblock,3,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'conversion_rate','vtiger_quotes',1,'1','conversion_rate','Conversion Rate',1,2,1,100,21,$quotesbasicblock,3,'N~O',3,null,'BAS',1)"); + + //Block 53 + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'bill_street','vtiger_quotesbillads',1,'24','bill_street','Billing Address',1,2,0,100,1,$quotesaddressblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'ship_street','vtiger_quotesshipads',1,'24','ship_street','Shipping Address',1,2,0,100,2,$quotesaddressblock,1,'V~M',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'bill_city','vtiger_quotesbillads',1,'1','bill_city','Billing City',1,2,0,100,5,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'ship_city','vtiger_quotesshipads',1,'1','ship_city','Shipping City',1,2,0,100,6,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'bill_state','vtiger_quotesbillads',1,'1','bill_state','Billing State',1,2,0,100,7,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'ship_state','vtiger_quotesshipads',1,'1','ship_state','Shipping State',1,2,0,100,8,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'bill_code','vtiger_quotesbillads',1,'1','bill_code','Billing Code',1,2,0,100,9,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'ship_code','vtiger_quotesshipads',1,'1','ship_code','Shipping Code',1,2,0,100,10,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'bill_country','vtiger_quotesbillads',1,'1','bill_country','Billing Country',1,2,0,100,11,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'ship_country','vtiger_quotesshipads',1,'1','ship_country','Shipping Country',1,2,0,100,12,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'bill_pobox','vtiger_quotesbillads',1,'1','bill_pobox','Billing Po Box',1,2,0,100,3,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'ship_pobox','vtiger_quotesshipads',1,'1','ship_pobox','Shipping Po Box',1,0,0,100,4,$quotesaddressblock,1,'V~O',3,null,'BAS',1)"); + //Block55 + + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$quotedescription,1,'V~O',3,null,'ADV',1)"); + + //Block 56 + $this->db->query("insert into vtiger_field values (20,".$this->db->getUniqueID("vtiger_field").",'terms_conditions','vtiger_quotes',1,'19','terms_conditions','Terms & Conditions',1,2,0,100,1,$quotetermsblock,1,'V~O',3,null,'ADV',1)"); + + + //Quote Details -- END + + //Purchase Order Details -- START + //Block57 + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'purchaseorder_no','vtiger_purchaseorder',1,'4','purchaseorder_no','PurchaseOrder No',1,0,0,100,2,$pobasicblock,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_purchaseorder',1,'2','subject','Subject',1,0,0,100,1,$pobasicblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'vendorid','vtiger_purchaseorder',1,'81','vendor_id','Vendor Name',1,0,0,100,3,$pobasicblock,1,'I~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'requisition_no','vtiger_purchaseorder',1,'1','requisition_no','Requisition No',1,2,0,100,4,$pobasicblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'tracking_no','vtiger_purchaseorder',1,'1','tracking_no','Tracking Number',1,2,0,100,5,$pobasicblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'contactid','vtiger_purchaseorder',1,'57','contact_id','Contact Name',1,2,0,100,6,$pobasicblock,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'duedate','vtiger_purchaseorder',1,'5','duedate','Due Date',1,2,0,100,7,$pobasicblock,1,'D~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'carrier','vtiger_purchaseorder',1,'15','carrier','Carrier',1,2,0,100,8,$pobasicblock,1,'V~O',3,null,'BAS',1)"); + //$this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'salestax','vtiger_purchaseorder',1,'1','txtTax','Sales Tax',1,0,0,100,10,57,3,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'adjustment','vtiger_purchaseorder',1,'1','txtAdjustment','Adjustment',1,2,0,100,10,$pobasicblock,3,'NN~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'salescommission','vtiger_purchaseorder',1,'1','salescommission','Sales Commission',1,2,0,100,11,$pobasicblock,1,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'exciseduty','vtiger_purchaseorder',1,'1','exciseduty','Excise Duty',1,2,0,100,12,$pobasicblock,1,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'total','vtiger_purchaseorder',1,'1','hdnGrandTotal','Total',1,2,0,100,13,$pobasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'subtotal','vtiger_purchaseorder',1,'1','hdnSubTotal','Sub Total',1,2,0,100,14,$pobasicblock,3,'N~O',3,null,'BAS',1)"); + //Added fields taxtype, discount percent, discount amount and S&H amount for Tax process + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'taxtype','vtiger_purchaseorder',1,'16','hdnTaxType','Tax Type',1,2,0,100,14,$pobasicblock,3,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'discount_percent','vtiger_purchaseorder',1,'1','hdnDiscountPercent','Discount Percent',1,2,0,100,14,$pobasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'discount_amount','vtiger_purchaseorder',1,'1','hdnDiscountAmount','Discount Amount',1,0,0,100,14,$pobasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'s_h_amount','vtiger_purchaseorder',1,'1','hdnS_H_Amount','S&H Amount',1,2,0,100,14,$pobasicblock,3,'N~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'postatus','vtiger_purchaseorder',1,'15','postatus','Status',1,2,0,100,15,$pobasicblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,16,$pobasicblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,17,$pobasicblock,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,18,$pobasicblock,2,'T~O',3,null,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'currency_id','vtiger_purchaseorder',1,'117','currency_id','Currency',1,2,1,100,19,$pobasicblock,3,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'conversion_rate','vtiger_purchaseorder',1,'1','conversion_rate','Conversion Rate',1,2,1,100,20,$pobasicblock,3,'N~O',3,null,'BAS',1)"); + + //Block 59 + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'bill_street','vtiger_pobillads',1,'24','bill_street','Billing Address',1,2,0,100,1,$poaddressblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'ship_street','vtiger_poshipads',1,'24','ship_street','Shipping Address',1,2,0,100,2,$poaddressblock,1,'V~M',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'bill_city','vtiger_pobillads',1,'1','bill_city','Billing City',1,2,0,100,5,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'ship_city','vtiger_poshipads',1,'1','ship_city','Shipping City',1,2,0,100,6,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'bill_state','vtiger_pobillads',1,'1','bill_state','Billing State',1,2,0,100,7,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'ship_state','vtiger_poshipads',1,'1','ship_state','Shipping State',1,2,0,100,8,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'bill_code','vtiger_pobillads',1,'1','bill_code','Billing Code',1,2,0,100,9,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'ship_code','vtiger_poshipads',1,'1','ship_code','Shipping Code',1,2,0,100,10,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'bill_country','vtiger_pobillads',1,'1','bill_country','Billing Country',1,2,0,100,11,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'ship_country','vtiger_poshipads',1,'1','ship_country','Shipping Country',1,2,0,100,12,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'bill_pobox','vtiger_pobillads',1,'1','bill_pobox','Billing Po Box',1,2,0,100,3,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'ship_pobox','vtiger_poshipads',1,'1','ship_pobox','Shipping Po Box',1,2,0,100,4,$poaddressblock,1,'V~O',3,null,'BAS',1)"); + + //Block61 + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$podescription,1,'V~O',3,null,'ADV',1)"); + + //Block62 + $this->db->query("insert into vtiger_field values (21,".$this->db->getUniqueID("vtiger_field").",'terms_conditions','vtiger_purchaseorder',1,'19','terms_conditions','Terms & Conditions',1,2,0,100,1,$potermsblock,1,'V~O',3,null,'ADV',1)"); + + //Purchase Order Details -- END + + //Sales Order Details -- START + //Block63 + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'salesorder_no','vtiger_salesorder',1,'4','salesorder_no','SalesOrder No',1,0,0,100,4,$sobasicblock ,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_salesorder',1,'2','subject','Subject',1,0,0,100,1,$sobasicblock ,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'potentialid','vtiger_salesorder',1,'76','potential_id','Potential Name',1,2,0,100,2,$sobasicblock ,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'customerno','vtiger_salesorder',1,'1','customerno','Customer No',1,2,0,100,3,$sobasicblock ,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'quoteid','vtiger_salesorder',1,'78','quote_id','Quote Name',1,2,0,100,5,$sobasicblock ,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'purchaseorder','vtiger_salesorder',1,'1','vtiger_purchaseorder','Purchase Order',1,2,0,100,5,$sobasicblock ,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'contactid','vtiger_salesorder',1,'57','contact_id','Contact Name',1,2,0,100,6,$sobasicblock ,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'duedate','vtiger_salesorder',1,'5','duedate','Due Date',1,2,0,100,8,$sobasicblock ,1,'D~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'carrier','vtiger_salesorder',1,'15','carrier','Carrier',1,2,0,100,9,$sobasicblock ,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'pending','vtiger_salesorder',1,'1','pending','Pending',1,2,0,100,10,$sobasicblock ,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'sostatus','vtiger_salesorder',1,'15','sostatus','Status',1,2,0,100,11,$sobasicblock ,1,'V~M',3,null,'BAS',1)"); + //$this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'salestax','vtiger_salesorder',1,'1','txtTax','Sales Tax',1,0,0,100,12,63,3,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'adjustment','vtiger_salesorder',1,'1','txtAdjustment','Adjustment',1,2,0,100,12,$sobasicblock ,3,'NN~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'salescommission','vtiger_salesorder',1,'1','salescommission','Sales Commission',1,2,0,100,13,$sobasicblock ,1,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'exciseduty','vtiger_salesorder',1,'1','exciseduty','Excise Duty',1,2,0,100,13,$sobasicblock ,1,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'total','vtiger_salesorder',1,'1','hdnGrandTotal','Total',1,2,0,100,14,$sobasicblock ,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'subtotal','vtiger_salesorder',1,'1','hdnSubTotal','Sub Total',1,2,0,100,15,$sobasicblock ,3,'N~O',3,null,'BAS',1)"); + //Added fields taxtype, discount percent, discount amount and S&H amount for Tax process + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'taxtype','vtiger_salesorder',1,'16','hdnTaxType','Tax Type',1,2,0,100,15,$sobasicblock ,3,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'discount_percent','vtiger_salesorder',1,'1','hdnDiscountPercent','Discount Percent',1,2,0,100,15,$sobasicblock ,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'discount_amount','vtiger_salesorder',1,'1','hdnDiscountAmount','Discount Amount',1,0,0,100,15,$sobasicblock ,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'s_h_amount','vtiger_salesorder',1,'1','hdnS_H_Amount','S&H Amount',1,2,0,100,15,$sobasicblock ,3,'N~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'accountid','vtiger_salesorder',1,'73','account_id','Account Name',1,2,0,100,16,$sobasicblock ,1,'I~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,17,$sobasicblock ,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,18,$sobasicblock ,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,19,$sobasicblock ,2,'T~O',3,null,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'currency_id','vtiger_salesorder',1,'117','currency_id','Currency',1,2,1,100,20,$sobasicblock ,3,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'conversion_rate','vtiger_salesorder',1,'1','conversion_rate','Conversion Rate',1,2,1,100,21,$sobasicblock ,3,'N~O',3,null,'BAS',1)"); + + + //Block 65 + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'bill_street','vtiger_sobillads',1,'24','bill_street','Billing Address',1,2,0,100,1,$soaddressblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'ship_street','vtiger_soshipads',1,'24','ship_street','Shipping Address',1,2,0,100,2,$soaddressblock,1,'V~M',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'bill_city','vtiger_sobillads',1,'1','bill_city','Billing City',1,2,0,100,5,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'ship_city','vtiger_soshipads',1,'1','ship_city','Shipping City',1,2,0,100,6,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'bill_state','vtiger_sobillads',1,'1','bill_state','Billing State',1,2,0,100,7,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'ship_state','vtiger_soshipads',1,'1','ship_state','Shipping State',1,2,0,100,8,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'bill_code','vtiger_sobillads',1,'1','bill_code','Billing Code',1,2,0,100,9,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'ship_code','vtiger_soshipads',1,'1','ship_code','Shipping Code',1,2,0,100,10,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'bill_country','vtiger_sobillads',1,'1','bill_country','Billing Country',1,2,0,100,11,$soaddressblock,3,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'ship_country','vtiger_soshipads',1,'1','ship_country','Shipping Country',1,2,0,100,12,$soaddressblock,3,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'bill_pobox','vtiger_sobillads',1,'1','bill_pobox','Billing Po Box',1,2,0,100,3,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'ship_pobox','vtiger_soshipads',1,'1','ship_pobox','Shipping Po Box',1,2,0,100,4,$soaddressblock,1,'V~O',3,null,'BAS',1)"); + + //Block67 + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$sodescription,1,'V~O',3,null,'ADV',1)"); + + //Block68 + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID("vtiger_field").",'terms_conditions','vtiger_salesorder',1,'19','terms_conditions','Terms & Conditions',1,2,0,100,1,$sotermsblock,1,'V~O',3,null,'ADV',1)"); + + // Add fields for the Recurring Information block - Block 86 + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID('vtiger_field').",'enable_recurring','vtiger_salesorder',1,'56','enable_recurring','Enable Recurring',1,0,0,100,1,$sorecurringinvoiceblock,1,'C~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID('vtiger_field').",'recurring_frequency','vtiger_invoice_recurring_info',1,'16','recurring_frequency','Frequency',1,0,0,100,2,$sorecurringinvoiceblock,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID('vtiger_field').",'start_period','vtiger_invoice_recurring_info',1,'5','start_period','Start Period',1,0,0,100,3,$sorecurringinvoiceblock,1,'D~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID('vtiger_field').",'end_period','vtiger_invoice_recurring_info',1,'5','end_period','End Period',1,0,0,100,4,$sorecurringinvoiceblock,1,'D~O~OTH~G~start_period~Start Period',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID('vtiger_field').",'payment_duration','vtiger_invoice_recurring_info',1,'16','payment_duration','Payment Duration',1,0,0,100,5,$sorecurringinvoiceblock,1,'V~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (22,".$this->db->getUniqueID('vtiger_field').",'invoice_status','vtiger_invoice_recurring_info',1,'15','invoicestatus','Invoice Status',1,0,0,100,6,$sorecurringinvoiceblock,1,'V~M',3,null,'BAS',0)"); + + //Sales Order Details -- END + + //Invoice Details -- START + //Block69 + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'subject','vtiger_invoice',1,'2','subject','Subject',1,0,0,100,1,$invoicebasicblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'salesorderid','vtiger_invoice',1,'80','salesorder_id','Sales Order',1,2,0,100,2,$invoicebasicblock,1,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'customerno','vtiger_invoice',1,'1','customerno','Customer No',1,2,0,100,3,$invoicebasicblock,1,'V~O',3,null,'BAS',1)"); + + + //to include contact name vtiger_field in Invoice-start + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'contactid','vtiger_invoice',1,'57','contact_id','Contact Name',1,2,0,100,4,$invoicebasicblock,1,'I~O',3,null,'BAS',1)"); + //end + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'invoicedate','vtiger_invoice',1,'5','invoicedate','Invoice Date',1,2,0,100,5,$invoicebasicblock,1,'D~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'duedate','vtiger_invoice',1,'5','duedate','Due Date',1,2,0,100,6,$invoicebasicblock,1,'D~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'purchaseorder','vtiger_invoice',1,'1','vtiger_purchaseorder','Purchase Order',1,2,0,100,8,$invoicebasicblock,1,'V~O',3,null,'BAS',1)"); + //$this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'salestax','vtiger_invoice',1,'1','txtTax','Sales Tax',1,0,0,100,9,69,3,'N~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'adjustment','vtiger_invoice',1,'1','txtAdjustment','Adjustment',1,2,0,100,9,$invoicebasicblock,3,'NN~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'salescommission','vtiger_invoice',1,'1','salescommission','Sales Commission',1,2,0,10,13,$invoicebasicblock,1,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'exciseduty','vtiger_invoice',1,'1','exciseduty','Excise Duty',1,2,0,100,11,$invoicebasicblock,1,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'subtotal','vtiger_invoice',1,'1','hdnSubTotal','Sub Total',1,2,0,100,12,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'total','vtiger_invoice',1,'1','hdnGrandTotal','Total',1,2,0,100,13,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); + //Added fields taxtype, discount percent, discount amount and S&H amount for Tax process + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'taxtype','vtiger_invoice',1,'16','hdnTaxType','Tax Type',1,2,0,100,13,$invoicebasicblock,3,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'discount_percent','vtiger_invoice',1,'1','hdnDiscountPercent','Discount Percent',1,2,0,100,13,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'discount_amount','vtiger_invoice',1,'1','hdnDiscountAmount','Discount Amount',1,2,0,100,13,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'s_h_amount','vtiger_invoice',1,'1','hdnS_H_Amount','S&H Amount',1,2,0,100,14,57,3,'N~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'accountid','vtiger_invoice',1,'73','account_id','Account Name',1,2,0,100,14,$invoicebasicblock,1,'I~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'invoicestatus','vtiger_invoice',1,'15','invoicestatus','Status',1,2,0,100,15,$invoicebasicblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'smownerid','vtiger_crmentity',1,'53','assigned_user_id','Assigned To',1,0,0,100,16,$invoicebasicblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'createdtime','vtiger_crmentity',1,'70','createdtime','Created Time',1,0,0,100,17,$invoicebasicblock,2,'T~O',3,null,'BAS',0)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'modifiedtime','vtiger_crmentity',1,'70','modifiedtime','Modified Time',1,0,0,100,18,$invoicebasicblock,2,'T~O',3,null,'BAS',0)"); + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'currency_id','vtiger_invoice',1,'117','currency_id','Currency',1,2,1,100,19,$invoicebasicblock,3,'I~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'conversion_rate','vtiger_invoice',1,'1','conversion_rate','Conversion Rate',1,2,1,100,20,$invoicebasicblock,3,'N~O',3,null,'BAS',1)"); + + //Block 71 + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'bill_street','vtiger_invoicebillads',1,'24','bill_street','Billing Address',1,2,0,100,1,$invoiceaddressblock,1,'V~M',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'ship_street','vtiger_invoiceshipads',1,'24','ship_street','Shipping Address',1,2,0,100,2,$invoiceaddressblock,1,'V~M',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'bill_city','vtiger_invoicebillads',1,'1','bill_city','Billing City',1,2,0,100,5,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'ship_city','vtiger_invoiceshipads',1,'1','ship_city','Shipping City',1,2,0,100,6,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'bill_state','vtiger_invoicebillads',1,'1','bill_state','Billing State',1,2,0,100,7,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'ship_state','vtiger_invoiceshipads',1,'1','ship_state','Shipping State',1,2,0,100,8,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'bill_code','vtiger_invoicebillads',1,'1','bill_code','Billing Code',1,2,0,100,9,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'ship_code','vtiger_invoiceshipads',1,'1','ship_code','Shipping Code',1,2,0,100,10,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'bill_country','vtiger_invoicebillads',1,'1','bill_country','Billing Country',1,2,0,100,11,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'ship_country','vtiger_invoiceshipads',1,'1','ship_country','Shipping Country',1,2,0,100,12,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'bill_pobox','vtiger_invoicebillads',1,'1','bill_pobox','Billing Po Box',1,2,0,100,3,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'ship_pobox','vtiger_invoiceshipads',1,'1','ship_pobox','Shipping Po Box',1,2,0,100,4,$invoiceaddressblock,1,'V~O',3,null,'BAS',1)"); + + //Block73 + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_crmentity',1,'19','description','Description',1,2,0,100,1,$invoicedescription,1,'V~O',3,null,'ADV',1)"); + //Block74 + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'terms_conditions','vtiger_invoice',1,'19','terms_conditions','Terms & Conditions',1,2,0,100,1,$invoicetermsblock,1,'V~O',3,null,'ADV',1)"); + //Added for Custom invoice Number + $this->db->query("insert into vtiger_field values (23,".$this->db->getUniqueID("vtiger_field").",'invoice_no','vtiger_invoice',1,'4','invoice_no','Invoice No',1,0,0,100,3,$invoicebasicblock,1,'V~O',3,null,'BAS',0)"); + + //Invoice Details -- END + //users Details Starts Block 79,80,81 + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'user_name','vtiger_users',1,'106','user_name','User Name',1,0,0,11,1,$userloginandroleblockid,1,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'is_admin','vtiger_users',1,'156','is_admin','Admin',1,0,0,3,2,$userloginandroleblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'user_password','vtiger_users',1,'99','user_password','Password',1,0,0,30,3,$userloginandroleblockid,4,'P~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'confirm_password','vtiger_users',1,'99','confirm_password','Confirm Password',1,0,0,30,5,$userloginandroleblockid,4,'P~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'first_name','vtiger_users',1,'1','first_name','First Name',1,0,0,30,7,$userloginandroleblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'last_name','vtiger_users',1,'2','last_name','Last Name',1,0,0,30,9,$userloginandroleblockid,1,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'roleid','vtiger_user2role',1,'98','roleid','Role',1,0,0,200,11,$userloginandroleblockid,1,'V~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'email1','vtiger_users',1,'104','email1','Email',1,0,0,100,4,$userloginandroleblockid,1,'E~M',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'status','vtiger_users',1,'115','status','Status',1,0,0,100,6,$userloginandroleblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'activity_view','vtiger_users',1,'16','activity_view','Default Activity View',1,0,0,100,12,$userloginandroleblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'lead_view','vtiger_users',1,'16','lead_view','Default Lead View',1,0,0,100,10,$userloginandroleblockid,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'currency_id','vtiger_users',1,'116','currency_id','Currency',1,0,0,100,8,$userloginandroleblockid,1,'I~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'hour_format','vtiger_users',1,'116','hour_format','Calendar Hour Format',1,0,0,100,13,$userloginandroleblockid,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'end_hour','vtiger_users',1,'116','end_hour','Day ends at',1,0,0,100,15,$userloginandroleblockid,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'start_hour','vtiger_users',1,'116','start_hour','Day starts at',1,0,0,100,14,$userloginandroleblockid,3,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'title','vtiger_users',1,'1','title','Title',1,0,0,50,1,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'phone_work','vtiger_users',1,'1','phone_work','Office Phone',1,0,0,50,5,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'department','vtiger_users',1,'1','department','Department',1,0,0,50,3,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'phone_mobile','vtiger_users',1,'1','phone_mobile','Mobile',1,0,0,50,7,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'reports_to_id','vtiger_users',1,'101','reports_to_id','Reports To',1,0,0,50,8,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'phone_other','vtiger_users',1,'1','phone_other','Other Phone',1,0,0,50,11,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'email2','vtiger_users',1,'13','email2','Other Email',1,0,0,100,4,$usermoreinfoblock,1,'E~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'phone_fax','vtiger_users',1,'1','phone_fax','Fax',1,0,0,50,2,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'yahoo_id','vtiger_users',1,'13','yahoo_id','Yahoo id',1,0,0,100,6,$usermoreinfoblock,1,'E~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'phone_home','vtiger_users',1,'1','phone_home','Home Phone',1,0,0,50,9,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'date_format','vtiger_users',1,'16','date_format','Date Format',1,0,0,30,12,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'signature','vtiger_users',1,'21','signature','Signature',1,0,0,250,13,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'description','vtiger_users',1,'21','description','Documents',1,0,0,250,14,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'address_street','vtiger_users',1,'21','address_street','Street Address',1,0,0,250,1,$useraddressblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'address_city','vtiger_users',1,'1','address_city','City',1,0,0,100,3,$useraddressblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'address_state','vtiger_users',1,'1','address_state','State',1,0,0,100,5,$useraddressblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'address_postalcode','vtiger_users',1,'1','address_postalcode','Postal Code',1,0,0,100,4,$useraddressblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'address_country','vtiger_users',1,'1','address_country','Country',1,0,0,100,2,$useraddressblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values(29,".$this->db->getUniqueID("vtiger_field").",'accesskey','vtiger_users',1,3,'accesskey','Webservice Access Key',1,0,0,100,2,$useradvanceblock,2,'V~O',1,null,'BAS',1);"); + + //User Image Information + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'imagename','vtiger_users',1,'105','imagename','User Image',1,0,0,250,10,$userblockid,1,'V~O',1,null,'BAS',1)"); + //added for internl_mailer + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'internal_mailer','vtiger_users',1,'56','internal_mailer','INTERNAL_MAIL_COMPOSER',1,0,0,50,15,$usermoreinfoblock,1,'V~O',1,null,'BAS',1)"); + $this->db->query("insert into vtiger_field values (29,".$this->db->getUniqueID("vtiger_field").",'reminder_interval','vtiger_users',1,'16','reminder_interval','Reminder Interval',1,0,0,100,1,$useradvanceblock,1,'V~O',1,null,'BAS',1)"); + //user Details End + + // Updated Phone field uitype + $this->db->query("update vtiger_field set uitype='11' where fieldname='mobile' and tabid=".getTabid('Leads')); + $this->db->query("update vtiger_field set uitype='11' where fieldname='mobile' and tabid=".getTabid('Contacts')); + $this->db->query("update vtiger_field set uitype='11' where fieldname='fax' and tabid=".getTabid('Leads')); + $this->db->query("update vtiger_field set uitype='11' where fieldname='fax' and tabid=".getTabid('Contacts')); + $this->db->query("update vtiger_field set uitype='11' where fieldname='fax' and tabid=".getTabid('Accounts')); + + $tab_field_array = array( + 'Accounts'=>array('accountname'), + 'Contacts'=>array('imagename'), + 'Products'=>array('imagename','product_id'), + 'Invoice'=>array('invoice_no','salesorder_id'), + 'SalesOrder'=>array('quote_id','salesorder_no'), + 'PurchaseOrder'=>array('purchaseorder_no'), + 'Quotes'=>array('quote_no'), + 'HelpDesk'=>array('filename'), + ); + foreach($tab_field_array as $index=>$value){ + $tabid = getTabid($index); + $this->db->pquery("UPDATE vtiger_field SET masseditable=0 WHERE tabid=? AND fieldname IN (".generateQuestionMarks($value).")",array($tabid,$value)); + } + + //Emails field added here + $email_Tabid = getTabid('Emails'); + $blockid = $this->db->getUniqueID('vtiger_blocks'); + $this->db->query("INSERT INTO vtiger_field values($email_Tabid,".$this->db->getUniqueID("vtiger_field").",'from_email','vtiger_emaildetails',1,12,'from_email','From',1,2,0,100,1,$blockid,3,'V~M',3,NULL,'BAS',0)"); + $this->db->query("INSERT INTO vtiger_field values($email_Tabid,".$this->db->getUniqueID("vtiger_field").",'to_email','vtiger_emaildetails',1,8,'saved_toid','To',1,2,0,100,2,$blockid,1,'V~M',3,NULL,'BAS',0)"); + $this->db->query("INSERT INTO vtiger_field values($email_Tabid,".$this->db->getUniqueID("vtiger_field").",'cc_email','vtiger_emaildetails',1,8,'ccmail','CC',1,2,0,1000,3,$blockid,1,'V~O',3,NULL,'BAS',0)"); + $this->db->query("INSERT INTO vtiger_field values($email_Tabid,".$this->db->getUniqueID("vtiger_field").",'bcc_email','vtiger_emaildetails',1,8,'bccmail','BCC' ,1,2,0,1000,4,$blockid,1,'V~O',3,NULL,'BAS',0)"); + $this->db->query("INSERT INTO vtiger_field values($email_Tabid,".$this->db->getUniqueID("vtiger_field").",'idlists','vtiger_emaildetails',1,1,'parent_id','Parent ID' ,1,2,0,1000,5,$blockid,3,'V~O',3,NULL,'BAS',0)"); + $this->db->query("INSERT INTO vtiger_field values($email_Tabid,".$this->db->getUniqueID("vtiger_field").",'email_flag','vtiger_emaildetails',1,16,'email_flag','Email Flag' ,1,2,0,1000,6,$blockid,3,'V~O',3,NULL,'BAS',0)"); + //Emails fields ends + + //The Entity Name for the modules are maintained in this table + $this->db->query("insert into vtiger_entityname values(7,'Leads','vtiger_leaddetails','lastname,firstname','leadid','leadid')"); + $this->db->query("insert into vtiger_entityname values(6,'Accounts','vtiger_account','accountname','accountid','account_id')"); + $this->db->query("insert into vtiger_entityname values(4,'Contacts','vtiger_contactdetails','lastname,firstname','contactid','contact_id')"); + $this->db->query("insert into vtiger_entityname values(2,'Potentials','vtiger_potential','potentialname','potentialid','potential_id')"); + $this->db->query("insert into vtiger_entityname values(8,'Documents','vtiger_notes','title','notesid','notesid')"); + $this->db->query("insert into vtiger_entityname values(13,'HelpDesk','vtiger_troubletickets','title','ticketid','ticketid')"); + $this->db->query("insert into vtiger_entityname values(9,'Calendar','vtiger_activity','subject','activityid','activityid')"); + $this->db->query("insert into vtiger_entityname values(10,'Emails','vtiger_activity','subject','activityid','activityid')"); + $this->db->query("insert into vtiger_entityname values(14,'Products','vtiger_products','productname','productid','product_id')"); + $this->db->query("insert into vtiger_entityname values(29,'Users','vtiger_users','last_name,first_name','id','id')"); + $this->db->query("insert into vtiger_entityname values(23,'Invoice','vtiger_invoice','subject','invoiceid','invoiceid')"); + $this->db->query("insert into vtiger_entityname values(20,'Quotes','vtiger_quotes','subject','quoteid','quote_id')"); + $this->db->query("insert into vtiger_entityname values(21,'PurchaseOrder','vtiger_purchaseorder','subject','purchaseorderid','purchaseorderid')"); + $this->db->query("insert into vtiger_entityname values(22,'SalesOrder','vtiger_salesorder','subject','salesorderid','salesorder_id')"); + $this->db->query("insert into vtiger_entityname values(18,'Vendors','vtiger_vendor','vendorname','vendorid','vendor_id')"); + $this->db->query("insert into vtiger_entityname values(19,'PriceBooks','vtiger_pricebook','bookname','pricebookid','pricebookid')"); + $this->db->query("insert into vtiger_entityname values(26,'Campaigns','vtiger_campaign','campaignname','campaignid','campaignid')"); + $this->db->query("insert into vtiger_entityname values(15,'Faq','vtiger_faq','question','id','id')"); + // Insert End + + + //Inserting values into org share action mapping + $this->db->query("insert into vtiger_org_share_action_mapping values(0,'Public: Read Only')"); + $this->db->query("insert into vtiger_org_share_action_mapping values(1,'Public: Read, Create/Edit')"); + $this->db->query("insert into vtiger_org_share_action_mapping values(2,'Public: Read, Create/Edit, Delete')"); + $this->db->query("insert into vtiger_org_share_action_mapping values(3,'Private')"); + + $this->db->query("insert into vtiger_org_share_action_mapping values(4,'Hide Details')"); + $this->db->query("insert into vtiger_org_share_action_mapping values(5,'Hide Details and Add Events')"); + $this->db->query("insert into vtiger_org_share_action_mapping values(6,'Show Details')"); + $this->db->query("insert into vtiger_org_share_action_mapping values(7,'Show Details and Add Events')"); + + + //Inserting for all vtiger_tabs + $def_org_tabid= Array(2,4,6,7,8,9,10,13,16,20,21,22,23,26); + + foreach($def_org_tabid as $def_tabid) + { + $this->db->query("insert into vtiger_org_share_action2tab values(0,".$def_tabid.")"); + $this->db->query("insert into vtiger_org_share_action2tab values(1,".$def_tabid.")"); + $this->db->query("insert into vtiger_org_share_action2tab values(2,".$def_tabid.")"); + $this->db->query("insert into vtiger_org_share_action2tab values(3,".$def_tabid.")"); + } + + //Insert into default_org_sharingrule + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",2,2,0)"); + + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",4,2,2)"); + + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",6,2,0)"); + + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",7,2,0)"); + + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",9,3,1)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",13,2,0)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",16,3,2)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",20,2,0)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",21,2,0)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",22,2,0)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",23,2,0)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",26,2,0)"); + $this->db->query("insert into vtiger_def_org_share values (".$this->db->getUniqueID('vtiger_def_org_share').",8,2,0)"); + + //Populating the DataShare Related Modules + + //Lead Related Module + + //Account Related Module + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",6,2)"); + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",6,13)"); + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",6,20)"); + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",6,22)"); + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",6,23)"); + + //Potential Related Module + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",2,20)"); + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",2,22)"); + + //Quote Related Module + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",20,22)"); + + //SO Related Module + $this->db->query("insert into vtiger_datashare_relatedmodules values (".$this->db->getUniqueID('vtiger_datashare_relatedmodules').",22,23)"); + + + + + // New Secutity End + + + //insert into the vtiger_notificationscheduler vtiger_table + + //insert into related list vtiger_table + //Inserting for vtiger_account related lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Contacts").",'get_contacts',1,'Contacts',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Potentials").",'get_opportunities',2,'Potentials',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Quotes").",'get_quotes',3,'Quotes',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("SalesOrder").",'get_salesorder',4,'Sales Order',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Invoice").",'get_invoices',5,'Invoice',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Calendar").",'get_activities',6,'Activities',0,'add')"); + + //added for the ticket4109 + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Emails").",'get_emails',7,'Emails',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Calendar").",'get_history',8,'Activity History',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Documents").",'get_attachments',9,'Documents',0,'add,select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("HelpDesk").",'get_tickets',10,'HelpDesk',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Accounts").",".getTabid("Products").",'get_products',11,'Products',0,'select')"); + + //Inserting Lead Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Calendar").",'get_activities',1,'Activities',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Emails").",'get_emails',2,'Emails',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Calendar").",'get_history',3,'Activity History',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Documents").",'get_attachments',4,'Documents',0,'add,select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Products").",'get_products',5,'Products',0,'select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Leads").",".getTabid("Campaigns").",'get_campaigns',6,'Campaigns',0,'select')"); + + //Inserting for contact related lists + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Potentials").",'get_opportunities',1,'Potentials',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Calendar").",'get_activities',2,'Activities',0,'add')"); + + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Emails").",'get_emails',3,'Emails',0,'add')"); + + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("HelpDesk").",'get_tickets',4,'HelpDesk',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Quotes").",'get_quotes',5,'Quotes',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("PurchaseOrder").",'get_purchase_orders',6,'Purchase Order',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("SalesOrder").",'get_salesorder',7,'Sales Order',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Products").",'get_products',8,'Products',0,'select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Calendar").",'get_history',9,'Activity History',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Documents").",'get_attachments',10,'Documents',0,'add,select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Contacts").",".getTabid("Campaigns").",'get_campaigns',11,'Campaigns',0,'select')"); + + $this->db->query("INSERT INTO vtiger_relatedlists VALUES(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid('Contacts').",".getTabid('Invoice').",'get_invoices',12,'Invoice',0, 'add')"); + + //Inserting Potential Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("Calendar").",'get_activities',1,'Activities',0,'add')"); + + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("Contacts").",'get_contacts',2,'Contacts',0,'select')"); + + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("Products").",'get_products',3,'Products',0,'select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",0,'get_stage_history',4,'Sales Stage History',0,'')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("Documents").",'get_attachments',5,'Documents',0,'add,select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("Quotes").",'get_Quotes',6,'Quotes',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("SalesOrder").",'get_salesorder',7,'Sales Order',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Potentials").",".getTabid("Calendar").",'get_history',8,'Activity History',0,'')"); + + //Inserting Product Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("HelpDesk").",'get_tickets',1,'HelpDesk',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Documents").",'get_attachments',3,'Documents',0,'add,select')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Quotes").",'get_quotes',4,'Quotes',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("PurchaseOrder").",'get_purchase_orders',5,'Purchase Order',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("SalesOrder").",'get_salesorder',6,'Sales Order',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Invoice").",'get_invoices',7,'Invoice',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("PriceBooks").",'get_product_pricebooks',8,'PriceBooks',0,'add')"); + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Leads").",'get_leads',9,'Leads',0,'select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Accounts").",'get_accounts',10,'Accounts',0,'select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Contacts").",'get_contacts',11,'Contacts',0,'select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Potentials").",'get_opportunities',12,'Potentials',0,'select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Products").",'get_products',13,'Product Bundles',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Products").",".getTabid("Products").",'get_parent_products',14,'Parent Product',0,'')"); + + //Inserting Emails Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Emails").",".getTabid("Contacts").",'get_contacts',1,'Contacts',0,'select,bulkmail')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Emails").",0,'get_users',2,'Users',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Emails").",".getTabid("Documents").",'get_attachments',3,'Documents',0,'add,select')"); + + //Inserting HelpDesk Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("HelpDesk").",".getTabid("Calendar").",'get_activities',1,'Activities',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("HelpDesk").",".getTabid("Documents").",'get_attachments',2,'Documents',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("HelpDesk").",0,'get_ticket_history',3,'Ticket History',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("HelpDesk").",".getTabid("Calendar").",'get_history',4,'Activity History',0,'')"); + + //Inserting PriceBook Related Lists + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("PriceBooks").",14,'get_pricebook_products',2,'Products',0,'select')"); + + // Inserting Vendor Related Lists + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Vendors").",14,'get_products',1,'Products',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Vendors").",21,'get_purchase_orders',2,'Purchase Order',0,'add')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Vendors").",4,'get_contacts',3,'Contacts',0,'select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Vendors").",".getTabid("Emails").",'get_emails',4,'Emails',0,'add')"); + + // Inserting Quotes Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Quotes").",".getTabid("SalesOrder").",'get_salesorder',1,'Sales Order',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Quotes").",9,'get_activities',2,'Activities',0,'add')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Quotes").",".getTabid("Documents").",'get_attachments',3,'Documents',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Quotes").",9,'get_history',4,'Activity History',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Quotes").",0,'get_quotestagehistory',5,'Quote Stage History',0,'')"); + + // Inserting Purchase order Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("PurchaseOrder").",9,'get_activities',1,'Activities',0,'add')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("PurchaseOrder").",".getTabid("Documents").",'get_attachments',2,'Documents',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("PurchaseOrder").",".getTabid("Calendar").",'get_history',3,'Activity History',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("PurchaseOrder").",0,'get_postatushistory',4,'PurchaseOrder Status History',0,'')"); + + // Inserting Sales order Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("SalesOrder").",9,'get_activities',1,'Activities',0,'add')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("SalesOrder").",".getTabid("Documents").",'get_attachments',2,'Documents',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("SalesOrder").",".getTabid("Invoice").",'get_invoices',3,'Invoice',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("SalesOrder").",".getTabid("Calendar").",'get_history',4,'Activity History',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("SalesOrder").",0,'get_sostatushistory',5,'SalesOrder Status History',0,'')"); + + // Inserting Invoice Related Lists + + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Invoice").",9,'get_activities',1,'Activities',0,'add')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Invoice").",".getTabid("Documents").",'get_attachments',2,'Documents',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Invoice").",".getTabid("Calendar").",'get_history',3,'Activity History',0,'')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Invoice").",0,'get_invoicestatushistory',4,'Invoice Status History',0,'')"); + + // Inserting Activities Related Lists + + $this->db->query("insert into vtiger_relatedlists values (".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Calendar").",0,'get_users',1,'Users',0,'')"); + $this->db->query("insert into vtiger_relatedlists values (".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Calendar").",4,'get_contacts',2,'Contacts',0,'')"); + + // Inserting Campaigns Related Lists + + $this->db->query("insert into vtiger_relatedlists values (".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",".getTabid("Contacts").",'get_contacts',1,'Contacts',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values (".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",".getTabid("Leads").",'get_leads',2,'Leads',0,'add,select')"); + $this->db->query("insert into vtiger_relatedlists values (".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",".getTabid("Potentials").",'get_opportunities',3,'Potentials',0,'add')"); + $this->db->query("insert into vtiger_relatedlists values(".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Campaigns").",9,'get_activities',4,'Activities',0,'add')"); + + // Inserting Faq's Related Lists + $this->db->query("insert into vtiger_relatedlists values (".$this->db->getUniqueID('vtiger_relatedlists').",".getTabid("Faq").",".getTabid("Documents").",'get_attachments',1,'Documents',0,'add,select')"); + + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_TASK_NOTIFICATION_DESCRITPION',1,'Task Delay Notification','Tasks delayed beyond 24 hrs ','LBL_TASK_NOTIFICATION')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_BIG_DEAL_DESCRIPTION' ,1,'Big Deal notification','Success! A big deal has been won! ','LBL_BIG_DEAL')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_TICKETS_DESCRIPTION',1,'Pending Tickets notification','Ticket pending please ','LBL_PENDING_TICKETS')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_MANY_TICKETS_DESCRIPTION',1,'Too many tickets Notification','Too many tickets pending against this entity ','LBL_MANY_TICKETS')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label,type) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_START_DESCRIPTION' ,1,'Support Start Notification','10','LBL_START_NOTIFICATION','select')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label,type) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_SUPPORT_DESCRIPTION',1,'Support ending please','11','LBL_SUPPORT_NOTICIATION','select')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label,type) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_SUPPORT_DESCRIPTION_MONTH',1,'Support ending please','12','LBL_SUPPORT_NOTICIATION_MONTH','select')"); + $this->db->query("insert into vtiger_notificationscheduler(schedulednotificationid,schedulednotificationname,active,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_notificationscheduler").",'LBL_ACTIVITY_REMINDER_DESCRIPTION' ,1,'Activity Reminder Notification','This is a reminder notification for the Activity','LBL_ACTIVITY_NOTIFICATION')"); + + //inserting actions for get_attachments + $folderid = $this->db->getUniqueID("vtiger_attachmentsfolder"); + $this->db->query("insert into vtiger_attachmentsfolder values(".$folderid.",'Default','This is a Default Folder',1,1)"); + + //Inserting Inventory Notifications + $invoice_body = 'Dear {HANDLER}, + +The current stock of {PRODUCTNAME} in our warehouse is {CURRENTSTOCK}. Kindly procure required number of units as the stock level is below reorder level {REORDERLEVELVALUE}. + +Please treat this information as Urgent as the invoice is already sent to the customer. + +Severity: Critical + +Thanks, +{CURRENTUSER}'; + + + $this->db->query("insert into vtiger_inventorynotification(notificationid,notificationname,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_inventorynotification").",'InvoiceNotification','{PRODUCTNAME} Stock Level is Low','".$invoice_body." ','InvoiceNotificationDescription')"); + + $quote_body = 'Dear {HANDLER}, + +Quote is generated for {QUOTEQUANTITY} units of {PRODUCTNAME}. The current stock of {PRODUCTNAME} in our warehouse is {CURRENTSTOCK}. + +Severity: Minor + +Thanks, +{CURRENTUSER}'; + + + $this->db->query("insert into vtiger_inventorynotification(notificationid,notificationname,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_inventorynotification").",'QuoteNotification','Quote given for {PRODUCTNAME}','".$quote_body." ','QuoteNotificationDescription')"); + + $so_body = 'Dear {HANDLER}, + +SalesOrder is generated for {SOQUANTITY} units of {PRODUCTNAME}. The current stock of {PRODUCTNAME} in our warehouse is {CURRENTSTOCK}. + +Please treat this information with priority as the sales order is already generated. + +Severity: Major + +Thanks, +{CURRENTUSER}'; + + + $this->db->query("insert into vtiger_inventorynotification(notificationid,notificationname,notificationsubject,notificationbody,label) values (".$this->db->getUniqueID("vtiger_inventorynotification").",'SalesOrderNotification','Sales Order generated for {PRODUCTNAME}','".$so_body." ','SalesOrderNotificationDescription')"); + +//insert into inventory terms and conditions table + + $inv_tandc_text=' + - Unless otherwise agreed in writing by the supplier all invoices are payable within thirty (30) days of the date of invoice, in the currency of the invoice, drawn on a bank based in India or by such other method as is agreed in advance by the Supplier. + + - All prices are not inclusive of VAT which shall be payable in addition by the Customer at the applicable rate.'; + + $this->db->query("insert into vtiger_inventory_tandc(id,type,tandc) values (".$this->db->getUniqueID("vtiger_inventory_tandc").", 'Inventory', '".$inv_tandc_text."')"); + +//insert into email template vtiger_table + + $body='Hello!
    +
    + On behalf of the vtiger team, I am pleased to announce the release of vtiger crm4.2 . This is a feature packed release including the mass email template handling, custom view feature, vtiger_reports feature and a host of other utilities. vtiger runs on all platforms.
    +
    + Notable Features of vtiger are :
    +
    + -Email Client Integration
    + -Trouble Ticket Integration
    + -Invoice Management Integration
    + -Reports Integration
    + -Portal Integration
    + -Enhanced Word Plugin Support
    + -Custom View Integration
    +
    + Known Issues:
    + -ABCD
    + -EFGH
    + -IJKL
    + -MNOP
    + -QRST'; + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Announcement for Release','Announcement for Release','Announcement of a release','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + +$body='name
    +street,
    +city,
    +state,
    + zip)
    +
    + Dear
    +
    + Please check the following invoices that are yet to be paid by you:
    +
    + No. Date Amount
    + 1 1/1/01 $4000
    + 2 2/2//01 $5000
    + 3 3/3/01 $10000
    + 4 7/4/01 $23560
    +
    + Kindly let us know if there are any issues that you feel are pending to be discussed.
    + We will be more than happy to give you a call.
    + We would like to continue our business with you.'; + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Pending Invoices','Invoices Pending','Payment Due','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + + + +$body=' Dear
    +
    +Your proposal on the project XYZW has been reviewed by us
    +and is acceptable in its entirety.
    +
    +We are eagerly looking forward to this project
    +and are pleased about having the opportunity to work
    +together. We look forward to a long standing relationship
    +with your esteemed firm.
    +
    +I would like to take this opportunity to invite you
    +to a game of golf on Wednesday morning 9am at the
    +Cuff Links Ground. We will be waiting for you in the
    +Executive Lounge.
    +
    +Looking forward to seeing you there.'; + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Acceptance Proposal','Acceptance Proposal','Acceptance of Proposal','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + +$body= ' The undersigned hereby acknowledges receipt and delivery of the goods.
    +The undersigned will release the payment subject to the goods being discovered not satisfactory.
    +
    +Signed under seal this '; + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Goods received acknowledgement','Goods received acknowledgement','Acknowledged Receipt of Goods','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + $body= ' Dear
    + We are in receipt of your order as contained in the
    + purchase order form.We consider this to be final and binding on both sides.
    +If there be any exceptions noted, we shall consider them
    +only if the objection is received within ten days of receipt of
    +this notice.
    +
    +Thank you for your patronage.'; + + + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Accept Order','Accept Order','Acknowledgement/Acceptance of Order','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + + +$body='Dear
    +
    +We are relocating our office to
    +11111,XYZDEF Cross,
    +UVWWX Circle
    +The telephone number for this new location is (101) 1212-1328.
    +
    +Our Manufacturing Division will continue operations
    +at 3250 Lovedale Square Avenue, in Frankfurt.
    +
    +We hope to keep in touch with you all.
    +Please update your addressbooks.'; + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Address Change','Change of Address','Address Change','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + +$body='Dear
    +
    +Thank you for extending us the opportunity to meet with
    +you and members of your staff.
    +
    +I know that John Doe serviced your account
    +for many years and made many friends at your firm. He has personally
    +discussed with me the deep relationship that he had with your firm.
    +While his presence will be missed, I can promise that we will
    +continue to provide the fine service that was accorded by
    +John to your firm.
    +
    +I was genuinely touched to receive such fine hospitality.
    +
    +Thank you once again.'; + + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Follow Up','Follow Up','Follow Up of meeting','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + +$body='Congratulations!
    +
    +The numbers are in and I am proud to inform you that our
    +total sales for the previous quarter
    +amounts to $100,000,00.00!. This is the first time
    +we have exceeded the target by almost 30%.
    +We have also beat the previous quarter record by a
    +whopping 75%!
    +
    +Let us meet at Smoking Joe for a drink in the evening!
    + +C you all there guys!'; + + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Target Crossed!','Target Crossed!','Fantastic Sales Spree!','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + +$body='Dear
    +
    +Thank you for your confidence in our ability to serve you.
    +We are glad to be given the chance to serve you.I look
    +forward to establishing a long term partnership with you.
    +Consider me as a friend.
    +Should any need arise,please do give us a call.'; + + + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Thanks Note','Thanks Note','Note of thanks','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + +//Added for HTML Eemail templates.. +//for Customer Portal Login details +$body=' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    $logo$
    vtiger CRM
    The honest Open Source CRM
    +
    + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Dear $contact_name$,
    Thank you very much for subscribing to the vtiger CRM - annual support service.
    Here is your self service portal login details:
    + + + + + + + + + + +

    User ID : $login_name$
    Password: $password$
    $URL$
    +
    NOTE: We suggest you to change your password after logging in first time.

    Help Documentation

    After logging in to vtiger Self-service Portal first time, you can access the vtiger CRM documents from the Documents tab. Following documents are available for your reference:
    +
      +
    • Installation Manual (Windows & Linux OS)
    • +
    • User & Administrator Manual
    • +
    • vtiger Customer Portal - User Manual
    • +
    • vtiger Outlook Plugin - User Manual
    • +
    • vtiger Office Plug-in - User Manual
    • +
    • vtiger Thunderbird Extension - User Manual
    • +
    • vtiger Web Forms - User Manual
    • +
    • vtiger Firefox Tool bar - User Manual
    • +
    +

    Knowledge Base

    Periodically we update frequently asked question based on our customer experiences. You can access the latest articles from the FAQ tab.

    vtiger CRM - Details

    Kindly let us know your current vtiger CRM version and system specification so that we can provide you necessary guidelines to enhance your vtiger CRM system performance. Based on your system specification we alert you about the latest security & upgrade patches.

    Thank you once again and wish you a wonderful experience with vtiger CRM.


    Best Regards
    $support_team$
    www.vtiger.com
    +
    +
    + + + + + + + + + + +
    Shree Narayana Complex, No 11 Sarathy Nagar, Vijaya Nagar , Velachery, Chennai - 600 042 India
    Telephone No: +91 - 44 - 4202 - 1990 Toll Free No: +1 877 788 4437
    Email Id: support@vtiger.com
    +
    +
    '; + + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Customer Login Details','Customer Portal Login Details','Send Portal login details to customer','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + +//for Support end notification before a week +$body=' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    $logo$
    vtiger CRM
    The honest Open Source CRM
    +
    + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Dear $contacts-lastname$,
    This is just a notification mail regarding your support end.
    Priority: Urgent
    Your Support is going to expire on next week
    Please contact support@vtiger.com.





    Sincerly
    Support Team
    www.vtiger.com
    +
    +
    + + + + + + + + + + +
    Shree Narayana Complex, No 11 Sarathy Nagar, Vijaya Nagar , Velachery, Chennai - 600 042 India
    Telephone No: +91 - 44 - 4202 - 1990 Toll Free No: +1 877 788 4437
    Email Id: info@vtiger.com
    +
    +
    '; + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Support end notification before a week','VtigerCRM Support Notification','Send Notification mail to customer before a week of support end date','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + +//for Support end notification before a month +$body=' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + +
    + + + + + + + + + + + + + + +
    $logo$
    vtiger CRM
    The honest Open Source CRM
    +
    + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Dear $contacts-lastname$,
    This is just a notification mail regarding your support end.
    Priority: Normal
    Your Support is going to expire on next month.
    Please contact support@vtiger.com





    Sincerly
    Support Team
    www.vtiger.com
    +
    +
    + + + + + + + + + + +
    Shree Narayana Complex, No 11 Sarathy Nagar, Vijaya Nagar , Velachery, Chennai - 600 042 India
    Telephone No: +91 - 44 - 4202 - 1990 Toll Free No: +1 877 788 4437
    Email Id: info@vtiger.com
    +
    +
    '; + $this->db->query("insert into vtiger_emailtemplates(foldername,templatename,subject,description,body,deleted,templateid) values ('Public','Support end notification before a month','VtigerCRM Support Notification','Send Notification mail to customer before a month of support end date','".$body."',0,".$this->db->getUniqueID('vtiger_emailtemplates').")"); + + + + //Insert into vtiger_organizationdetails vtiger_table + $this->db->query("insert into vtiger_organizationdetails(organizationname,address,city,state,country,code,phone,fax,website,logoname) values ('vtiger',' 40-41-42, Sivasundar Apartments, Flat D-II, Shastri Street, Velachery','Chennai','Tamil Nadu','India','600 042','+91-44-5202-1990','+91-44-5202-1990','www.vtiger.com','vtiger-crm-logo.jpg')"); + + + $this->db->query("insert into vtiger_actionmapping values(0,'Save',0)"); + $this->db->query("insert into vtiger_actionmapping values(1,'EditView',0)"); + $this->db->query("insert into vtiger_actionmapping values(2,'Delete',0)"); + $this->db->query("insert into vtiger_actionmapping values(3,'index',0)"); + $this->db->query("insert into vtiger_actionmapping values(4,'DetailView',0)"); + $this->db->query("insert into vtiger_actionmapping values(5,'Import',0)"); + $this->db->query("insert into vtiger_actionmapping values(6,'Export',0)"); + //$this->db->query("insert into vtiger_actionmapping values(7,'AddBusinessCard',0)"); + $this->db->query("insert into vtiger_actionmapping values(8,'Merge',0)"); + $this->db->query("insert into vtiger_actionmapping values(1,'VendorEditView',1)"); + $this->db->query("insert into vtiger_actionmapping values(4,'VendorDetailView',1)"); + $this->db->query("insert into vtiger_actionmapping values(0,'SaveVendor',1)"); + $this->db->query("insert into vtiger_actionmapping values(2,'DeleteVendor',1)"); + $this->db->query("insert into vtiger_actionmapping values(1,'PriceBookEditView',1)"); + $this->db->query("insert into vtiger_actionmapping values(4,'PriceBookDetailView',1)"); + $this->db->query("insert into vtiger_actionmapping values(0,'SavePriceBook',1)"); + $this->db->query("insert into vtiger_actionmapping values(2,'DeletePriceBook',1)"); + $this->db->query("insert into vtiger_actionmapping values(9,'ConvertLead',0)"); + $this->db->query("insert into vtiger_actionmapping values(1,'DetailViewAjax',1)"); + $this->db->query("insert into vtiger_actionmapping values(4,'TagCloud',1)"); + $this->db->query("insert into vtiger_actionmapping values(1,'QuickCreate',1)"); + $this->db->query("insert into vtiger_actionmapping values(3,'Popup',1)"); + $this->db->query("insert into vtiger_actionmapping values(10,'DuplicatesHandling',0)"); + + //Insert values for vtiger_moduleowners vtiger_table which contains the modules and their vtiger_users. default user id admin - after 4.2 patch 2 + $module_array = Array('Potentials','Contacts','Accounts','Leads','Documents','Calendar','Emails','HelpDesk','Products','Faq','Vendors','PriceBooks','Quotes','PurchaseOrder','SalesOrder','Invoice','Reports','Campaigns'); + foreach($module_array as $mod) + { + $this->db->query("insert into vtiger_moduleowners values(".getTabid($mod).",1)"); + } + //added by jeri for category view from db + $this->db->query("insert into vtiger_parenttab values (1,'My Home Page',1,0)"); + $this->db->query("insert into vtiger_parenttab values (2,'Marketing',2,0)"); + $this->db->query("insert into vtiger_parenttab values (3,'Sales',3,0)"); + $this->db->query("insert into vtiger_parenttab values (4,'Support',4,0)"); + $this->db->query("insert into vtiger_parenttab values (5,'Analytics',5,0)"); + $this->db->query("insert into vtiger_parenttab values (6,'Inventory',6,0)"); + $this->db->query("insert into vtiger_parenttab values (7,'Tools',7,0)"); + $this->db->query("insert into vtiger_parenttab values (8,'Settings',8,0)"); + + $this->db->query("insert into vtiger_parenttabrel values (1,9,2)"); + $this->db->query("insert into vtiger_parenttabrel values (1,28,4)"); + $this->db->query("insert into vtiger_parenttabrel values (1,3,1)"); + $this->db->query("insert into vtiger_parenttabrel values (3,7,1)"); + $this->db->query("insert into vtiger_parenttabrel values (3,6,2)"); + $this->db->query("insert into vtiger_parenttabrel values (3,4,3)"); + $this->db->query("insert into vtiger_parenttabrel values (3,2,4)"); + $this->db->query("insert into vtiger_parenttabrel values (3,20,5)"); + $this->db->query("insert into vtiger_parenttabrel values (3,22,6)"); + $this->db->query("insert into vtiger_parenttabrel values (3,23,7)"); + $this->db->query("insert into vtiger_parenttabrel values (3,19,8)"); + $this->db->query("insert into vtiger_parenttabrel values (3,8,9)"); + $this->db->query("insert into vtiger_parenttabrel values (4,13,1)"); + $this->db->query("insert into vtiger_parenttabrel values (4,15,2)"); + $this->db->query("insert into vtiger_parenttabrel values (4,6,3)"); + $this->db->query("insert into vtiger_parenttabrel values (4,4,4)"); + $this->db->query("insert into vtiger_parenttabrel values (4,8,5)"); + $this->db->query("insert into vtiger_parenttabrel values (5,1,2)"); + $this->db->query("insert into vtiger_parenttabrel values (5,25,1)"); + $this->db->query("insert into vtiger_parenttabrel values (6,14,1)"); + $this->db->query("insert into vtiger_parenttabrel values (6,18,2)"); + $this->db->query("insert into vtiger_parenttabrel values (6,19,3)"); + $this->db->query("insert into vtiger_parenttabrel values (6,21,4)"); + $this->db->query("insert into vtiger_parenttabrel values (6,22,5)"); + $this->db->query("insert into vtiger_parenttabrel values (6,20,6)"); + $this->db->query("insert into vtiger_parenttabrel values (6,23,7)"); + $this->db->query("insert into vtiger_parenttabrel values (7,24,1)"); + $this->db->query("insert into vtiger_parenttabrel values (7,27,2)"); + $this->db->query("insert into vtiger_parenttabrel values (7,8,3)"); + $this->db->query("insert into vtiger_parenttabrel values (2,26,1)"); + $this->db->query("insert into vtiger_parenttabrel values (2,6,2)"); + $this->db->query("insert into vtiger_parenttabrel values (2,4,3)"); + $this->db->query("insert into vtiger_parenttabrel values (2,28,4)"); + $this->db->query("insert into vtiger_parenttabrel values (4,28,7)"); + $this->db->query("insert into vtiger_parenttabrel values (2,7,5)"); + $this->db->query("insert into vtiger_parenttabrel values (2,9,6)"); + $this->db->query("insert into vtiger_parenttabrel values (4,9,8)"); + $this->db->query("insert into vtiger_parenttabrel values (2,8,8)"); + $this->db->query("insert into vtiger_parenttabrel values (3,9,11)"); + + //add settings page to database starts + $this->addEntriesForSettings(); + //add settings page to database end + + //Added to populate the default inventory tax informations + $vatid = $this->db->getUniqueID("vtiger_inventorytaxinfo"); + $salesid = $this->db->getUniqueID("vtiger_inventorytaxinfo"); + $serviceid = $this->db->getUniqueID("vtiger_inventorytaxinfo"); + $this->db->query("insert into vtiger_inventorytaxinfo values($vatid,'tax".$vatid."','VAT','4.50','0')"); + $this->db->query("insert into vtiger_inventorytaxinfo values($salesid,'tax".$salesid."','Sales','10.00','0')"); + $this->db->query("insert into vtiger_inventorytaxinfo values($serviceid,'tax".$serviceid."','Service','12.50','0')"); + //After added these taxes we should add these taxes as columns in vtiger_inventoryproductrel table + $this->db->query("alter table vtiger_inventoryproductrel add column tax$vatid decimal(7,3) default NULL"); + $this->db->query("alter table vtiger_inventoryproductrel add column tax$salesid decimal(7,3) default NULL"); + $this->db->query("alter table vtiger_inventoryproductrel add column tax$serviceid decimal(7,3) default NULL"); + + //Added to handle picklist uniqueid for the picklist values + //$this->db->query("insert into vtiger_picklistvalues_seq values(1)"); + + //Added to populate the default Shipping & Hanlding tax informations + $shvatid = $this->db->getUniqueID("vtiger_shippingtaxinfo"); + $shsalesid = $this->db->getUniqueID("vtiger_shippingtaxinfo"); + $shserviceid = $this->db->getUniqueID("vtiger_shippingtaxinfo"); + $this->db->query("insert into vtiger_shippingtaxinfo values($shvatid,'shtax".$shvatid."','VAT','4.50','0')"); + $this->db->query("insert into vtiger_shippingtaxinfo values($shsalesid,'shtax".$shsalesid."','Sales','10.00','0')"); + $this->db->query("insert into vtiger_shippingtaxinfo values($shserviceid,'shtax".$shserviceid."','Service','12.50','0')"); + //After added these taxes we should add these taxes as columns in vtiger_inventoryshippingrel table + $this->db->query("alter table vtiger_inventoryshippingrel add column shtax$shvatid decimal(7,3) default NULL"); + $this->db->query("alter table vtiger_inventoryshippingrel add column shtax$shsalesid decimal(7,3) default NULL"); + $this->db->query("alter table vtiger_inventoryshippingrel add column shtax$shserviceid decimal(7,3) default NULL"); + + //version file is included here because without including this file version cannot be get + include('vtigerversion.php'); + $this->db->query("insert into vtiger_version values(".$this->db->getUniqueID('vtiger_version').",'".$vtiger_current_version."','".$vtiger_current_version."')"); + + //Register default language English + require_once('vtlib/Vtiger/Language.php'); + $vtlanguage = new Vtiger_Language(); + $vtlanguage->register('en_us','US English','English',true,true,true); + + $this->insertUser2mergefields(0); + $this->insertUser2mergefields(1); + $this->db->query("update vtiger_user2mergefields set visible=1 where fieldid in(1,38,40,65,104,106,111,152,156,255)"); + $this->initWebservices(); + + /** + * Setup module sequence numbering. + */ + $modseq = array( + 'Leads' =>'LEA', + 'Accounts' =>'ACC', + 'Campaigns' =>'CAM', + 'Contacts' =>'CON', + 'Potentials'=>'POT', + 'HelpDesk' =>'TT', + 'Quotes' =>'QUO', + 'SalesOrder'=>'SO', + 'PurchaseOrder'=>'PO', + 'Invoice' =>'INV', + 'Products' =>'PRO', + 'Vendors' =>'VEN', + 'PriceBooks'=>'PB', + 'Faq' =>'FAQ', + 'Documents' =>'DOC' + ); + foreach($modseq as $modname => $prefix) { + $this->addInventoryRows( + array( + array('semodule'=>$modname, 'active'=>'1','prefix'=>$prefix,'startid'=>'1','curid'=>'1') + ) + ); + } + + // Adding Sharing Types for Reports + $this->db->query("insert into vtiger_reportfilters values(1,'Private')"); + $this->db->query("insert into vtiger_reportfilters values(2,'Public')"); + $this->db->query("insert into vtiger_reportfilters values(3,'Shared')"); + + require_once('modules/Utilities/Currencies.php'); + foreach($currencies as $key=>$value){ + $this->db->query("insert into vtiger_currencies values(".$this->db->getUniqueID("vtiger_currencies").",'$key','".$value[0]."','".$value[1]."')"); + } + + } + + //Added to insert the records in vtiger_user_mergefields + function insertUser2mergefields($userid){ + global $log, $adb; + $log->debug("Entering insertUser2mergefields(".$userid.") method ..."); + $log->info("in insertUser2mergefields ".$userid); + + //$this->db->database->SetFetchMode(ADODB_FETCH_ASSOC); + $tab_res = $adb->query("SELECT distinct tabid FROM vtiger_tab"); + $noOfTabs = $adb->num_rows($tab_res); + for($i=0;$i<$noOfTabs;$i++) { + $tab_id = $this->db->query_result($tab_res,$i,'tabid'); + $fld_result = getFieldsResultForMerge($tab_id); + if ($fld_result != null) { + $num_rows = $this->db->num_rows($fld_result); + for($j=0; $j<$num_rows; $j++) { + $field_id = $this->db->query_result($fld_result,$j,'fieldid'); + $data_type = explode("~",$this->db->query_result($fld_result,$j,'typeofdata')); + if($data_type[1] == 'M') { + $visible = 1; + $this->db->query("insert into vtiger_user2mergefields values ($userid, $tab_id, $field_id, $visible)"); + } + } + } + } + $log->debug("Exiting insertUser2mergefields method ..."); + } + + function initWebservices(){ + $this->vtws_addEntityInfo(); + $this->vtws_addOperationInfo(); + $this->vtws_addFieldTypeInformation(); + } + + function vtws_addOperationInfo(){ + $operationMeta = array( + "login"=>array( + "include"=>array( + "include/Webservices/Login.php" + ), + "handler"=>"vtws_login", + "params"=>array( + "username"=>"String", + "accessKey"=>"String" + ), + "prelogin"=>1, + "type"=>"POST" + ), + "retrieve"=>array( + "include"=>array( + "include/Webservices/Retrieve.php" + ), + "handler"=>"vtws_retrieve", + "params"=>array( + "id"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "create"=>array( + "include"=>array( + "include/Webservices/Create.php" + ), + "handler"=>"vtws_create", + "params"=>array( + "elementType"=>"String", + "element"=>"encoded" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "update"=>array( + "include"=>array( + "include/Webservices/Update.php" + ), + "handler"=>"vtws_update", + "params"=>array( + "element"=>"encoded" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "delete"=>array( + "include"=>array( + "include/Webservices/Delete.php" + ), + "handler"=>"vtws_delete", + "params"=>array( + "id"=>"String" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "sync"=>array( + "include"=>array( + "include/Webservices/GetUpdates.php" + ), + "handler"=>"vtws_sync", + "params"=>array( + "modifiedTime"=>"DateTime", + "elementType"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "query"=>array( + "include"=>array( + "include/Webservices/Query.php" + ), + "handler"=>"vtws_query", + "params"=>array( + "query"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "logout"=>array( + "include"=>array( + "include/Webservices/Logout.php" + ), + "handler"=>"vtws_logout", + "params"=>array( + "sessionName"=>"String" + ), + "prelogin"=>0, + "type"=>"POST" + ), + "listtypes"=>array( + "include"=>array( + "include/Webservices/ModuleTypes.php" + ), + "handler"=>"vtws_listtypes", + "params"=>array(), + "prelogin"=>0, + "type"=>"GET" + ), + "getchallenge"=>array( + "include"=>array( + "include/Webservices/AuthToken.php" + ), + "handler"=>"vtws_getchallenge", + "params"=>array( + "username"=>"String" + ), + "prelogin"=>1, + "type"=>"GET" + ), + "describe"=>array( + "include"=>array( + "include/Webservices/DescribeObject.php" + ), + "handler"=>"vtws_describe", + "params"=>array( + "elementType"=>"String" + ), + "prelogin"=>0, + "type"=>"GET" + ), + "extendsession"=>array( + "include"=>array( + "include/Webservices/ExtendSession.php" + ), + "handler"=>"vtws_extendSession", + 'params'=>array(), + "prelogin"=>1, + "type"=>"POST" + ) + ); + $createOperationQuery = "insert into vtiger_ws_operation(operationid,name,handler_path,handler_method,type,prelogin) + values (?,?,?,?,?,?);"; + $createOperationParamsQuery = "insert into vtiger_ws_operation_parameters(operationid,name,type,sequence) + values (?,?,?,?);"; + foreach ($operationMeta as $operationName => $operationDetails) { + $operationId = $this->db->getUniqueID("vtiger_ws_operation"); + $result = $this->db->pquery($createOperationQuery,array($operationId,$operationName,$operationDetails['include'], + $operationDetails['handler'],$operationDetails['type'],$operationDetails['prelogin'])); + $params = $operationDetails['params']; + $sequence = 1; + foreach ($params as $paramName => $paramType) { + $result = $this->db->pquery($createOperationParamsQuery,array($operationId,$paramName,$paramType,$sequence++)); + } + } + } + + function vtws_addEntityInfo(){ + require_once 'include/Webservices/Utils.php'; + $names = vtws_getModuleNameList(); + $moduleHandler = array('file'=>'include/Webservices/VtigerModuleOperation.php', + 'class'=>'VtigerModuleOperation'); + + foreach ($names as $tab){ + if(in_array($tab,array('Rss','Webmails','Recyclebin'))){ + continue; + } + $entityId = $this->db->getUniqueID("vtiger_ws_entity"); + $this->db->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)', + array($entityId,$tab,$moduleHandler['file'],$moduleHandler['class'],1)); + } + + $entityId = $this->db->getUniqueID("vtiger_ws_entity"); + $this->db->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)', + array($entityId,'Events',$moduleHandler['file'],$moduleHandler['class'],1)); + + + $entityId = $this->db->getUniqueID("vtiger_ws_entity"); + $this->db->pquery('insert into vtiger_ws_entity(id,name,handler_path,handler_class,ismodule) values (?,?,?,?,?)', + array($entityId,'Users',$moduleHandler['file'],$moduleHandler['class'],1)); + + vtws_addDefaultActorTypeEntity('Groups',array('fieldNames'=>'groupname', + 'indexField'=>'groupid','tableName'=>'vtiger_groups')); + + require_once("include/Webservices/WebServiceError.php"); + require_once 'include/Webservices/VtigerWebserviceObject.php'; + $webserviceObject = VtigerWebserviceObject::fromName($this->db,'Groups'); + $this->db->pquery("insert into vtiger_ws_entity_tables(webservice_entity_id,table_name) values + (?,?)",array($webserviceObject->getEntityId(),'vtiger_groups')); + + vtws_addDefaultActorTypeEntity('Currency',array('fieldNames'=>'currency_name', + 'indexField'=>'id','tableName'=>'vtiger_currency_info')); + + $webserviceObject = VtigerWebserviceObject::fromName($this->db,'Currency'); + $this->db->pquery("insert into vtiger_ws_entity_tables(webservice_entity_id,table_name) values (?,?)", + array($webserviceObject->getEntityId(),'vtiger_currency_info')); + + vtws_addDefaultActorTypeEntity('DocumentFolders',array('fieldNames'=>'foldername', + 'indexField'=>'folderid','tableName'=>'vtiger_attachmentsfolder')); + $webserviceObject = VtigerWebserviceObject::fromName($this->db,'DocumentFolders'); + $this->db->pquery("insert into vtiger_ws_entity_tables(webservice_entity_id,table_name) values (?,?)", + array($webserviceObject->getEntityId(),'vtiger_attachmentsfolder')); + + } + + function vtws_addFieldTypeInformation(){ + $fieldTypeInfo = array('picklist'=>array(15,16),'text'=>array(19,20,21,24),'autogenerated'=>array(3),'phone'=>array(11), + 'multipicklist'=>array(33),'url'=>array(17),'skype'=>array(85),'boolean'=>array(56,156),'owner'=>array(53), + 'file'=>array(61,28)); + + foreach($fieldTypeInfo as $type=>$uitypes){ + foreach($uitypes as $uitype){ + $result = $this->db->pquery("insert into vtiger_ws_fieldtype(uitype,fieldtype) values(?,?)",array($uitype,$type)); + if(!is_object($result)){ + "Query for fieldtype details($uitype:uitype,$type:fieldtype)"; + } + } + } + + $this->vtws_addReferenceTypeInformation(); + } + + function vtws_addReferenceTypeInformation(){ + $referenceMapping = array("50"=>array("Accounts"),"51"=>array("Accounts"),"57"=>array("Contacts"), + "58"=>array("Campaigns"),"73"=>array("Accounts"),"75"=>array("Vendors"),"76"=>array("Potentials"), + "78"=>array("Quotes"),"80"=>array("SalesOrder"),"81"=>array("Vendors"),"101"=>array("Users"),"52"=>array("Users"), + "357"=>array("Contacts","Accounts","Leads","Users","Vendors"),"59"=>array("Products"), + "66"=>array("Leads","Accounts","Potentials","HelpDesk"),"77"=>array("Users"),"68"=>array("Contacts","Accounts"), + "117"=>array('Currency'),"116"=>array('Currency'),'26'=>array('DocumentFolders'),'10'=>array()); + + foreach($referenceMapping as $uitype=>$referenceArray){ + $success = true; + $result = $this->db->pquery("insert into vtiger_ws_fieldtype(uitype,fieldtype) values(?,?)",array($uitype,"reference")); + if(!is_object($result)){ + $success=false; + } + $result = $this->db->pquery("select * from vtiger_ws_fieldtype where uitype=?",array($uitype)); + $rowCount = $this->db->num_rows($result); + for($i=0;$i<$rowCount;$i++){ + $fieldTypeId = $this->db->query_result($result,$i,"fieldtypeid"); + foreach($referenceArray as $index=>$referenceType){ + $result = $this->db->pquery("insert into vtiger_ws_referencetype(fieldtypeid,type) values(?,?)",array($fieldTypeId,$referenceType)); + if(!is_object($result)){ + echo "failed for: $referenceType, uitype: $fieldTypeId"; + $success=false; + } + } + } + if(!$success){ + echo "Migration Query Failed"; + } + } + + $success = true; + $fieldTypeId = $this->db->getUniqueID("vtiger_ws_entity_fieldtype"); + $result = $this->db->pquery("insert into vtiger_ws_entity_fieldtype(fieldtypeid,table_name,field_name,fieldtype) values(?,?,?,?);", + array($fieldTypeId,'vtiger_attachmentsfolder','createdby',"reference")); + if(!is_object($result)){ + echo "failed fo init
    "; + $success=false; + } + $result = $this->db->pquery("insert into vtiger_ws_entity_referencetype(fieldtypeid,type) values(?,?)",array($fieldTypeId,'Users')); + if(!is_object($result)){ + echo "failed for: Users, fieldtypeid: $fieldTypeId"; + $success=false; + } + if(!$success){ + echo "Migration Query Failed"; + } + + } + + function addInventoryRows($paramArray){ + global $adb; + + $fieldCreateCount = 0; + + for($index = 0; $index < count($paramArray); ++$index) { + $criteria = $paramArray[$index]; + + $semodule = $criteria['semodule']; + + $modfocus = CRMEntity::getInstance($semodule); + $modfocus->setModuleSeqNumber('configure', $semodule, $criteria['prefix'], $criteria['startid']); + } + } + + /** + * this function adds the entries for settings page + * it assumes entries as were present on 10-12-208 + */ + function addEntriesForSettings(){ + global $adb; + + //icons for all fields + $icons = array("ico-users.gif", + "ico-roles.gif", + "ico-profile.gif", + "ico-groups.gif", + "shareaccess.gif", + "orgshar.gif", + "audit.gif", + "set-IcoLoginHistory.gif", + "vtlib_modmng.gif", + "picklist.gif", + "ViewTemplate.gif", + "mailmarge.gif", + "notification.gif", + "inventory.gif", + "company.gif", + "ogmailserver.gif", + "backupserver.gif", + "assign.gif", + "currency.gif", + "taxConfiguration.gif", + "system.gif", + "proxy.gif", + "announ.gif", + "set-IcoTwoTabConfig.gif", + "terms.gif", + "settingsInvNumber.gif", + "mailScanner.gif", + "settingsWorkflow.png"); + + //labels for blocks + $blocks = array('LBL_MODULE_MANAGER', + 'LBL_USER_MANAGEMENT', + 'LBL_STUDIO', + 'LBL_COMMUNICATION_TEMPLATES', + 'LBL_OTHER_SETTINGS'); + + //field names + $names = array('LBL_USERS', + 'LBL_ROLES', + 'LBL_PROFILES', + 'USERGROUPLIST', + 'LBL_SHARING_ACCESS', + 'LBL_FIELDS_ACCESS', + 'LBL_AUDIT_TRAIL', + 'LBL_LOGIN_HISTORY_DETAILS', + 'VTLIB_LBL_MODULE_MANAGER', + 'LBL_PICKLIST_EDITOR', + 'EMAILTEMPLATES', + 'LBL_MAIL_MERGE', + 'NOTIFICATIONSCHEDULERS', + 'INVENTORYNOTIFICATION', + 'LBL_COMPANY_DETAILS', + 'LBL_MAIL_SERVER_SETTINGS', + 'LBL_BACKUP_SERVER_SETTINGS', + 'LBL_ASSIGN_MODULE_OWNERS', + 'LBL_CURRENCY_SETTINGS', + 'LBL_TAX_SETTINGS', + 'LBL_SYSTEM_INFO', + 'LBL_PROXY_SETTINGS', + 'LBL_ANNOUNCEMENT', + 'LBL_DEFAULT_MODULE_VIEW', + 'INVENTORYTERMSANDCONDITIONS', + 'LBL_CUSTOMIZE_MODENT_NUMBER', + 'LBL_MAIL_SCANNER', + 'LBL_LIST_WORKFLOWS',); + + + $name_blocks = array('LBL_USERS'=>'LBL_USER_MANAGEMENT', + 'LBL_ROLES'=>'LBL_USER_MANAGEMENT', + 'LBL_PROFILES'=>'LBL_USER_MANAGEMENT', + 'USERGROUPLIST'=>'LBL_USER_MANAGEMENT', + 'LBL_SHARING_ACCESS'=>'LBL_USER_MANAGEMENT', + 'LBL_FIELDS_ACCESS'=>'LBL_USER_MANAGEMENT', + 'LBL_AUDIT_TRAIL'=>'LBL_USER_MANAGEMENT', + 'LBL_LOGIN_HISTORY_DETAILS'=>'LBL_USER_MANAGEMENT', + 'VTLIB_LBL_MODULE_MANAGER'=>'LBL_STUDIO', + 'LBL_PICKLIST_EDITOR'=>'LBL_STUDIO', + 'EMAILTEMPLATES'=>'LBL_COMMUNICATION_TEMPLATES', + 'LBL_MAIL_MERGE'=>'LBL_COMMUNICATION_TEMPLATES', + 'NOTIFICATIONSCHEDULERS'=>'LBL_COMMUNICATION_TEMPLATES', + 'INVENTORYNOTIFICATION'=>'LBL_COMMUNICATION_TEMPLATES', + 'LBL_COMPANY_DETAILS'=>'LBL_COMMUNICATION_TEMPLATES', + 'LBL_MAIL_SERVER_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_BACKUP_SERVER_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_ASSIGN_MODULE_OWNERS'=>'LBL_OTHER_SETTINGS', + 'LBL_CURRENCY_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_TAX_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_SYSTEM_INFO'=>'LBL_OTHER_SETTINGS', + 'LBL_PROXY_SETTINGS'=>'LBL_OTHER_SETTINGS', + 'LBL_ANNOUNCEMENT'=>'LBL_OTHER_SETTINGS', + 'LBL_DEFAULT_MODULE_VIEW'=>'LBL_OTHER_SETTINGS', + 'INVENTORYTERMSANDCONDITIONS'=>'LBL_OTHER_SETTINGS', + 'LBL_CUSTOMIZE_MODENT_NUMBER'=>'LBL_OTHER_SETTINGS', + 'LBL_MAIL_SCANNER'=>'LBL_OTHER_SETTINGS', + 'LBL_LIST_WORKFLOWS'=>'LBL_OTHER_SETTINGS',); + + + //description for fields + $description = array('LBL_USER_DESCRIPTION', + 'LBL_ROLE_DESCRIPTION', + 'LBL_PROFILE_DESCRIPTION', + 'LBL_GROUP_DESCRIPTION', + 'LBL_SHARING_ACCESS_DESCRIPTION', + 'LBL_SHARING_FIELDS_DESCRIPTION', + 'LBL_AUDIT_DESCRIPTION', + 'LBL_LOGIN_HISTORY_DESCRIPTION', + 'VTLIB_LBL_MODULE_MANAGER_DESCRIPTION', + 'LBL_PICKLIST_DESCRIPTION', + 'LBL_EMAIL_TEMPLATE_DESCRIPTION', + 'LBL_MAIL_MERGE_DESCRIPTION', + 'LBL_NOTIF_SCHED_DESCRIPTION', + 'LBL_INV_NOTIF_DESCRIPTION', + 'LBL_COMPANY_DESCRIPTION', + 'LBL_MAIL_SERVER_DESCRIPTION', + 'LBL_BACKUP_SERVER_DESCRIPTION', + 'LBL_MODULE_OWNERS_DESCRIPTION', + 'LBL_CURRENCY_DESCRIPTION', + 'LBL_TAX_DESCRIPTION', + 'LBL_SYSTEM_DESCRIPTION', + 'LBL_PROXY_DESCRIPTION', + 'LBL_ANNOUNCEMENT_DESCRIPTION', + 'LBL_DEFAULT_MODULE_VIEW_DESC', + 'LBL_INV_TANDC_DESCRIPTION', + 'LBL_CUSTOMIZE_MODENT_NUMBER_DESCRIPTION', + 'LBL_MAIL_SCANNER_DESCRIPTION', + 'LBL_LIST_WORKFLOWS_DESCRIPTION'); + + $links = array('index.php?module=Administration&action=index&parenttab=Settings', + 'index.php?module=Settings&action=listroles&parenttab=Settings', + 'index.php?module=Settings&action=ListProfiles&parenttab=Settings', + 'index.php?module=Settings&action=listgroups&parenttab=Settings', + 'index.php?module=Settings&action=OrgSharingDetailView&parenttab=Settings', + 'index.php?module=Settings&action=DefaultFieldPermissions&parenttab=Settings', + 'index.php?module=Settings&action=AuditTrailList&parenttab=Settings', + 'index.php?module=Settings&action=ListLoginHistory&parenttab=Settings', + 'index.php?module=Settings&action=ModuleManager&parenttab=Settings', + 'index.php?module=PickList&action=PickList&parenttab=Settings', + 'index.php?module=Settings&action=listemailtemplates&parenttab=Settings', + 'index.php?module=Settings&action=listwordtemplates&parenttab=Settings', + 'index.php?module=Settings&action=listnotificationschedulers&parenttab=Settings', + 'index.php?module=Settings&action=listinventorynotifications&parenttab=Settings', + 'index.php?module=Settings&action=OrganizationConfig&parenttab=Settings', + 'index.php?module=Settings&action=EmailConfig&parenttab=Settings', + 'index.php?module=Settings&action=BackupServerConfig&parenttab=Settings', + 'index.php?module=Settings&action=ListModuleOwners&parenttab=Settings', + 'index.php?module=Settings&action=CurrencyListView&parenttab=Settings', + 'index.php?module=Settings&action=TaxConfig&parenttab=Settings', + 'index.php?module=System&action=listsysconfig&parenttab=Settings', + 'index.php?module=Settings&action=ProxyServerConfig&parenttab=Settings', + 'index.php?module=Settings&action=Announcements&parenttab=Settings', + 'index.php?module=Settings&action=DefModuleView&parenttab=Settings', + 'index.php?module=Settings&action=OrganizationTermsandConditions&parenttab=Settings', + 'index.php?module=Settings&action=CustomModEntityNo&parenttab=Settings', + 'index.php?module=Settings&action=MailScanner&parenttab=Settings', + 'index.php?module=com_vtiger_workflow&action=workflowlist&parenttab=Settings',); + + //insert settings blocks + $count = count($blocks); + for($i=0; $i<$count; $i++){ + $adb->query("insert into vtiger_settings_blocks values (".$adb->getUniqueID('vtiger_settings_blocks').", '$blocks[$i]', $i+1)"); + } + + $count = count($icons); + //insert settings fields + for($i=0, $seq=1; $i<$count; $i++, $seq++){ + if($i==8 || $i==12 || $i==18){ + $seq = 1; + } + $adb->query("insert into vtiger_settings_field (fieldid, blockid, name, iconpath, description, linkto, sequence) values (".$adb->getUniqueID('vtiger_settings_field').", ".getSettingsBlockId($name_blocks[$names[$i]]).", '$names[$i]', '$icons[$i]', '$description[$i]', '$links[$i]', $seq)"); + } + + // for Workflow in settings page of every module + $module_manager_id = getSettingsBlockId('LBL_MODULE_MANAGER'); + $result = $adb->pquery("SELECT max(sequence) AS maxseq FROM vtiger_settings_field WHERE blockid = ?",array($module_manager_id)); + $maxseq = $adb->query_result($result,0,'maxseq'); + if($maxseq < 0 || $maxseq == NULL){ + $maxseq=1; + } + $adb->pquery("INSERT INTO vtiger_settings_field (fieldid, blockid, name, iconpath, description, linkto, sequence) VALUES (?,?,?,?,?,?,?)",array($adb->getUniqueID('vtiger_settings_field'), $module_manager_id, 'LBL_WORKFLOW_LIST', 'settingsWorkflow.png', 'LBL_AVAILABLE_WORKLIST_LIST', 'index.php?module=com_vtiger_workflow&action=workflowlist', $maxseq)); + + //hide the system details tab for now + $adb->query("update vtiger_settings_field set active=1 where name='LBL_SYSTEM_INFO'"); + } +} +?> diff --git a/oss/vtiger/trunk/modules/Users/Delete.php b/oss/vtiger/trunk/modules/Users/Delete.php new file mode 100644 index 00000000..18080c31 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Delete.php @@ -0,0 +1,18 @@ +pquery($sql, array($_REQUEST['record'], $_REQUEST['return_id'])); + +if($_REQUEST['return_module'] == 'Calendar') + $mode ='&activity_mode=Events'; + +header("Location: index.php?module=".vtlib_purify($_REQUEST['return_module'])."&action=".vtlib_purify($_REQUEST['return_action']).$mode."&record=".vtlib_purify($_REQUEST['return_id'])."&relmodule=".vtlib_purify($_REQUEST['module'])); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DeleteGroup.php b/oss/vtiger/trunk/modules/Users/DeleteGroup.php new file mode 100644 index 00000000..ae1915df --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DeleteGroup.php @@ -0,0 +1,30 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DeleteProfile.php b/oss/vtiger/trunk/modules/Users/DeleteProfile.php new file mode 100644 index 00000000..79d44e67 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DeleteProfile.php @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DeleteRole.php b/oss/vtiger/trunk/modules/Users/DeleteRole.php new file mode 100644 index 00000000..4ec84d9d --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DeleteRole.php @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DeleteSharingRule.php b/oss/vtiger/trunk/modules/Users/DeleteSharingRule.php new file mode 100644 index 00000000..fa992271 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DeleteSharingRule.php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DeleteUser.php b/oss/vtiger/trunk/modules/Users/DeleteUser.php new file mode 100644 index 00000000..b721dbdb --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DeleteUser.php @@ -0,0 +1,77 @@ +pquery($sql1, array($tran_id, $del_id)); +$sql2 = "update vtiger_crmentity set smownerid=? where smownerid=?"; +$adb->pquery($sql2, array($tran_id, $del_id)); +$sql3 = "update vtiger_crmentity set modifiedby=? where modifiedby=?"; +$adb->pquery($sql3, array($tran_id, $del_id)); + +//deleting from vtiger_tracker +$sql4 = "delete from vtiger_tracker where user_id=?"; +$adb->pquery($sql4, array($del_id)); + +//updating created by in vtiger_lar +$sql5 = "update vtiger_lar set createdby=? where createdby=?"; +$adb->pquery($sql5, array($tran_id, $del_id)); + +//updating the vtiger_import_maps +$sql6 ="update vtiger_import_maps set assigned_user_id=? where assigned_user_id=?"; +$adb->pquery($sql6, array($tran_id, $del_id)); + +//update assigned_user_id in vtiger_files +$sql7 ="update vtiger_files set assigned_user_id=? where assigned_user_id=?"; +$adb->pquery($sql7, array($tran_id, $del_id)); + +//update assigned_user_id in vtiger_users_last_import +$sql8 = "update vtiger_users_last_import set assigned_user_id=? where assigned_user_id=?"; +$adb->pquery($sql8, array($tran_id, $del_id)); + +//updating handler in vtiger_products +$sql9 = "update vtiger_products set handler=? where handler=?"; +$adb->pquery($sql9, array($tran_id, $del_id)); + +//updating inventorymanager in vtiger_quotes +$sql10 = "update vtiger_quotes set inventorymanager=? where inventorymanager=?"; +$adb->pquery($sql10, array($tran_id, $del_id)); + +//updating reports_to_id in vtiger_users +$sql11 = "update vtiger_users set reports_to_id=? where reports_to_id=?"; +$adb->pquery($sql11, array($tran_id, $del_id)); + +//updating user_id in vtiger_moduleowners +$sql12 = "update vtiger_moduleowners set user_id=? where user_id=?"; +$adb->pquery($sql12, array($tran_id, $del_id)); + +//delete from vtiger_users to group vtiger_table +$sql13 = "delete from vtiger_user2role where userid=?"; +$adb->pquery($sql13, array($del_id)); + +//delete from vtiger_users to vtiger_role vtiger_table +$sql14 = "delete from vtiger_users2group where userid=?"; +$adb->pquery($sql14, array($del_id)); + + +//delete from user vtiger_table; +$sql15 = "delete from vtiger_users where id=?"; +$adb->pquery($sql15, array($del_id)); + +//if check to delete user from detail view +if(isset($_REQUEST["ajax_delete"]) && $_REQUEST["ajax_delete"] == 'false') + header("Location: index.php?action=ListView&module=Users"); +else + header("Location: index.php?action=UsersAjax&module=Users&file=ListView&ajax=true"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DetailView.php b/oss/vtiger/trunk/modules/Users/DetailView.php new file mode 100644 index 00000000..75895a4c --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DetailView.php @@ -0,0 +1,234 @@ +retrieve_entity_info($_REQUEST['record'],'Users'); + $focus->id = $_REQUEST['record']; +} +else +{ + + echo " + + "; +} + +if( $focus->user_name == "" ) +{ + + if(is_admin($current_user)) + { + echo " + + + + "; + + echo " + + + +
    + User does not exist. +
    + List Users +
    + "; + exit; + } + +} + + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +//the user might belong to multiple groups +$log->info("User detail view"); + +$category = getParenttab(); + +$smarty = new vtigerCRM_Smarty; + +$smarty->assign("UMOD", $mod_strings); +global $current_language; +$smod_strings = return_module_language($current_language, 'Settings'); +$smarty->assign("MOD", $smod_strings); + +$smarty->assign("APP", $app_strings); + +$oGetUserGroups = new GetUserGroups(); +$oGetUserGroups->getAllUserGroups($focus->id); +if(useInternalMailer() == 1) + $smarty->assign("INT_MAILER","true"); + +$smarty->assign("GROUP_COUNT",count($oGetUserGroups->user_groups)); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", $focus->id); +$smarty->assign("CATEGORY", $category); +if(isset($focus->imagename) && $focus->imagename!='') +{ + $imagestring="
    +
    +
    + + +
    +

    "; + //$smarty->assign("USER_IMAGE",$imagestring); +} + +if(isset($_REQUEST['modechk']) && $_REQUEST['modechk'] != '' ) +{ + $modepref = $_REQUEST['modechk']; +} + if($_REQUEST['modechk'] == 'prefview') + $parenttab = ''; + else + $parenttab = 'Settings'; + +$smarty->assign("PARENTTAB", $parenttab); + +if ((is_admin($current_user) || $_REQUEST['record'] == $current_user->id) + && isset($default_user_name) + && $default_user_name == $focus->user_name + && isset($lock_default_user_name) + && $lock_default_user_name == true ) { + $buttons = ""; + $smarty->assign('EDIT_BUTTON',$buttons); +} +elseif (is_admin($current_user) || $_REQUEST['record'] == $current_user->id) { + $buttons = ""; + $smarty->assign('EDIT_BUTTON',$buttons); + + $buttons = ""; + $smarty->assign('CHANGE_PW_BUTTON',$buttons); + + +} +if (is_admin($current_user)) +{ + $buttons = ""; + $smarty->assign('DUPLICATE_BUTTON',$buttons); + + //done so that only the admin user can see the customize tab button + if($_REQUEST['record'] != $current_user->id) + { + $buttons = "id')\" type='button' name='Delete' value=' ".$app_strings['LBL_DELETE_BUTTON_LABEL']." '>"; + $smarty->assign('DELETE_BUTTON',$buttons); + } + + if($_SESSION['authenticated_user_roleid'] == 'administrator') + { + $buttons = ""; + $smarty->assign('LISTROLES_BUTTON',$buttons); + } + +} + +if(is_admin($current_user)) + $smarty->assign("IS_ADMIN", true); +else + $smarty->assign("IS_ADMIN", false); + +$lead_tables = Array('vtiger_users','vtiger_user2role'); +$tabid = getTabid("Users"); +$validationData = getDBValidationData($lead_tables,$tabid); +$data = split_validationdataArray($validationData); + +if($current_user->id == $_REQUEST['record'] || is_admin($current_user) == true) +{ +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); +$smarty->assign("MODULE", 'Users'); +$smarty->assign("CURRENT_USERID", $current_user->id); +$smarty->assign("HOMEORDER",$focus->getHomeStuffOrder($focus->id)); +//Added to provide User based Tagcloud +$smarty->assign("TAGCLOUDVIEW",getTagCloudView($focus->id)); +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); +$smarty->assign("USERNAME",$focus->last_name.' '.$focus->first_name); +$smarty->assign("HOUR_FORMAT",$focus->hour_format); +$smarty->assign("START_HOUR",$focus->start_hour); + +//for check audittrail if it is enable or not +$smarty->assign("AUDITTRAIL",$audit_trail); + +$smarty->display("UserDetailView.tpl"); +} +else +{ + $output = ' + +
    +
    + + + + + + + + +
    + + + '.$app_strings["LBL_PERMISSION"].' + +
    + '.$app_strings["LBL_GO_BACK"].' +
    +
    +
    +
    '; + echo $output; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/DetailViewAjax.php b/oss/vtiger/trunk/modules/Users/DetailViewAjax.php new file mode 100644 index 00000000..ee83c0ef --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/DetailViewAjax.php @@ -0,0 +1,49 @@ +retrieve_entity_info($crmid,"Users"); + $userObj->column_fields[$fieldname] = $fieldvalue; + if($fieldname == 'internal_mailer'){ + + if(isset($_SESSION['internal_mailer']) && $_SESSION['internal_mailer'] != $userObj->column_fields['internal_mailer']) + $_SESSION['internal_mailer'] = $userObj->column_fields['internal_mailer']; + } + $userObj->id = $crmid; + $userObj->mode = "edit"; + $userObj->save("Users"); + if($userObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/EditView.php b/oss/vtiger/trunk/modules/Users/EditView.php new file mode 100644 index 00000000..ddbc2440 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/EditView.php @@ -0,0 +1,125 @@ +assign("ID",vtlib_purify($_REQUEST['record'])); + $mode='edit'; + if (!is_admin($current_user) && $_REQUEST['record'] != $current_user->id) die ("Unauthorized access to user administration."); + $focus->retrieve_entity_info($_REQUEST['record'],'Users'); + $smarty->assign("USERNAME",$focus->last_name.' '.$focus->first_name); +}else +{ + $mode='create'; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + $focus->user_name = ""; + $mode='create'; + + //When duplicating the user the password fields should be empty + $focus->column_fields['user_password']=''; + $focus->column_fields['confirm_password']=''; +} + +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$log->info("User edit view"); + + +$smarty->assign("JAVASCRIPT", get_validate_record_js()); +$smarty->assign("UMOD", $mod_strings); +global $current_language; +$smod_strings = return_module_language($current_language,'Settings'); +$smarty->assign("MOD", $smod_strings); +$smarty->assign("CURRENT_USERID", $current_user->id); +$smarty->assign("APP", $app_strings); + +if (isset($_REQUEST['error_string'])) $smarty->assign("ERROR_STRING", "Error: ".vtlib_purify($_REQUEST['error_string']).""); +if (isset($_REQUEST['return_module'])) +{ + $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module'])); + $RETURN_MODULE=vtlib_purify($_REQUEST['return_module']); +} +if (isset($_REQUEST['return_action'])) +{ + $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action'])); + $RETURN_ACTION = vtlib_purify($_REQUEST['return_action']); +} +if ($_REQUEST['isDuplicate'] != 'true' && isset($_REQUEST['return_id'])) +{ + $smarty->assign("RETURN_ID", vtlib_purify($_REQUEST['return_id'])); + $RETURN_ID = vtlib_purify($_REQUEST['return_id']); +} +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$focus->mode = $mode; +$disp_view = getView($focus->mode); +$smarty->assign("IMAGENAME",$focus->imagename); +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("MODULE", 'Settings'); +$smarty->assign("MODE",$focus->mode); +$smarty->assign("HOUR_FORMAT",$focus->hour_format); +$smarty->assign("START_HOUR",$focus->start_hour); +if ($_REQUEST['Edit'] == ' Edit ') +{ + $smarty->assign("READONLY", "readonly"); + $smarty->assign("USERNAME_READONLY", "readonly"); + +} +if(isset($_REQUEST['record']) && $_REQUEST['isDuplicate'] != 'true') +{ + $smarty->assign("USERNAME_READONLY", "readonly"); +} + +$smarty->assign("HOMEORDER",$focus->getHomeStuffOrder($focus->id)); +//Added to provide User based Tagcloud +if($mode == 'create') $smarty->assign("TAGCLOUDVIEW","true"); // While creating user select tag cloud by default +else $smarty->assign("TAGCLOUDVIEW",getTagCloudView($focus->id)); + +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); +$smarty->assign("USER_MODE",$mode); +$smarty->assign('PARENTTAB', getParentTab()); + +$smarty->display('UserEditView.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/Error.php b/oss/vtiger/trunk/modules/Users/Error.php new file mode 100644 index 00000000..3efa01ce --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Error.php @@ -0,0 +1,26 @@ + +

    + +

    + +
    + diff --git a/oss/vtiger/trunk/modules/Users/Forms.php b/oss/vtiger/trunk/modules/Users/Forms.php new file mode 100644 index 00000000..b1a38042 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Forms.php @@ -0,0 +1,216 @@ +query($sql); + + $count = $adb->num_rows($result); + + if($count > 0){ + return "true"; + }else{ + return "false"; + } +} + +/** + * this function gets the asterisk extensions assigned in vtiger + */ +function getAsteriskExtensions(){ + global $adb, $current_user; + + $sql = "select * from vtiger_asteriskextensions where userid != ".$current_user->id; + $result = $adb->pquery($sql, array()); + $count = $adb->num_rows($result); + $data = array(); + + for($i=0;$i<$count;$i++){ + $user = $adb->query_result($result, $i, "userid"); + $extension = $adb->query_result($result, $i, "asterisk_extension"); + if(!empty($extension)){ + $data[$user] = $extension; + } + } + return $data; +} + +/** + * Create javascript to validate the data entered into a record. + * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. + * All Rights Reserved. + * Contributor(s): ______________________________________.. + */ +function get_validate_record_js () { +global $mod_strings; +global $app_strings; + +$lbl_last_name = $mod_strings['LBL_LIST_LAST_NAME']; +$lbl_user_name = $mod_strings['LBL_LIST_USER_NAME']; +$lbl_role_name = $mod_strings['LBL_ROLE_NAME']; +$lbl_new_password = $mod_strings['LBL_LIST_PASSWORD']; +$lbl_confirm_new_password = $mod_strings['LBL_LIST_CONFIRM_PASSWORD']; +$lbl_user_email1 = $mod_strings['LBL_LIST_EMAIL']; +$err_missing_required_fields = $app_strings['ERR_MISSING_REQUIRED_FIELDS']; +$err_invalid_email_address = $app_strings['ERR_INVALID_EMAIL_ADDRESS']; +$err_invalid_yahoo_email_address = $app_strings['ERR_INVALID_YAHOO_EMAIL_ADDRESS']; +$lbl_user_image=$mod_strings['User Image']; +$the_emailid = $app_strings['THE_EMAILID']; +$email_field_is = $app_strings['EMAIL_FILED_IS'].$err_invalid_email_address; +$other_email_field_is = $app_strings['OTHER_EMAIL_FILED_IS'].$err_invalid_email_address; +$yahoo_email_field_is = $app_strings['YAHOO_EMAIL_FILED_IS'].$err_invalid_yahoo_email_address; +$lbl_asterisk_details_not_set = $app_strings['LBL_ASTERISK_SET_ERROR']; + +//check asteriskdetails start +$checkAsteriskDetails = checkAsteriskDetails(); +$extensions_list = implode(",",getAsteriskExtensions()); +//check asteriskdetails end + +$the_script = << + + + +EOQ; + +return $the_script; +} + +?> diff --git a/oss/vtiger/trunk/modules/Users/GroupDeleteStep1.php b/oss/vtiger/trunk/modules/Users/GroupDeleteStep1.php new file mode 100644 index 00000000..1c4b034e --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/GroupDeleteStep1.php @@ -0,0 +1,119 @@ + +
    + + + + + + + + +
    '.$mod_strings['LBL_DELETE_GROUP'].''.$app_strings[
    + + + + +
    + + + + + + + + + +
    '.$mod_strings['LBL_DELETE_GROUPNAME'].''.htmlentities($delete_group_name,ENT_QUOTES,$default_charset).'
    '.$mod_strings['LBL_TRANSFER_GROUP'].''; + global $adb; + $sql = "select groupid,groupname from vtiger_groups"; + $result = $adb->pquery($sql, array()); + $num_groups = $adb->num_rows($result); + + $sql1 = "select id,user_name from vtiger_users where deleted=0"; + $result1= $adb->pquery($sql1, array()); + $num_users = $adb->num_rows($result1); + + + $output.= ' User'; + if($num_groups > 1) + { + $output .= ' Group'; + } + + $output .= ''; + + $output .= ''; + + if($num_groups > 1) + { + $output .= ''; + } + + $output.='
    +
    + + + + +
    +
    +
    '; + +echo $output; +?> diff --git a/oss/vtiger/trunk/modules/Users/ListView.php b/oss/vtiger/trunk/modules/Users/ListView.php new file mode 100644 index 00000000..caf237c4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/ListView.php @@ -0,0 +1,103 @@ +is_admin != 'on') +{ + die("

    ".$app_strings['LBL_PERMISSION']." ".$app_strings['LBL_GO_BACK'].".
    "); +} + +$log = LoggerManager::getLogger('user_list'); + +global $mod_strings,$adb; +global $theme; +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +global $current_language; +$mod_strings = return_module_language($current_language,'Users'); +$category = getParentTab(); +$focus = new Users(); +$no_of_users=UserCount(); + +//Display the mail send status +$smarty = new vtigerCRM_Smarty; +if($_REQUEST['mail_error'] != '') +{ + require_once("modules/Emails/mail.php"); + $error_msg = strip_tags(parseEmailErrorString($_REQUEST['mail_error'])); + $error_msg = $app_strings['LBL_MAIL_NOT_SENT_TO_USER']. ' ' . vtlib_purify($_REQUEST['user']). '. ' .$app_strings['LBL_PLS_CHECK_EMAIL_N_SERVER']; + $smarty->assign("ERROR_MSG",$mod_strings['LBL_MAIL_SEND_STATUS'].' '.$error_msg.''); +} + +//Retreiving the start value from request +if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); +} elseif($_SESSION['user_pagestart'] != '') { + $start = $_SESSION['user_pagestart']; +} else + $start=1; + +$list_query = getListQuery("Users"); + + $userid = array(); + $userid_Query = "SELECT id,user_name FROM vtiger_users WHERE user_name IN ('admin')"; + $users = $adb->pquery($userid_Query,array()); + $norows = $adb->num_rows($users); + if($norows > 0){ + for($i=0;$i<$norows ;$i++){ + $id = $adb->query_result($users,$i,'id'); + $userid[$id] = $adb->query_result($users,$i,'user_name'); + } + } + $smarty->assign("USERNODELETE",$userid); +$_SESSION['user_pagestart'] = $start; +if($_REQUEST['sorder'] !='') + $sorder = $adb->sql_escape_string($_REQUEST['sorder']); +elseif($_SESSION['user_sorder'] != '') + $sorder = $adb->sql_escape_string($_SESSION['user_sorder']); +else + $sorder = 'ASC'; +$_SESSION['user_sorder'] = $sorder; +if($_REQUEST['order_by'] != '') + $order_by = $adb->sql_escape_string($_REQUEST['order_by']); +elseif($_SESSION['user_orderby'] != '') + $order_by = $adb->sql_escape_string($_SESSION['user_orderby']); +else + $order_by = 'last_name'; +$_SESSION['user_orderby'] = $orderby; +$list_query .= ' ORDER BY '.$order_by.' '.$sorder; +$list_result = $adb->query($list_query); +//Retreive the Navigation array +$navigation_array = getNavigationValues($start, $adb->num_rows($list_result), $no_of_users['user']); + +$navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Administration","index",''); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("CURRENT_USERID", $current_user->id); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("CATEGORY",$category); +$smarty->assign("LIST_HEADER",getListViewHeader($focus,"Users",$url_string,$sorder,$order_by,"","")); +$smarty->assign("LIST_ENTRIES",getListViewEntries($focus,"Users",$list_result,$navigation_array,"","","EditView","Delete","")); +$smarty->assign("USER_COUNT",$no_of_users); +$smarty->assign("RECORD_COUNTS", $record_string); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("USER_IMAGES",getUserImageNames()); +if($_REQUEST['ajax'] !='') + $smarty->display("UserListViewContents.tpl"); +else + $smarty->display("UserListView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/Login.php b/oss/vtiger/trunk/modules/Users/Login.php new file mode 100644 index 00000000..9e16ce35 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Login.php @@ -0,0 +1,198 @@ + + + + + + +

    +
    + + + + +
    + + + + + + + + + + + +
    vtiger CRMThe honest Open Source CRM
    + + + + + +
    +
    + + + + + + + + + + + +
    <?php echo $app_strings['LBL_SIGN_IN']?>
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
     
    +

    +
    +
    +
    +
    diff --git a/oss/vtiger/trunk/modules/Users/LoginHistory.php b/oss/vtiger/trunk/modules/Users/LoginHistory.php new file mode 100644 index 00000000..e2a9b697 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/LoginHistory.php @@ -0,0 +1,211 @@ +log = LoggerManager::getLogger('loginhistory'); + $this->db = PearDatabase::getInstance(); + } + + var $sortby_fields = Array('user_name', 'user_ip', 'login_time', 'logout_time', 'status'); + + // This is the list of vtiger_fields that are in the lists. + var $list_fields = Array( + 'User Name'=>Array('vtiger_loginhistory'=>'user_name'), + 'User IP'=>Array('vtiger_loginhistory'=>'user_ip'), + 'Signin Time'=>Array('vtiger_loginhistory'=>'login_time'), + 'Signout Time'=>Array('vtiger_loginhistory'=>'logout_time'), + 'Status'=>Array('vtiger_loginhistory'=>'status'), + ); + + var $list_fields_name = Array( + 'User Name'=>'user_name', + 'User IP'=>'user_ip', + 'Signin Time'=>'login_time', + 'Signout Time'=>'logout_time', + 'Status'=>'status' + ); + var $default_order_by = "login_time"; + var $default_sort_order = 'DESC'; + +/** + * Function to get the Header values of Login History. + * Returns Header Values like UserName, IP, LoginTime etc in an array format. +**/ + function getHistoryListViewHeader() + { + global $log; + $log->debug("Entering getHistoryListViewHeader method ..."); + global $app_strings; + + $header_array = array($app_strings['LBL_LIST_USER_NAME'], $app_strings['LBL_LIST_USERIP'], $app_strings['LBL_LIST_SIGNIN'], $app_strings['LBL_LIST_SIGNOUT'], $app_strings['LBL_LIST_STATUS']); + + $log->debug("Exiting getHistoryListViewHeader method ..."); + return $header_array; + + } + +/** + * Function to get the Login History values of the User. + * @param $navigation_array - Array values to navigate through the number of entries. + * @param $sortorder - DESC + * @param $orderby - login_time + * Returns the login history entries in an array format. +**/ + function getHistoryListViewEntries($username, $navigation_array, $sorder='', $orderby='') + { + global $log; + $log->debug("Entering getHistoryListViewEntries() method ..."); + global $adb, $current_user; + + if($sorder != '' && $order_by != '') + $list_query = "Select * from vtiger_loginhistory where user_name=? order by ".$order_by." ".$sorder; + else + $list_query = "Select * from vtiger_loginhistory where user_name=? order by ".$this->default_order_by." ".$this->default_sort_order; + + $result = $adb->pquery($list_query, array($username)); + $entries_list = array(); + + if($navigation_array['end_val'] != 0) + { + for($i = $navigation_array['start']; $i <= $navigation_array['end_val']; $i++) + { + $entries = array(); + $loginid = $adb->query_result($result, $i-1, 'login_id'); + + $entries[] = $adb->query_result($result, $i-1, 'user_name'); + $entries[] = $adb->query_result($result, $i-1, 'user_ip'); + $entries[] = $adb->query_result($result, $i-1, 'login_time'); + $entries[] = $adb->query_result($result, $i-1, 'logout_time'); + $entries[] = $adb->query_result($result, $i-1, 'status'); + + $entries_list[] = $entries; + } + $log->debug("Exiting getHistoryListViewEntries() method ..."); + return $entries_list; + } + } + + /** Function that Records the Login info of the User + * @param ref variable $usname :: Type varchar + * @param ref variable $usip :: Type varchar + * @param ref variable $intime :: Type timestamp + * Returns the query result which contains the details of User Login Info + */ + function user_login(&$usname,&$usip,&$intime) + { + global $adb; + //Kiran: Setting logout time to '0000-00-00 00:00:00' instead of null + $query = "Insert into vtiger_loginhistory (user_name, user_ip, logout_time, login_time, status) values (?,?,?,?,?)"; + $params = array($usname,$usip,'0000-00-00 00:00:00', $this->db->formatDate($intime, true),'Signed in'); + $result = $adb->pquery($query, $params) + or die("MySQL error: ".mysql_error()); + + return $result; + } + + /** Function that Records the Logout info of the User + * @param ref variable $usname :: Type varchar + * @param ref variable $usip :: Type varchar + * @param ref variable $outime :: Type timestamp + * Returns the query result which contains the details of User Logout Info + */ + function user_logout(&$usname,&$usip,&$outtime) + { + global $adb; + $logid_qry = "SELECT max(login_id) AS login_id from vtiger_loginhistory where user_name=? and user_ip=?"; + $result = $adb->pquery($logid_qry, array($usname, $usip)); + $loginid = $adb->query_result($result,0,"login_id"); + if ($loginid == '') + { + return; + } + // update the user login info. + $query = "Update vtiger_loginhistory set logout_time =?, status=? where login_id = ?"; + $result = $adb->pquery($query, array($this->db->formatDate($outtime, true), 'Signed off', $loginid)) + or die("MySQL error: ".mysql_error()); + } + + /** Function to create list query + * @param reference variable - order by is passed when the query is executed + * @param reference variable - where condition is passed when the query is executed + * Returns Query. + */ + function create_list_query(&$order_by, &$where) + { + // Determine if the vtiger_account name is present in the where clause. + global $current_user, $adb; + $query = "SELECT user_name,user_ip, status, + ".$this->db->getDBDateString("login_time")." AS login_time, + ".$this->db->getDBDateString("logout_time")." AS logout_time + FROM ".$this->table_name; + if($where != "") + { + if(!is_admin($current_user)) + $where .=" AND user_name = '". $adb->sql_escape_string($current_user->user_name) ."'"; + $query .= " WHERE ($where)"; + } + else + { + if(!is_admin($current_user)) + $query .= " WHERE user_name = '". $adb->sql_escape_string($current_user->user_name) ."'"; + } + + if(!empty($order_by)) + $query .= " ORDER BY ". $adb->sql_escape_string($order_by); + + return $query; + } + +} + + + +?> diff --git a/oss/vtiger/trunk/modules/Users/Logout.php b/oss/vtiger/trunk/modules/Users/Logout.php new file mode 100644 index 00000000..2541b030 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Logout.php @@ -0,0 +1,129 @@ +pquery($query, array('ftp_backup')); + $num_rows = $adb->num_rows($result); + if($num_rows > 0) + { + $ftpserver = $adb->query_result($result,0,'server'); + $ftpuser = $adb->query_result($result,0,'server_username'); + $ftppassword = $adb->query_result($result,0,'server_password'); + } + + //Taking the Backup of DB + $currenttime=date("Ymd_His"); + if($ftpserver != '' && $ftpuser != '' && $ftppassword != '') + { + $createZip = new createDirZip; + $fileName = '/backup_'.$currenttime.'.zip'; + + $createZip->addDirectory('user_privileges/'); + $createZip->get_files_from_folder('user_privileges/', 'user_privileges/'); + + $createZip->addDirectory('storage/'); + $createZip->get_files_from_folder('storage/', 'storage/'); + + $backup_DBFileName = "sqlbackup_".$currenttime.".sql"; + $dbdump = new DatabaseDump(dbserver, dbuser, dbpass); + $dumpfile = 'backup/'.$backup_DBFileName; + $dbdump->save(dbname, $dumpfile) ; + + $filedata = implode("", file('backup/'.$backup_DBFileName)); + $createZip->addFile($filedata,$backup_DBFileName); + + $fd = fopen ($fileName, 'wb'); + $out = fwrite ($fd, $createZip->getZippedfile()); + fclose ($fd); + + $source_file=$fileName; + ftpBackupFile($source_file, $ftpserver, $ftpuser, $ftppassword); + if(file_exists($source_file)) unlink($source_file); + + } +} +if($enable_local_backup == 'true' && is_admin($current_user) == true) +{ + define("dbserver", $dbconfig['db_hostname']); + define("dbuser", $dbconfig['db_username']); + define("dbpass", $dbconfig['db_password']); + define("dbname", $dbconfig['db_name']); + + $path_query = $adb->pquery("SELECT * FROM vtiger_systems WHERE server_type = ?",array('local_backup')); + $path = $adb->query_result($path_query,0,'server_path'); + $currenttime=date("Ymd_His"); + + if(is_dir($path) && is_writable($path)) + { + $createZip = new createDirZip; + $fileName = $path.'/backup_'.$currenttime.'.zip'; + + $createZip->addDirectory('user_privileges/'); + $createZip->get_files_from_folder('user_privileges/', 'user_privileges/'); + + $createZip->addDirectory('storage/'); + $createZip->get_files_from_folder('storage/', 'storage/'); + + $backup_DBFileName = "sqlbackup_".$currenttime.".sql"; + $dbdump = new DatabaseDump(dbserver, dbuser, dbpass); + $dumpfile = 'backup/'.$backup_DBFileName; + $dbdump->save(dbname, $dumpfile) ; + + $filedata = implode("", file('backup/'.$backup_DBFileName)); + $createZip->addFile($filedata,$backup_DBFileName); + + $fd = fopen ($fileName, 'wb'); + $out = fwrite ($fd, $createZip->getZippedfile()); + fclose ($fd); + } +} +// Recording Logout Info + $usip=$_SERVER['REMOTE_ADDR']; + $outtime=date("Y/m/d H:i:s"); + $loghistory=new LoginHistory(); + $loghistory->user_logout($current_user->user_name,$usip,$outtime); + + +$local_log =& LoggerManager::getLogger('Logout'); + +// clear out the autthenticating flag +session_destroy(); + +define("IN_LOGIN", true); + +// go to the login screen. +header("Location: index.php?action=Login&module=Users"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/OrgSharingEditView.php b/oss/vtiger/trunk/modules/Users/OrgSharingEditView.php new file mode 100644 index 00000000..cbf1765b --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/OrgSharingEditView.php @@ -0,0 +1,73 @@ + $def_perr) +{ + $entity_name = getTabname($tab_id); + if($tab_id == 6) + { + $cont_name = getTabname(4); + $entity_name .= ' & '.$cont_name; + } + $defActionArr=getModuleSharingActionArray($tab_id); + + $entries[] = $entity_name; + + if($tab_id != 6) + { + $output = ''; + } + $entries[] = $tab_id; + + foreach($defActionArr as $shareActId=>$shareActName) + { + $selected=''; + if($shareActId == $def_perr) + { + $selected='selected'; + } + $output .= ''; + + } + + + $output .= ''; + $entries[] = $output; + $row++; +} + +$list_entries=array_chunk($entries,3); +$smarty->assign("ORGINFO",$list_entries); +$smarty->assign("MOD", return_module_language($current_language,'Settings')); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); + +$smarty->display("OrgSharingEditView.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Users/Popup.php b/oss/vtiger/trunk/modules/Users/Popup.php new file mode 100644 index 00000000..88877b45 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Popup.php @@ -0,0 +1,20 @@ + diff --git a/oss/vtiger/trunk/modules/Users/ProfileDeleteStep1.php b/oss/vtiger/trunk/modules/Users/ProfileDeleteStep1.php new file mode 100644 index 00000000..d9d717cb --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/ProfileDeleteStep1.php @@ -0,0 +1,75 @@ + +
    + + + + + + + + +
    '.$mod_strings["LBL_DELETE_PROFILE"].''.$app_strings[
    + + + + +
    + + + + + + + + + +
    '.$mod_strings["LBL_PROFILE_TO_BE_DELETED"].''.htmlentities($delete_prof_name,ENT_QUOTES,$default_charset).'
    '.$mod_strings["LBL_TRANSFER_ROLES_TO_PROFILE"].''; + $output.=''; + + $output.='
    +
    + + + + +
    + +
    +
    '; + +echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/RecalculateSharingRules.php b/oss/vtiger/trunk/modules/Users/RecalculateSharingRules.php new file mode 100644 index 00000000..bbf2ea7e --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/RecalculateSharingRules.php @@ -0,0 +1,18 @@ + diff --git a/oss/vtiger/trunk/modules/Users/RenameProfile.php b/oss/vtiger/trunk/modules/Users/RenameProfile.php new file mode 100644 index 00000000..3f18c6f1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/RenameProfile.php @@ -0,0 +1,25 @@ +pquery($query, array($profilename, $profileDesc, $profileid)); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/RoleDragDrop.php b/oss/vtiger/trunk/modules/Users/RoleDragDrop.php new file mode 100644 index 00000000..ec6f96d9 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/RoleDragDrop.php @@ -0,0 +1,64 @@ +pquery($query, array($toid)); +$parentRoleList=$adb->query_result($result,0,'parentrole'); +$replace_with=$parentRoleList; +$orgDepth=$adb->query_result($result,0,'depth'); + +//echo 'replace with is '.$replace_with; +//echo '
    org depth '.$orgDepth; +$parentRoles=explode('::',$parentRoleList); + +if(in_array($fromid,$parentRoles)) +{ + echo $mod_strings['ROLE_DRAG_ERR_MSG']; + die; +} + + +$roleInfo=getRoleAndSubordinatesInformation($fromid); + +$fromRoleInfo=$roleInfo[$fromid]; +$replaceToStringArr=explode('::'.$fromid,$fromRoleInfo[1]); +$replaceToString=$replaceToStringArr[0]; +//echo '
    to be replaced string '.$replaceToString; + + +$stdDepth=$fromRoleInfo['2']; +//echo '
    std depth '.$stdDepth; + +//Constructing the query +foreach($roleInfo as $mvRoleId=>$mvRoleInfo) +{ + $subPar=explode($replaceToString,$mvRoleInfo[1],2);//we have to spilit as two elements only + $mvParString=$replace_with.$subPar[1]; + $subDepth=$mvRoleInfo[2]; + $mvDepth=$orgDepth+(($subDepth-$stdDepth)+1); + $query="update vtiger_role set parentrole=?,depth=? where roleid=?"; + //echo $query; + $adb->pquery($query, array($mvParString, $mvDepth, $mvRoleId)); + + // Invalidate any cached information + VTCacheUtils::clearRoleSubordinates($roleId); +} + + + +header("Location: index.php?action=SettingsAjax&module=Settings&file=listroles&ajax=true"); +?> diff --git a/oss/vtiger/trunk/modules/Users/RolePopup.php b/oss/vtiger/trunk/modules/Users/RolePopup.php new file mode 100644 index 00000000..3ccb432f --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/RolePopup.php @@ -0,0 +1,160 @@ +pquery($hquery, array()); +$num_rows = $adb->num_rows($hr_res); +$hrarray= Array(); + +for($l=0; $l<$num_rows; $l++) +{ + $roleid = $adb->query_result($hr_res,$l,'roleid'); + $parent = $adb->query_result($hr_res,$l,'parentrole'); + $temp_list = explode('::',$parent); + $size = sizeof($temp_list); + $i=0; + $k= Array(); + $y=$hrarray; + if(sizeof($hrarray) == 0) + { + $hrarray[$temp_list[0]]= Array(); + } + else + { + while($i<$size-1) + { + $y=$y[$temp_list[$i]]; + $k[$temp_list[$i]] = $y; + $i++; + + } + $y[$roleid] = Array(); + $k[$roleid] = Array(); + + //Reversing the Array + $rev_temp_list=array_reverse($temp_list); + $j=0; + //Now adding this into the main array + foreach($rev_temp_list as $value) + { + if($j == $size-1) + { + $hrarray[$value]=$k[$value]; + } + else + { + $k[$rev_temp_list[$j+1]][$value]=$k[$value]; + } + $j++; + } + } + +} +//Constructing the Roledetails array +$role_det = getAllRoleDetails(); +$query = "select * from vtiger_role"; +$result = $adb->pquery($query, array()); +$num_rows=$adb->num_rows($result); +$mask_roleid=Array(); +$del_roleid=$_REQUEST['maskid']; +if($del_roleid != '' && strlen($del_roleid) >0) +{ + $mask_roleid= getRoleAndSubordinatesRoleIds($del_roleid); +} +$roleout =''; +$roleout .= indent($hrarray,$roleout,$role_det,$mask_roleid); + +/** recursive function to construct the role tree ui + * @param $hrarray -- Hierarchial role tree array with only the roleid:: Type array + * @param $roleout -- html string ouput of the constucted role tree ui:: Type varchar + * @param $role_det -- Roledetails array got from calling getAllRoleDetails():: Type array + * @param $mask_roleid -- role id to be masked from selecting in the tree:: Type integer + * @returns $role_out -- html string ouput of the constucted role tree ui:: Type string + * + */ +function indent($hrarray,$roleout,$role_det,$mask_roleid='') +{ + global $theme,$app_strings,$default_charset; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + foreach($hrarray as $roleid => $value) + { + + //retreiving the vtiger_role details + $role_det_arr=$role_det[$roleid]; + $roleid_arr=$role_det_arr[2]; + $rolename = htmlentities($role_det_arr[0],ENT_QUOTES,$default_charset); + $roledepth = $role_det_arr[1]; + $roleout .= '
      '; + $roleout .= '
    • '; + if(sizeof($value) >0 && $roledepth != 0) + { + $roleout .= ''.$app_strings['LBL_EXPAND_COLLAPSE'].''; + } + else if($roledepth != 0){ + $roleout .= ''.$app_strings['LBL_EXPAND_COLLAPSE'].''; + } + else + { + $roleout .= ''.$app_strings['LBL_ROOT'].''; + } + if($roledepth == 0 || in_array($roleid,$mask_roleid)) + { + $roleout .= ' '.$rolename.''; + } + else + { + $type =$_REQUEST['type']; + if($type == '') + { + $roleout .= ' '.$rolename.''; + } + else + { + $picklist_module = vtlib_purify($_REQUEST['picklistmodule']); + $picklist_fieldname = vtlib_purify($_REQUEST['pick_fieldname']); + $picklist_uitype = vtlib_purify($_REQUEST['pick_uitype']); + + $roleout .= ' '.$rolename.''; + } + } + $roleout .= '
    • '; + if(sizeof($value) > 0 ) + { + $roleout = indent($value,$roleout,$role_det,$mask_roleid); + } + + $roleout .= '
    '; + + } + + return $roleout; +} +$smarty->assign("THEME",$theme_path); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("APP", $app_strings); +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("ROLETREE", $roleout); +$smarty->display("RolePopup.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/Save.php b/oss/vtiger/trunk/modules/Users/Save.php new file mode 100644 index 00000000..fec64d23 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Save.php @@ -0,0 +1,221 @@ +pquery($user_query, array($user_name)); + $group_query = "SELECT groupname FROM vtiger_groups WHERE groupname =?"; + $group_result = $adb->pquery($group_query, array($user_name)); + + if($adb->num_rows($user_result) > 0) { + echo $mod_strings['LBL_USERNAME_EXIST']; + die; + } elseif($adb->num_rows($group_result) > 0) { + echo $mod_strings['LBL_GROUPNAME_EXIST']; + die; + } else { + echo 'SUCCESS'; + die; + } +} + +if (isset($_POST['record']) && !is_admin($current_user) && $_POST['record'] != $current_user->id) echo ("Unauthorized access to user administration."); +elseif (!isset($_POST['record']) && !is_admin($current_user)) echo ("Unauthorized access to user administration."); + +$focus = new Users(); +if(isset($_REQUEST["record"]) && $_REQUEST["record"] != '') +{ + $focus->mode='edit'; + $focus->id = $_REQUEST["record"]; +} +else +{ + $focus->mode=''; +} + + +if($_REQUEST['changepassword'] == 'true') +{ + $focus->retrieve_entity_info($_REQUEST['record'],'Users'); + $focus->id = $_REQUEST['record']; +if (isset($_POST['new_password'])) { + $new_pass = $_POST['new_password']; + $new_passwd = $_POST['new_password']; + $new_pass = md5($new_pass); + $old_pass = $_POST['old_password']; + $uname = $_POST['user_name']; + if (!$focus->change_password($_POST['old_password'], $_POST['new_password'])) { + + header("Location: index.php?action=Error&module=Users&error_string=".urlencode($focus->error_string)); + exit; +} +} + +} + + +//save user Image +if(! $_REQUEST['changepassword'] == 'true') +{ + if(strtolower($current_user->is_admin) == 'off' && $current_user->id != $focus->id) + { + $log->fatal("SECURITY:Non-Admin ". $current_user->id . " attempted to change settings for user:". $focus->id); + header("Location: index.php?module=Users&action=Logout"); + exit; + } + if(strtolower($current_user->is_admin) == 'off' && isset($_POST['is_admin']) && strtolower($_POST['is_admin']) == 'on') + { + $log->fatal("SECURITY:Non-Admin ". $current_user->id . " attempted to change is_admin settings for user:". $focus->id); + header("Location: index.php?module=Users&action=Logout"); + exit; + } + + if (!isset($_POST['is_admin'])) $_REQUEST["is_admin"] = 'off'; + //Code contributed by mike crowe for rearrange the home page and tab + if (!isset($_POST['deleted'])) $_REQUEST["deleted"] = '0'; + if (!isset($_POST['homeorder']) || $_POST['homeorder'] == "" ) $_REQUEST["homeorder"] = 'ILTI,QLTQ,ALVT,PLVT,CVLVT,HLT,OLV,GRT,OLTSO'; + if(isset($_REQUEST['internal_mailer']) && $_REQUEST['internal_mailer'] == 'on') + $focus->column_fields['internal_mailer'] = 1; + else + $focus->column_fields['internal_mailer'] = 0; + if(isset($_SESSION['internal_mailer']) && $_SESSION['internal_mailer'] != $focus->column_fields['internal_mailer']) + $_SESSION['internal_mailer'] = $focus->column_fields['internal_mailer']; + setObjectValuesFromRequest($focus); + + // Added for Reminder Popup support + $query_prev_interval = $adb->pquery("SELECT reminder_interval from vtiger_users where id=?",array($focus->id)); + $prev_reminder_interval = $adb->query_result($query_prev_interval,0,'reminder_interval'); + + $focus->saveentity("Users"); + //$focus->imagename = $image_upload_array['imagename']; + $focus->saveHomeStuffOrder($focus->id); + SaveTagCloudView($focus->id); + + // Added for Reminder Popup support + $focus->resetReminderInterval($prev_reminder_interval); + + $return_id = $focus->id; + +if (isset($_POST['user_name']) && isset($_POST['new_password'])) { + $new_pass = $_POST['new_password']; + $new_passwd = $_POST['new_password']; + $new_pass = md5($new_pass); + $uname = $_POST['user_name']; + if (!$focus->change_password($_POST['confirm_new_password'], $_POST['new_password'])) { + + header("Location: index.php?action=Error&module=Users&error_string=".urlencode($focus->error_string)); + exit; +} +} + +if(isset($focus->id) && $focus->id != '') +{ + + if(isset($_POST['user_role'])) + { + updateUser2RoleMapping($_POST['user_role'],$focus->id); + } + if(isset($_POST['group_name']) && $_POST['group_name'] != '') + { + updateUsers2GroupMapping($_POST['group_name'],$focus->id); + } +} +else +{ + if(isset($_POST['user_role'])) + { + insertUser2RoleMapping($_POST['user_role'],$focus->id); + } + if(isset($_POST['group_name'])) + { + insertUsers2GroupMapping($_POST['group_name'],$focus->id); + } +} + +//Creating the Privileges Flat File +require_once('modules/Users/CreateUserPrivilegeFile.php'); +createUserPrivilegesfile($focus->id); +createUserSharingPrivilegesfile($focus->id); + +} +if(isset($_POST['return_module']) && $_POST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Users"; +if(isset($_POST['return_action']) && $_POST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_POST['return_id']) && $_POST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); +if(isset($_REQUEST['activity_mode'])) $activitymode = '&activity_mode='.vtlib_purify($_REQUEST['activity_mode']); +if(isset($_POST['parenttab'])) $parenttab = getParentTab(); + +$log->debug("Saved record with id of ".$return_id); + +//Asha: Added Check to see if the mode is User Creation and if yes, then sending the email notification to the User with Login details. +if($_REQUEST['mode'] == 'create') { + global $app_strings, $mod_strings, $default_charset; + require_once('modules/Emails/mail.php'); + $user_emailid = $focus->column_fields['email1']; + + $subject = $mod_strings['User Login Details']; + $email_body = $app_strings['MSG_DEAR']." ". $focus->column_fields['last_name'] .",

    "; + $email_body .= $app_strings['LBL_PLEASE_CLICK'] . " " + . $app_strings['LBL_HERE'] . " " . $mod_strings['LBL_TO_LOGIN'] . "

    "; + $email_body .= $mod_strings['LBL_USER_NAME'] . " : " . $focus->column_fields['user_name'] . "
    "; + $email_body .= $mod_strings['LBL_PASSWORD'] . " : " . $focus->column_fields['user_password'] . "
    "; + $email_body .= $mod_strings['LBL_ROLE_NAME'] . " : " . getRoleName($_POST['user_role']) . "
    "; + + $email_body .= "
    " . $app_strings['MSG_THANKS'] . "
    " . $current_user->user_name; + $email_body = htmlentities($email_body, ENT_QUOTES, $default_charset); + + $mail_status = send_mail('Users',$user_emailid,$HELPDESK_SUPPORT_NAME,$HELPDESK_SUPPORT_EMAIL_ID,$subject,$email_body); + + if($mail_status != 1) { + $mail_status_str = $user_emailid."=".$mail_status."&&&"; + $error_str = getMailErrorString($mail_status_str); + } +} +$location = "Location: index.php?action=".vtlib_purify($return_action)."&module=".vtlib_purify($return_module)."&record=".vtlib_purify($return_id); + +if($_REQUEST['modechk'] != 'prefview') { + $location .= "&parenttab=".vtlib_purify($parenttab); +} + +if ($error_str != '') { + $user = $focus->column_fields['user_name']; + $location .= "&user=$user&$error_str"; +} + +header($location); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/SaveDefModuleView.php b/oss/vtiger/trunk/modules/Users/SaveDefModuleView.php new file mode 100644 index 00000000..877f48fc --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/SaveDefModuleView.php @@ -0,0 +1,45 @@ + + diff --git a/oss/vtiger/trunk/modules/Users/SaveGroup.php b/oss/vtiger/trunk/modules/Users/SaveGroup.php new file mode 100644 index 00000000..48cc3435 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/SaveGroup.php @@ -0,0 +1,126 @@ +pquery($query, $params); + + $user_query = "SELECT user_name FROM vtiger_users WHERE user_name =?"; + $user_result = $adb->pquery($user_query, array($groupName)); + + if($adb->num_rows($result) > 0) { + echo $mod_strings['LBL_GROUPNAME_EXIST']; + die; + } elseif($adb->num_rows($user_result) > 0) { + echo $mod_strings['LBL_USERNAME_EXIST']; + die; + } else { + echo 'SUCCESS'; + die; + } +} + + +/** returns the group members in an formatted array + * @param $member_array -- member_array:: Type varchar + * @returns $groupMemberArray:: Type varchar + + $groupMemberArray['groups'] -- gives the array of sub groups members ; + $groupMemberArray['roles'] -- gives the array of roles present in the group ; + $groupMemberArray['rs'] -- gives the array of roles & subordinates present in the group ; + $groupMemberArray['users'] -- gives the array of roles & subordinates present in the group; + * + */ +function constructGroupMemberArray($member_array) +{ + global $adb; + + $groupMemberArray=Array(); + $roleArray=Array(); + $roleSubordinateArray=Array(); + $groupArray=Array(); + $userArray=Array(); + + foreach($member_array as $member) + { + $memSubArray=explode('::',$member); + if($memSubArray[0] == 'groups') + { + $groupArray[]=$memSubArray[1]; + } + if($memSubArray[0] == 'roles') + { + $roleArray[]=$memSubArray[1]; + } + if($memSubArray[0] == 'rs') + { + $roleSubordinateArray[]=$memSubArray[1]; + } + if($memSubArray[0] == 'users') + { + $userArray[]=$memSubArray[1]; + } + } + + $groupMemberArray['groups']=$groupArray; + $groupMemberArray['roles']=$roleArray; + $groupMemberArray['rs']=$roleSubordinateArray; + $groupMemberArray['users']=$userArray; + + return $groupMemberArray; + +} + + if(isset($_REQUEST['returnaction']) && $_REQUEST['returnaction'] != '') + { + $returnaction=$_REQUEST['returnaction'].'&roleid='.$_REQUEST['roleid']; + } + else + { + $returnaction='GroupDetailView'; + } + + //Inserting values into Role Table + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'edit') + { + $groupId = $_REQUEST['groupId']; + $selected_col_string = $_REQUEST['selectedColumnsString']; + $member_array = explode(';',$selected_col_string); + $groupMemberArray=constructGroupMemberArray($member_array); + updateGroup($groupId,$groupName,$groupMemberArray,$description); + + $loc = "Location: index.php?action=".vtlib_purify($returnaction)."&module=Settings&parenttab=Settings&groupId=".vtlib_purify($groupId); + } + elseif(isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'create') + { + $selected_col_string = $_REQUEST['selectedColumnsString']; + $member_array = explode(';',$selected_col_string); + $groupMemberArray=constructGroupMemberArray($member_array); + $groupId=createGroup($groupName,$groupMemberArray,$description); + $loc = "Location: index.php?action=".vtlib_purify($returnaction)."&parenttab=Settings&module=Settings&groupId=".vtlib_purify($groupId); + + } + + header($loc); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/SaveMailAccount.php b/oss/vtiger/trunk/modules/Users/SaveMailAccount.php new file mode 100644 index 00000000..1dd4cf70 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/SaveMailAccount.php @@ -0,0 +1,58 @@ +id; +$email=$_REQUEST['email']; +$account_name=$_REQUEST['account_name']; +$mailprotocol=$_REQUEST['mailprotocol']; +$server_username = $_REQUEST['server_username']; +$server_password = $_REQUEST['server_password']; +$mail_servername = $_REQUEST['mail_servername']; +$box_refresh = $_REQUEST['box_refresh']; +$mails_per_page = $_REQUEST['mails_per_page']; +$ssltype = $_REQUEST["ssltype"]; +$sslmeth = $_REQUEST["sslmeth"]; + +if($mails_per_page == '') $mails_per_page='0'; + +if(isset($_REQUEST['record']) && $_REQUEST['record']!='') { + $id=$_REQUEST['record']; +} + +$focus = new Users(); +$encrypted_password=$focus->changepassword($_REQUEST['server_password']); +if(isset($_REQUEST['edit']) && $_REQUEST['edit'] && $_REQUEST['record']!='') { + $sql="update vtiger_mail_accounts set display_name = ?, mail_id = ?, account_name = ?, mail_protocol = ?, mail_username = ?"; + $params = array($displayname, $email, $account_name, $mailprotocol, $server_username); + if($server_password != '*****') { + $sql.=", mail_password=?"; + array_push($params, $encrypted_password); + } + $sql.=", mail_servername=?, box_refresh=?, mails_per_page=?, ssltype=? , sslmeth=?, int_mailer=? where user_id = ?"; + array_push($params, $mail_servername, $box_refresh, $mails_per_page, $ssltype, $sslmeth, $_REQUEST["int_mailer"], $id); +} else { + $account_id = $adb->getUniqueID("vtiger_mail_accounts"); + $sql="insert into vtiger_mail_accounts(account_id, user_id, display_name, mail_id, account_name, mail_protocol, mail_username, mail_password, mail_servername, box_refresh, mails_per_page, ssltype, sslmeth, int_mailer, status, set_default) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + $params = array($account_id, $current_user->id, $displayname, $email, $account_name, $mailprotocol, $server_username, $encrypted_password, $mail_servername, $box_refresh, $mails_per_page, $ssltype, $sslmeth, $_REQUEST["int_mailer"],'1','0'); +} + +$adb->pquery($sql, $params); + +$return_module = vtlib_purify($_REQUEST['return_module']); +if(empty($return_module)) $return_module = 'Webmails'; + +$return_action = vtlib_purify($_REQUEST['return_action']); +if(empty($return_action)) $return_action = 'index'; + +header("Location:index.php?module=$return_module&action=$return_action&mailbox=INBOX&parenttab=My Home Page"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/SaveOrgSharing.php b/oss/vtiger/trunk/modules/Users/SaveOrgSharing.php new file mode 100644 index 00000000..4966a121 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/SaveOrgSharing.php @@ -0,0 +1,38 @@ +pquery($sql2, array()); +$num_rows = $adb->num_rows($result2); + +for($i=0; $i<$num_rows; $i++) { + $ruleid=$adb->query_result($result2,$i,'ruleid'); + $tabid=$adb->query_result($result2,$i,'tabid'); + $reqval = $tabid.'_per'; + $permission=$_REQUEST[$reqval]; + $sql7="update vtiger_def_org_share set permission=? where tabid=? and ruleid=?"; + $adb->pquery($sql7, array($permission, $tabid, $ruleid)); + + if($tabid == 6) { + $sql8="update vtiger_def_org_share set permission=? where tabid=4"; + $adb->pquery($sql8, array($permission)); + } + + if($tabid == 9) { + $sql8="update vtiger_def_org_share set permission=? where tabid=16"; + $adb->pquery($sql8, array($permission)); + } +} +$loc = "Location: index.php?action=OrgSharingDetailView&module=Settings&parenttab=Settings"; +header($loc); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/SaveProfile.php b/oss/vtiger/trunk/modules/Users/SaveProfile.php new file mode 100644 index 00000000..5e0f131e --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/SaveProfile.php @@ -0,0 +1,212 @@ +getUniqueID("vtiger_profile"); +//Inserting values into Profile Table +$sql1 = "insert into vtiger_profile(profileid, profilename, description) values(?,?,?)"; +$adb->pquery($sql1, array($profile_id,$profilename, $description)); + + //Retreiving the vtiger_profileid + $sql2 = "select max(profileid) as current_id from vtiger_profile"; + $result2 = $adb->pquery($sql2, array()); + $profileid = $adb->query_result($result2,0,'current_id'); + + + //Retreiving the vtiger_tabs permission array + // + + //Retreiving the first profileid + $prof_query="select profileid from vtiger_profile order by profileid ASC"; + $prof_result = $adb->pquery($prof_query, array()); + $first_prof_id = $adb->query_result($prof_result,0,'profileid'); + +$tab_perr_result = $adb->pquery("select * from vtiger_profile2tab where profileid=?", array($first_prof_id)); +$act_perr_result = $adb->pquery("select * from vtiger_profile2standardpermissions where profileid=?", array($first_prof_id)); +$act_utility_result = $adb->pquery("select * from vtiger_profile2utility where profileid=?", array($first_prof_id)); +$num_tab_per = $adb->num_rows($tab_perr_result); +$num_act_per = $adb->num_rows($act_perr_result); +$num_act_util_per = $adb->num_rows($act_utility_result); + + //Updating vtiger_profile2global permissons vtiger_table + $view_all_req=$_REQUEST['view_all']; + $view_all = getPermissionValue($view_all_req); + + $edit_all_req=$_REQUEST['edit_all']; + $edit_all = getPermissionValue($edit_all_req); + + + $sql4="insert into vtiger_profile2globalpermissions values(?,?,?)"; + $adb->pquery($sql4, array($profileid,1, $view_all)); + + $sql4="insert into vtiger_profile2globalpermissions values(?,?,?)"; + $adb->pquery($sql4, array($profileid,2, $edit_all)); + + + //profile2tab permissions + for($i=0; $i<$num_tab_per; $i++) + { + $tab_id = $adb->query_result($tab_perr_result,$i,"tabid"); + $request_var = $tab_id.'_tab'; + if($tab_id != 3 && $tab_id != 16) + { + $permission = $_REQUEST[$request_var]; + if($permission == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + $sql4="insert into vtiger_profile2tab values(?,?,?)"; + $adb->pquery($sql4, array($profileid, $tab_id, $permission_value)); + + if($tab_id ==9) + { + $sql4="insert into vtiger_profile2tab values(?,?,?)"; + $adb->pquery($sql4, array($profileid,16, $permission_value)); + } + } + } + + //profile2standard permissions + for($i=0; $i<$num_act_per; $i++) + { + $tab_id = $adb->query_result($act_perr_result,$i,"tabid"); + $action_id = $adb->query_result($act_perr_result,$i,"operation"); + if($tab_id != 16) + { + $action_name = getActionname($action_id); + if($action_name == 'EditView' || $action_name == 'Delete' || $action_name == 'DetailView') + { + $request_var = $tab_id.'_'.$action_name; + } + elseif($action_name == 'Save') + { + $request_var = $tab_id.'_EditView'; + } + elseif($action_name == 'index') + { + $request_var = $tab_id.'_DetailView'; + } + + $permission = $_REQUEST[$request_var]; + if($permission == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + + $sql7="insert into vtiger_profile2standardpermissions values(?,?,?,?)"; + $adb->pquery($sql7, array($profileid, $tab_id, $action_id, $permission_value)); + + if($tab_id ==9) + { + $sql7="insert into vtiger_profile2standardpermissions values(?,?,?,?)"; + $adb->pquery($sql7, array($profileid, 16, $action_id, $permission_value)); + } + } + } + + //Update Profile 2 utility + for($i=0; $i<$num_act_util_per; $i++) + { + $tab_id = $adb->query_result($act_utility_result,$i,"tabid"); + + $action_id = $adb->query_result($act_utility_result,$i,"activityid"); + $action_name = getActionname($action_id); + $request_var = $tab_id.'_'.$action_name; + + + $permission = $_REQUEST[$request_var]; + if($permission == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + + $sql9="insert into vtiger_profile2utility values(?,?,?,?)"; + $adb->pquery($sql9, array($profileid, $tab_id, $action_id, $permission_value)); + + } + + + + $modArr=getFieldModuleAccessArray(); + + +foreach($modArr as $fld_module => $fld_label) +{ + $fieldListResult = getProfile2FieldList($fld_module, $first_prof_id); + $noofrows = $adb->num_rows($fieldListResult); + $tab_id = getTabid($fld_module); + for($i=0; $i<$noofrows; $i++) + { + $fieldid = $adb->query_result($fieldListResult,$i,"fieldid"); + $visible = $_REQUEST[$fieldid]; + if($visible == 'on') + { + $visible_value = 0; + } + else + { + $visible_value = 1; + } + //Updating the Mandatory vtiger_fields + $uitype = $adb->query_result($fieldListResult,$i,"uitype"); + $displaytype = $adb->query_result($fieldListResult,$i,"displaytype"); + $fieldname = $adb->query_result($fieldListResult,$i,"fieldname"); + $typeofdata = $adb->query_result($fieldListResult,$i,"typeofdata"); + $fieldtype = explode("~",$typeofdata); + if($fieldtype[1] == 'M') + { + $visible_value = 0; + } + //Updating the database + $sql11="insert into vtiger_profile2field values(?,?,?,?,?)"; + $adb->pquery($sql11, array($profileid, $tab_id, $fieldid, $visible_value,1)); + } +} + $loc = "Location: index.php?action=ListProfiles&module=Settings&mode=view&parenttab=Settings&profileid=".vtlib_purify($profileid)."&selected_tab=".vtlib_purify($def_tab)."&selected_module=".vtlib_purify($def_module); + header($loc); + + +/** returns value 0 if request permission is on else returns value 1 + * @param $req_per -- Request Permission:: Type varchar + * @returns $permission - can have value 0 or 1:: Type integer + * + */ +function getPermissionValue($req_per) +{ + if($req_per == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + return $permission_value; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/ShowHistory.html b/oss/vtiger/trunk/modules/Users/ShowHistory.html new file mode 100644 index 00000000..62568e4e --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/ShowHistory.html @@ -0,0 +1,53 @@ + + + + + + + + + +

    + + {MOD.LBL_LOGIN_HISTORY_BUTTON_LABEL} +

    + + +
    {START_LINK}  {PREVIOUS_LINK}   + {NEXT_LINK}  {END_LINK}   {START_RECORD} - {END_RECORD} {APP.LBL_LIST_OF} {ROW_COUNT}  
    + + + + + + + + + + + + + + + + + + + + +
     {APP.LBL_LIST_USER_NAME}{user_name_arrow} {APP.LBL_LIST_USERIP}{user_ip_arrow} {APP.LBL_LIST_SIGNIN}{login_time_arrow} {APP.LBL_LIST_SIGNOUT}{logout_time_arrow} {APP.LBL_LIST_STATUS}
    {LOGIN.USER_NAME}{LOGIN.USER_IP}{LOGIN.LOGIN_TIME}{LOGIN.LOGOUT_TIME}{LOGIN.STATUS}
    + +
    +
    + + diff --git a/oss/vtiger/trunk/modules/Users/ShowHistory.php b/oss/vtiger/trunk/modules/Users/ShowHistory.php new file mode 100644 index 00000000..a3524a53 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/ShowHistory.php @@ -0,0 +1,74 @@ +pquery($qry, array($username)); +$no_of_rows = $adb->num_rows($qry_result); + +//Retreiving the start value from request +if(isset($_REQUEST['start']) && $_REQUEST['start'] != '') { + $start = vtlib_purify($_REQUEST['start']); +} else { + $start=1; +} + +//Retreive the Navigation array +$navigation_array = getNavigationValues($start, $no_of_rows, '10'); + +$start_rec = $navigation_array['start']; +$end_rec = $navigation_array['end_val']; +$record_string= $app_strings[LBL_SHOWING]." " .$start_rec." - ".$end_rec." " .$app_strings[LBL_LIST_OF] ." ".$no_of_rows; + +$navigationOutput = getTableHeaderNavigation($navigation_array, $url_string,"Users","ShowHistory",''); + +$smarty->assign("CMOD", $mod_strings); +$smarty->assign("MOD", return_module_language($current_language, "Settings")); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("LIST_HEADER",$focus->getHistoryListViewHeader()); +$smarty->assign("LIST_ENTRIES",$focus->getHistoryListViewEntries($username, $navigation_array, $sorder, $sortby)); +$smarty->assign("RECORD_COUNTS", $record_string); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("CATEGORY",$category); + +$smarty->display("ShowHistoryContents.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/TemplateMerge.php b/oss/vtiger/trunk/modules/Users/TemplateMerge.php new file mode 100644 index 00000000..5d9363eb --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/TemplateMerge.php @@ -0,0 +1,30 @@ + +
    + + +
    + diff --git a/oss/vtiger/trunk/modules/Users/UpdateProfileChanges.php b/oss/vtiger/trunk/modules/Users/UpdateProfileChanges.php new file mode 100644 index 00000000..e7b15923 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/UpdateProfileChanges.php @@ -0,0 +1,204 @@ +pquery("select * from vtiger_profile2tab where profileid=?", array($profileid)); +$act_perr_result = $adb->pquery("select * from vtiger_profile2standardpermissions where profileid=?", array($profileid)); +$act_utility_result = $adb->pquery("select * from vtiger_profile2utility where profileid=?", array($profileid)); +$num_tab_per = $adb->num_rows($tab_perr_result); +$num_act_per = $adb->num_rows($act_perr_result); +$num_act_util_per = $adb->num_rows($act_utility_result); + + //Updating vtiger_profile2global permissons vtiger_table + $view_all_req=$_REQUEST['view_all']; + $view_all = getPermissionValue($view_all_req); + + $edit_all_req=$_REQUEST['edit_all']; + $edit_all = getPermissionValue($edit_all_req); + + $update_query = "update vtiger_profile2globalpermissions set globalactionpermission=? where globalactionid=1 and profileid=?"; + $adb->pquery($update_query, array($view_all, $profileid)); + $update_query = "update vtiger_profile2globalpermissions set globalactionpermission=? where globalactionid=2 and profileid=?"; + $adb->pquery($update_query, array($edit_all, $profileid)); + + + //profile2tab permissions + for($i=0; $i<$num_tab_per; $i++) + { + $tab_id = $adb->query_result($tab_perr_result,$i,"tabid"); + $request_var = $tab_id.'_tab'; + if($tab_id != 3 && $tab_id != 16) + { + $permission = $_REQUEST[$request_var]; + if($permission == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + $update_query = "update vtiger_profile2tab set permissions=? where tabid=? and profileid=?"; + $adb->pquery($update_query, array($permission_value, $tab_id, $profileid)); + if($tab_id ==9) + { + $update_query = "update vtiger_profile2tab set permissions=? where tabid=16 and profileid=?"; + $adb->pquery($update_query, array($permission_value, $profileid)); + } + } + } + + //profile2standard permissions + for($i=0; $i<$num_act_per; $i++) + { + $tab_id = $adb->query_result($act_perr_result,$i,"tabid"); + if($tab_id != 16) + { + $action_id = $adb->query_result($act_perr_result,$i,"operation"); + $action_name = getActionname($action_id); + if($action_name == 'EditView' || $action_name == 'Delete' || $action_name == 'DetailView') + { + $request_var = $tab_id.'_'.$action_name; + } + elseif($action_name == 'Save') + { + $request_var = $tab_id.'_EditView'; + } + elseif($action_name == 'index') + { + $request_var = $tab_id.'_DetailView'; + } + + $permission = $_REQUEST[$request_var]; + if($permission == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + $update_query = "update vtiger_profile2standardpermissions set permissions=? where tabid=? and Operation=? and profileid=?"; + $adb->pquery($update_query, array($permission_value, $tab_id, $action_id, $profileid)); + if($tab_id ==9) + { + $update_query = "update vtiger_profile2standardpermissions set permissions=? where tabid=16 and Operation=? and profileid=?"; + $adb->pquery($update_query, array($permission_value, $action_id, $profileid)); + } + + + + } + } + + //Update Profile 2 utility + for($i=0; $i<$num_act_util_per; $i++) + { + $tab_id = $adb->query_result($act_utility_result,$i,"tabid"); + + $action_id = $adb->query_result($act_utility_result,$i,"activityid"); + $action_name = getActionname($action_id); + $request_var = $tab_id.'_'.$action_name; + + + $permission = $_REQUEST[$request_var]; + if($permission == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + + $update_query = "update vtiger_profile2utility set permission=? where tabid=? and activityid=? and profileid=?"; + $adb->pquery($update_query, array($permission_value, $tab_id, $action_id, $profileid)); + + + } + + + + $modArr=getFieldModuleAccessArray(); + +foreach($modArr as $fld_module => $fld_label) +{ + $fieldListResult = getProfile2FieldList($fld_module, $profileid); + $noofrows = $adb->num_rows($fieldListResult); + $tab_id = getTabid($fld_module); + for($i=0; $i<$noofrows; $i++) + { + $fieldid = $adb->query_result($fieldListResult,$i,"fieldid"); + $visible = $_REQUEST[$fieldid]; + if($visible == 'on') + { + $visible_value = 0; + } + else + { + $visible_value = 1; + } + //Updating the Mandatory vtiger_fields + $uitype = $adb->query_result($fieldListResult,$i,"uitype"); + $displaytype = $adb->query_result($fieldListResult,$i,"displaytype"); + $fieldname = $adb->query_result($fieldListResult,$i,"fieldname"); + $typeofdata = $adb->query_result($fieldListResult,$i,"typeofdata"); + $fieldtype = explode("~",$typeofdata); + if($fieldtype[1] == 'M') + { + $visible_value = 0; + } + //Updating the database + $update_query = "update vtiger_profile2field set visible=? where fieldid=? and profileid=? and tabid=?"; + $adb->pquery($update_query, array($visible_value, $fieldid, $profileid, $tab_id)); + + } +} + if($return_action == 'profilePrivileges' || $return_action == 'ListProfiles') + { + $loc = "Location: index.php?action=".$return_action."&module=Settings&mode=view&parenttab=Settings&profileid=".$profileid."&selected_tab=".$def_tab."&selected_module=".$def_module; + } + else + { + $loc = "Location: index.php?action=".$return_action."&module=Users&mode=view&parenttab=Settings&profileid=".$profileid."&selected_tab=".$def_tab."&selected_module=".$def_module; + } + header($loc); + + /** returns value 0 if request permission is on else returns value 1 + * @param $req_per -- Request Permission:: Type varchar + * @returns $permission - can have value 0 or 1:: Type integer + * + */ +function getPermissionValue($req_per) +{ + if($req_per == 'on') + { + $permission_value = 0; + } + else + { + $permission_value = 1; + } + return $permission_value; +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/UserDeleteStep1.php b/oss/vtiger/trunk/modules/Users/UserDeleteStep1.php new file mode 100644 index 00000000..bf1cf699 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/UserDeleteStep1.php @@ -0,0 +1,80 @@ + +
    + + + + + + + + +
    '.$mod_strings['LBL_DELETE'].' '.$mod_strings['LBL_USER'].''.$app_strings[
    + + + + +
    + + + + + + + + + + + +
    '.$mod_strings['LBL_DELETE_USER'].''.$delete_user_name.'
    '.$mod_strings['LBL_TRANSFER_USER'].''; + + $output.='
    +
    + + + + +
    +
    +
    '; + +echo $output; +?> diff --git a/oss/vtiger/trunk/modules/Users/UserGroups.php b/oss/vtiger/trunk/modules/Users/UserGroups.php new file mode 100644 index 00000000..676da8b6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/UserGroups.php @@ -0,0 +1,31 @@ +getAllUserGroups($user_id); +$user_group_info = Array(); +foreach($oGetUserGroups->user_groups as $groupid) +{ + $user_group_info[$groupid] = getGroupDetails($groupid); +} +$smarty->assign("IS_ADMIN",is_admin($current_user)); +$smarty->assign("GROUPLIST",$user_group_info); +$smarty->assign("UMOD", $mod_strings); +$smarty->display("UserGroups.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Users/Users.js b/oss/vtiger/trunk/modules/Users/Users.js new file mode 100644 index 00000000..8398d9ba --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/Users.js @@ -0,0 +1,320 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ + + + +document.write(" + + + + + + + + + + + + + + + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Akilan
    Anusha
    Asha
    Bharath
    Bharathi
    Dhananjay
    Dina
    Don
    Fenzik
    Gopal
    Jeri
    Kiran
    Mani
    Mickie
    Minnie
    Musavir
    Nitin
    Panchavarnam
    Pavani
    Philip
    Pinaki
    Prasad
    Preethi
    Puneeth
    Radiant
    Richie
    Sandeep
    Shahul
    Sidharth
    Sreenivas
    Srinivasan
    Tamilmani
    Vamsee
    Varma
    Vashni
     
    Aissa Belaid
    Allan Bush
    Brian Devendorf
    Brian Laughlin
    Davide Giarolo
    Dennis Grant
    Dhr. R.R. Gerbrands
    Dino Eberle
    Dirk Gorny
    Fathi Boudra
    Frank Piepiorra
    Jamie Jackson
    Jeff Kowalczyk
    Jens Gammelgaard
    Jens Hamisch
    Joao Oliveira
    Joel Rydbeck
    Josh Lee
    Ken Lyle
    Kim Haverblad
    Manilal K M
    Matjaz Slak
    Matthew Brichacek
    Michel Jacquemes
    Mike Crowe
    Mike Fedyk
    Neil
    Tim Smith
    Sergio A. Kessler
    Steve Fairchild
    Valmir Carlos Trindade
     
    -
    ADOdb
    Ajax Popup Chat
    Apache HTTP Server
    Attachments in E-mail Client
    Calculator
    Carousel Slideshow
    class_http
    ExcelReader
    FCKeditor
    FPDF
    freetag
    gdwin32
    Graph
    Image Crossfade Redux
    Image_Canvas
    Image_Color
    jscalendar
    log4php
    MagpieRSS
    Mailfeed
    MySQL
    nusoap
    NOCC
    PHP
    PHPMailer
    phpSysinfo
    Prototype
    script.oculo.us
    Smarty Template Engine
    SugarCRM (SPL 1.1.2)
    TCPDF
     
     
     
    +
    +
     
     
    + + + + + +
    +  |  +  |  +  |  + + + +
    +
    + + diff --git a/oss/vtiger/trunk/modules/Users/binaryfilelist.php b/oss/vtiger/trunk/modules/Users/binaryfilelist.php new file mode 100644 index 00000000..d3a957a8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/binaryfilelist.php @@ -0,0 +1,98 @@ +pquery($dbQuery, array()) or die("Couldn't get file list"); + +$list = ''; + +$list .= ''; +$list .=''; +$list .= ''; + +$list .= ''; + +$list .= ''; + +$list .= ''; + +$list .= ''; + +$list .= ''; + +$list .= ''; + +//$list .= ''; + +$i=1; +while($row = $adb->fetch_array($result)) +{ + + +if ($i%2==0) +$trowclass = 'evenListRow'; +else +$trowclass = 'oddListRow'; + $list .= ''; + + $list .= ''; + $list .= ''; + + $list .= ''; + + $list .= ''; +$i++; +} + + $list .= '
    '.$app_strings['LBL_OPERATION'].'
    '; +$list .= $app_strings['LBL_FILENAME'].''; +$list .= $mod_strings['LBL_MODULENAMES'].''; +$list .= $app_strings['LBL_UPD_DESC'].''; +$list .= $app_strings['LBL_TYPE'].''; +$list .= $app_strings['LBL_FILE'].'
    Del '; + + $list .= $row["filename"]; + + $list .= ''.$row["module"].''; + + $list .= $row["description"]; + + $list .= ''; + + $list .= $row["filetype"]; + + $list .= ''; + + $list .= ''; + + $list .= $app_strings['LBL_DOWNLOAD']; + + $list .= '
    '; + +return $list; +} +?> diff --git a/oss/vtiger/trunk/modules/Users/deletewordtemplate.php b/oss/vtiger/trunk/modules/Users/deletewordtemplate.php new file mode 100644 index 00000000..bf7aced2 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/deletewordtemplate.php @@ -0,0 +1,19 @@ +pquery($sql, array($id_array[$i])); +} +header("Location:index.php?module=Users&action=listwordtemplates&parenttab=Settings"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/downloadfile.php b/oss/vtiger/trunk/modules/Users/downloadfile.php new file mode 100644 index 00000000..222aa138 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/downloadfile.php @@ -0,0 +1,41 @@ +pquery($dbQuery, array($templateid)) or die("Couldn't get file list"); +if($adb->num_rows($result) == 1) +{ +$fileType = $adb->query_result($result, 0, "filetype"); +$name = $adb->query_result($result, 0, "filename"); +//echo 'filetype is ' .$fileType; +$fileContent = $adb->query_result($result, 0, "data"); +$size = $adb->query_result($result, 0, "filesize"); +$name = html_entity_decode($name, ENT_QUOTES, $default_charset); +header("Content-type: $fileType"); +//header("Content-length: $size"); +header("Cache-Control: private"); +header("Content-Disposition: attachment; filename=$name"); +header("Content-Description: PHP Generated Data"); +echo base64_decode($fileContent); +} +else +{ +echo "Record doesn't exist."; +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/getListOfRecords.php b/oss/vtiger/trunk/modules/Users/getListOfRecords.php new file mode 100644 index 00000000..f6db14a7 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/getListOfRecords.php @@ -0,0 +1,124 @@ +pquery("SELECT tablename,entityidfield, fieldname from vtiger_entityname WHERE modulename = ?",array($sModule)); +$table_name = $adb->query_result($query,0,'tablename'); +$field_name = $adb->query_result($query,0,'fieldname'); +$id_field = $adb->query_result($query,0,'entityidfield'); +$fieldname = split(",",$field_name); +$fields_array = array($sModule=>$fieldname); +$id_array = array($sModule=>$id_field); +$tables_array = array($sModule=>$table_name); + +$permittedFieldNameList = array(); +foreach ($fieldname as $fieldName) { + $checkForFieldAccess = $fieldName; + // Handling case where fieldname in vtiger_entityname mismatches fieldname in vtiger_field + if($sModule == 'HelpDesk' && $checkForFieldAccess == 'title') { + $checkForFieldAccess = 'ticket_title'; + } else if($sModule == 'Documents' && $checkForFieldAccess == 'title') { + $checkForFieldAccess = 'notes_title'; + } + // END + if(getFieldVisibilityPermission($sModule,$current_user->id, $checkForFieldAccess) == '0'){ + $permittedFieldNameList[] = $fieldName; + } +} + +$cv = new CustomView(); +$viewId = $cv->getViewId($sModule); +if(!empty($_SESSION[$sModule.'_DetailView_Navigation'.$viewId])){ + $recordNavigationInfo = Zend_Json::decode($_SESSION[$sModule.'_DetailView_Navigation'.$viewId]); + $recordList = array(); + $recordIndex = null; + $recordPageMapping = array(); + foreach ($recordNavigationInfo as $start=>$recordIdList){ + foreach ($recordIdList as $index=>$recordId) { + $recordList[] = $recordId; + $recordPageMapping[$recordId] = $start; + if($recordId == $iCurRecord){ + $recordIndex = count($recordList)-1; + } + } + } +}else{ + $recordList = array(); +} +$output = ' + + + +
    Jump to '.$app_strings[$sModule].':
    + +
    + +
    '; +$output .= '
    '; +$output .= ''; + +if(count($recordList) > 0){ + $displayRecordCount = 10; + $count = count($recordList); + $idListEndIndex = ($count < ($recordIndex+$displayRecordCount))? ($count+1) : ($recordIndex+$displayRecordCount+1); + $idListStartIndex = $recordIndex-$displayRecordCount; + if($idListStartIndex < 0){ + $idListStartIndex = 0; + } + $idsArray = array_slice($recordList,$idListStartIndex,($idListEndIndex - $idListStartIndex)); + + $selectColString = implode(',',$permittedFieldNameList).', '.$id_array[$sModule]; + $fieldQuery = "SELECT $selectColString from ".$tables_array[$sModule]." WHERE ".$id_array[$sModule]." IN (". generateQuestionMarks($idsArray) .")"; + + $fieldResult = $adb->pquery($fieldQuery,$idsArray); + $numOfRows = $adb->num_rows($fieldResult); + $recordNameMapping = array(); + for($i=0; $i<$numOfRows; ++$i) { + $recordId = $adb->query_result($fieldResult,$i,$id_array[$sModule]); + $fieldValue = ''; + foreach ($permittedFieldNameList as $fieldName) { + $fieldValue .= " ".$adb->query_result($fieldResult,$i,$fieldName); + } + $fieldValue = textlength_check($fieldValue); + $recordNameMapping[$recordId] = $fieldValue; + } + foreach ($idsArray as $id) { + if($id===$iCurRecord){ + $output .= ''; + }else{ + $output .= ''; + } + } +} +$output .= '
    '.$recordNameMapping[$id].'
    '.$recordNameMapping[$id].'
    '; +$output .= '
    '; + +echo $output; +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/language/en_us.lang.php b/oss/vtiger/trunk/modules/Users/language/en_us.lang.php new file mode 100644 index 00000000..ed6d0080 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/language/en_us.lang.php @@ -0,0 +1,682 @@ +'Users', +'LBL_MODULE_TITLE'=>'Users: Home', +'LBL_SEARCH_FORM_TITLE'=>'User Search', +'LBL_LIST_FORM_TITLE'=>'User List', +'LBL_NEW_FORM_TITLE'=>'New User', +'LBL_CREATE_NEW_USER'=>'Create New User', +'LBL_LOGIN'=>'Login', +'LBL_USER_ROLE'=>'Role', +'LBL_LIST_NAME'=>'Name', +'LBL_LIST_LAST_NAME'=>'Last Name', +'LBL_LIST_USER_NAME'=>'User Name', +'LBL_LIST_DEPARTMENT'=>'Department', +'LBL_LIST_EMAIL'=>'E-Mail', +'LBL_LIST_PRIMARY_PHONE'=>'Primary Phone', +'LBL_LIST_ADMIN'=>'Admin', +'LBL_LIST_CONFIRM_PASSWORD'=>'Confirm Password', +'LBL_LIST_USER_NAME_ROLE'=>'User ID , Name & Role', +'LBL_LIST_SELECT'=>'Select', +'LBL_LIST_PHONE'=>'Phone', +'LBL_LIST_NO'=>'#', + +'LBL_ADMINS'=>'Admins', +'LBL_STD_USERS'=>'Standard Users', + +'UserName'=>'UserName', +'Name'=>'Name', +'Tools'=>'Tools', + + +//added for patch2 +'LBL_GROUP'=>'Group', +'LBL_CURRENCY_NAME'=>'Currency', + +'LBL_NEW_USER_BUTTON_TITLE'=>'New User [Alt+N]', +'LBL_NEW_USER_BUTTON_LABEL'=>'New User', +'LBL_NEW_USER_BUTTON_KEY'=>'N', +'LBL_DATE_FORMAT'=>'Date Format', + +'LBL_ERROR'=>'Error:', +'LBL_PASSWORD'=>'Password', +'LBL_USER_NAME'=>'User Name', +'LBL_CRM_ID'=>'CRM ID', +'LBL_FIRST_NAME'=>'First Name', +'LBL_LAST_NAME'=>'Last Name', +'LBL_YAHOO_ID'=>'Yahoo ID', +'LBL_THEME'=>'Color Theme', +'LBL_LANGUAGE'=>'Language', +'LBL_ADMIN'=>'Admin', +'LBL_OFFICE_PHONE'=>'Office Phone', +'LBL_REPORTS_TO'=>'Reports to', +'LBL_OTHER_PHONE'=>'Other Phone', +'LBL_OTHER_EMAIL'=>'Other Email', +'LBL_DEPARTMENT'=>'Department', +'LBL_STATUS'=>'Status', +'LBL_TITLE'=>'Title', +'LBL_ANY_PHONE'=>'Any Phone:', +'LBL_ANY_EMAIL'=>'Any Email:', +'LBL_ADDRESS'=>'Street Address', +'LBL_CITY'=>'City', +'LBL_STATE'=>'State', +'LBL_POSTAL_CODE'=>'Postal Code', +'LBL_COUNTRY'=>'Country', +'LBL_USER_SETTINGS'=>'User Settings', +'LBL_USER_INFORMATION'=>'User Information', +'LBL_MOBILE_PHONE'=>'Mobile', +'LBL_OTHER'=>'Other', +'LBL_FAX'=>'Fax', +'LBL_EMAIL'=>'E-Mail Id', +'LBL_HOME_PHONE'=>'Home Phone', +'LBL_ADDRESS_INFORMATION'=>'User Address', +'LBL_CAL_HRFORMAT'=>'Calendar Time Format', +'LBL_CAL_DURATION'=>'Day starts at', +'LBL_PRIMARY_ADDRESS'=>'Primary Address:', + +'LBL_CHANGE_PASSWORD_BUTTON_TITLE'=>'Change Password [Alt+P]', +'LBL_CHANGE_PASSWORD_BUTTON_KEY'=>'P', +'LBL_CHANGE_PASSWORD_BUTTON_LABEL'=>'Change Password', +'LBL_LOGIN_BUTTON_TITLE'=>'Login [Alt+L]', +'LBL_LOGIN_BUTTON_KEY'=>'L', +'LBL_LOGIN_BUTTON_LABEL'=>'Login', +'LBL_LOGIN_HISTORY_BUTTON_TITLE'=>'Login History [Alt+H]', +'LBL_LOGIN_HISTORY_BUTTON_KEY'=>'H', +'LBL_LOGIN_HISTORY_BUTTON_LABEL'=>'Login History', +'LBL_LOGIN_HISTORY_TITLE'=>'Users: Login History', +'LBL_RESET_PREFERENCES'=>'Reset To Default Preferences', + +'LBL_CHANGE_PASSWORD'=>'Change Password', +'LBL_OLD_PASSWORD'=>'Old Password:', +'LBL_NEW_PASSWORD'=>'New Password:', +'LBL_CONFIRM_PASSWORD'=>'Confirm Password:', +'ERR_ENTER_OLD_PASSWORD'=>'Please enter your old password.', +'ERR_ENTER_NEW_PASSWORD'=>'Please enter your new password.', +'ERR_ENTER_CONFIRMATION_PASSWORD'=>'Please enter your password confirmation.', +'ERR_REENTER_PASSWORDS'=>'Please re-enter passwords. The \"new password\" and \"confirm password\" values do not match.', +'ERR_INVALID_PASSWORD'=>'You must specify a valid username and password.', +'ERR_PASSWORD_CHANGE_FAILED_1'=>'User password change failed for ', +'ERR_PASSWORD_CHANGE_FAILED_2'=>' failed. The new password must be set.', +'ERR_PASSWORD_INCORRECT_OLD'=>'Incorrect old password specified. Re-enter password information.', +'ERR_USER_NAME_EXISTS_1'=>'The user name ', +'ERR_USER_NAME_EXISTS_2'=>' already exists. Duplicate user names are not allowed.
    Change the user name to be unique.', +'ERR_LAST_ADMIN_1'=>'The user name ', +'ERR_LAST_ADMIN_2'=>' is the last Admin user. At least one user must be an Admin user.
    Check the Admin user setting.', + +'ERR_DELETE_RECORD'=>"A record number must be specified to delete the account.", + +// Additional Fields for i18n --- Release vtigerCRM 3.2 Patch 2 +// Users--listroles.php , createrole.php , ListPermissions.php , editpermissions.php + +'LBL_ROLES'=>'Roles', +'LBL_ROLES_SUBORDINATES'=>'Roles and Subordinates', + +'LBL_CREATE_NEW_ROLE'=>'Create New Role', +'LBL_INDICATES_REQUIRED_FIELD'=>'Indicates Required Field', +'LBL_NEW_ROLE'=>'New Role', +'LBL_PARENT_ROLE'=>'Parent Role', + +'LBL_LIST_ROLES'=>'List Roles', +'LBL_ENTITY_LEVEL_PERMISSIONS'=>'Entity Level Permissions', +'LBL_ENTITY'=>'Entity', +'LBL_CREATE_EDIT'=>'Create/Edit', +'LBL_DELETE'=>'Delete', +'LBL_LEADS'=>'Leads', +'LBL_ACCOUNTS'=>'Accounts', +'LBL_CONTACTS'=>'Contacts', +'LBL_OPPURTUNITIES'=>'Opportunities', +'LBL_TASKS'=>'Tasks', +'LBL_CASES'=>'Cases', +'LBL_EMAILS'=>'Email', +'LBL_NOTES'=>'Documents', +'LBL_MEETINGS'=>'Meetings', +'LBL_CALLS'=>'Calls', +'LBL_IMPORT_PERMISSIONS'=>'Import Permissions', +'LBL_IMPORT_LEADS'=>'Import Leads', +'LBL_IMPORT_ACCOUNTS'=>'Import Accounts', +'LBL_IMPORT_CONTACTS'=>'Import Contacts', +'LBL_IMPORT_OPPURTUNITIES'=>'Import Opportunities', + +'LBL_ROLE_DETAILS'=>'Role Details', +//added for vtigercrm4 rc +'LBL_FILE'=> 'File Name', +'LBL_FILE_TYPE'=>'File Type', +'LBL_UPLOAD'=>'Upload File', +'LBL_ATTACH_FILE'=>'Attach Mail Merge Template', +'LBL_EMAIL_TEMPLATES'=>'Email Templates', +'LBL_TEMPLATE_HEADER'=>'Template', +'LBL_TEMPLATE_DETAILS'=>'Template Details', +'LBL_EDIT_TEMPLATE'=>'Edit Template', +'LBL_TEMPLATE_FILE'=>'Template File', +'LBL_EMAIL_TEMPLATES_LIST'=>'Communication Templates > Email Templates', +'LBL_MAILMERGE_TEMPLATES_LIST'=>' > Communication Templates > Mail Merge Templates', +'LBL_MAILMERGE_TEMPLATES_ATTACHMENT' => '> Communication Templates > Attach Mail Merge Template', +'LBL_DOWNLOAD_NOW'=>'Download Now', +'LBL_DOWNLOAD'=>'Download', +'LBL_SELECT_MODULE'=>'Select Module', +'LBL_MERGE_FILE'=>'File : ', +'LBL_MERGE_MSG'=>'Select a module to assign this Template', +'LBL_MERGE_FIELDS'=>'Merge Fields', +'LBL_COPY_PASTE'=>'Copy & Paste', +'LNK_GO_TO_TOP'=>'Go to Page Top', +'LBL_COLON'=>':', +'LBL_EMAIL_TEMPLATE'=>'Email Template', +'LBL_NEW_TEMPLATE'=>'New Template', +'LBL_ADD_TEMPLATE'=>'Add Template', +'LBL_USE_MERGE_FIELDS_TO_EMAIL_CONTENT'=>'Use merge fields to personalize your email content.', +'LBL_AVAILABLE_MERGE_FIELDS'=>'Available Merge Fields', +'LBL_SELECT_FIELD_TYPE'=>'Select Field Type', +'LBL_SELECT_FIELD'=>'Select Field :', +'LBL_MERGE_FIELD_VALUE'=>'Copy Merge Field Value :', +'LBL_ACCOUNT_FIELDS'=>'Account Fields', +'LBL_CONTACT_FIELDS'=>'Contact Fields', +'LBL_LEAD_FIELDS'=>'Lead Fields', +'LBL_COPY_AND_PASTE_MERGE_FIELD'=>'Copy and paste the merge field value into your template below.', +'LBL_EMAIL_TEMPLATE_INFORMATION'=>'Communication Templates > Email Templates > Viewing', +'LBL_FOLDER'=>'Folder', +'LBL_PERSONAL'=>'Personal', +'LBL_PUBLIC'=>'Public', +'LBL_TEMPLATE_NAME'=>'Template Name:', +'LBL_SUBJECT'=>'Subject', +'LBL_BODY'=>'Email Body', +'LBL_TEMPLATE_TOOLS'=>'Tools', +'LBL_TEMPLATE_PUBLIC'=>'Public Access', +'LBL_TEMPLATE_PRIVATE'=>'Private Access', +'LBL_TEMPLATE_SUBJECT'=>'Email Subject', +'LBL_TEMPLATE_MESSAGE'=>'Email Message', +'LBL_VIEWING'=>'Viewing', +'LBL_PROPERTIES'=>'Properties of', + + + +// Added fields in createnewgroup.php +'LBL_CREATE_NEW_GROUP'=>'Create New Group', +'LBL_NEW_GROUP'=>'New Group', +'LBL_EDIT_GROUP'=>'Edit Group', +'LBL_GROUP_NAME'=>'Group Name', +'LBL_GROUP_DETAILS'=>'Group Details', +'LBL_MEMBER'=>'Members', +'LBL_MEMBER_AVLBL'=>'Available Entities & Members', +'LBL_MEMBER_SELECTED'=>'Selected Members', +'LBL_GROUP_MESG1'=>'Groups are a flexible way to assign access rights, when complex access rights has to be defined. You can combine multiple entities like Roles, Users, profiles etc into a single group.', +'LBL_GROUP_MESG2'=>'To add, select the Entity members from left and click the ">>" button.', +'LBL_GROUP_MESG3'=>'To remove, select the group members from the right and click the "<<" button.', + + +// Added fields in detailViewmailtemplate.html,listgroupmembers.php,listgroups.php +'LBL_DETAIL_VIEW_OF_EMAIL_TEMPLATE'=>'Detail View of Email Template', +'LBL_DETAIL_VIEW'=>'Detail View of', +'LBL_EDIT_VIEW'=>'Editing details of the user', +'LBL_EDITING'=>'Editing user', +'LBL_GROUP_MEMBERS_LIST'=>'Group members list', +'LBL_GROUPS'=>'Groups', +'LBL_MY_GROUPS'=>'My Groups', +'LBL_ADD_GROUP_BUTTON'=>'Add Group', +'LBL_WORD_TEMPLATES'=>'Mail Merge Templates', +'LBL_NEW_WORD_TEMPLATE'=>'New Template', +'LBL_EMAIL_TEMPLATE_DESC'=>'Manage email templates used for Campaigns and Mass mailing', +'LBL_NAME'=>'Name', + +// Added fields in TabCustomise.php,html and UpdateTab.php,html +'LBL_CUSTOMISE_TABS'=>'Customize Tabs', +'LBL_CHOOSE_TABS'=>'Choose Tabs', +'LBL_AVAILABLE_TABS'=>'Available Tabs', +'LBL_SELECTED_TABS'=>'Selected Tabs', +'LBL_USER'=>'User', +'LBL_TAB_MENU_UPDATED'=>'Tab Menu Updated! kindly go to ', +'LBL_TO_VIEW_CHANGES'=>' to view the changes', + +// Added to change homepage order +'LBL_CHANGE_HOMEPAGE_LABEL'=>'Homepage Order', +'LBL_CHANGE_HOMEPAGE_TITLE'=>'Homepage', + +// Added fields in binaryfilelist.php +'LBL_OERATION'=>'Operation', + +// Added fields in CreateProfile.php +'LBL_PROFILE_NAME'=>'Create New Profile:', +'LBL_NEW_PROFILE'=>'New Profile', +'LBL_NEW_PROFILE_NAME'=>'Profile Name', +'LBL_PARENT_PROFILE'=>'Parent Profile', +'LBL_BASIC_PROFILE_DETAILS'=>'Basic details of Profile', +'LBL_STEP_1_2'=>'Step 1 of 2', +'LBL_STEP_2_2'=>'Step 2 of 2', +'LBL_STEP'=>'Step', +'LBL_SELECT_BASE_PROFILE'=>'Select Base Profile', +'LBL_PROFILE_PRIVILEGES'=>'Profile Privileges', +'LBL_GLOBAL_PRIVILEGES'=>'Global Privileges', +'LBL_TAB_PRIVILEGES'=>'Tab Privileges', +'LBL_FIELD_PRIVILEGES'=>'Field Privileges', +'LBL_STANDARD_PRIVILEGES'=>'Standard Privileges', +'LBL_UTILITY_PRIVILEGES'=>'Utility Privileges', +'LBL_UTILITIES'=>'Utilities', +'LBL_BASE_PROFILE_MESG'=>'I would like to setup a base profile and edit privileges (Recommended)', +'LBL_BASE_PROFILE'=>'Base Profile:', +'LBL_OR'=>'OR', +'LBL_BASE_PROFILE_MESG_ADV'=>'I will choose the privileges from scratch (Advanced Users)', +'LBL_FOR'=>'for', +'LBL_GLOBAL_MESG_OPTION'=>'Select the options below to change global privileges', +'LBL_VIEW_ALL'=>'View all', +'LBL_EDIT_ALL'=>'Edit all', +'LBL_ALLOW'=>'Allows', +'LBL_MESG_VIEW'=>'to view all information / modules of vtiger CRM', +'LBL_MESG_EDIT'=>'to edit all information / modules of vtiger CRM', +'LBL_STD_MESG_OPTION'=>'Select the standard actions to be permitted', +'LBL_TAB_MESG_OPTION'=>'modules to be shown', +'LBL_UTILITY_MESG_OPTION'=>'Select the utility actions to be permitted', +'LBL_FIELD_MESG_OPTION'=>'Select the fields to be permitted', +'LBL_FINISH_BUTTON'=>'Finish', +'LBL_PROFILE_DETAIL_VIEW'=>'Detail View of Profile', +'LBL_PROFILE_MESG'=>'Viewing access privileges for', +'LBL_PROFILE_M'=>'Profile', +'LBL_DEFINE_PRIV_FOR'=>' Define Privileges for ', +'LBL_USE_OPTION_TO_SET_PRIV'=>'Use the options below to set privileges', +'LBL_SUPER_USER_PRIV'=>'Global Privileges', +'LBL_SET_PRIV_FOR_EACH_MODULE'=>'Set Privileges for each Module ', +'LBL_FIELDS_AND_TOOLS_SETTINGS'=>'Fields & Tools Settings', +'LBL_SHOW_FIELDS'=>'Show Fields', +'LBL_TOOLS_TO_BE_SHOWN'=>'Tools to be shown', +'LBL_WELCOME_PROFILE_CREATE'=>'Welcome to Privilege Profile Creator ', +'LBL_SELECT_CHOICE_NEW_PROFILE'=>'Select your choice of creating the new profile', +'LBL_ADD_CUSTOM_RULE'=>'Add Custom Privilege Rule', +'LBL_EDIT_CUSTOM_RULE'=>'Edit Custom Privilege Rule', +'LBL_CLOSE'=>'Close', +'LBL_SELECT_ENTITY'=>'Select an entity below', +'LBL_CAN_BE_ACCESSED_BY'=>'Can be accessed by', +'LBL_PERMISSIONS'=>'Permissions', +'LBL_ACCESS_RIGHTS_FOR_MODULES'=>'Access rights for relative modules', +'LBL_RULE_CONSTRUCTION'=>'Rule Construction Display', +'LBL_ADD_RULE'=>'Add Rule', +'LBL_RELATED_MODULE_RIGHTS'=>'Related Module Rights', +'LBL_IN_PERMISSION'=>'in the permission', + +//Added fields in createrole.php +'LBL_HDR_ROLE_NAME'=>'Create New Role:', +'LBL_TITLE_ROLE_NAME'=>'New Role', +'LBL_ROLE_NAME'=>'Role Name', +'LBL_ROLE_PROFILE_NAME'=>'Associate With Profile', +'LBL_SPECIFY_ROLE_NAME'=>'Specify a name for new role :', +'LBL_ASSIGN_PROFILE'=>'Assign Profile(s)', +'LBL_PROFILE_SELECT_TEXT'=>'Select the Profiles below and click on assign button', +'LBL_PROFILES_AVLBL'=>'Profiles Available', +'LBL_ASSIGN_PROFILES'=>'Assigned Profiles', +'LBL_REPORTS_TO_ROLE'=>'Reports to Role', +'LBL_ASSOCIATED_PROFILES'=>'Associated Profiles :', +'LBL_ASSOCIATED_USERS'=>'Associated Users :', + + +//Added fields in OrgSharingDetailsView.php +'LBL_ORG_SHARING_PRIVILEGES'=>'Organisation Sharing Privileges', +'LBL_EDIT_PERMISSIONS'=>'Edit Permissions', +'LBL_SAVE_PERMISSIONS'=>'Save Permissions', +'LBL_READ_ONLY'=>'Public: Read Only', +'LBL_EDIT_CREATE_ONLY'=>'Public: Read, Create/Edit', +'LBL_READ_CREATE_EDIT_DEL'=>'Public: Read, Create/Edit, Delete', +'LBL_PRIVATE'=>'Private', + +//Added fields in listnotificationschedulers.php +'LBL_HDR_EMAIL_SCHDS'=>'Users : Email Notifications', +'LBL_EMAIL_SCHDS_DESC'=>'The following is the list of notifications that are activated automatically when the corresponding event has happened.', +'LBL_ACTIVE'=>'Active', +'LBL_INACTIVE'=>'Inactive', +'LBL_NOTIFICATION'=>'Notification', +'LBL_DESCRIPTION'=>'Description', +'LBL_TASK_NOTIFICATION'=>'Delayed Task Notification', +'LBL_TASK_NOTIFICATION_DESCRITPION'=>'Notify when a task is delayed beyond 24 hrs', +'LBL_MANY_TICKETS'=>'Too many tickets Notification', +'LBL_MANY_TICKETS_DESCRIPTION'=>'Notify when a particular entity is allocated too many tickets, might reflect Service Level commitments', +'LBL_PENDING_TICKETS'=>'Pending Tickets Notification', +'LBL_TICKETS_DESCRIPTION'=>'Notify for getting attention to status of tickets which are pending', +'LBL_START_NOTIFICATION'=>'Support Start Notification', +'LBL_START_DESCRIPTION'=>'Notifiy stating the start of support/service', +'LBL_BIG_DEAL'=>'Big Deal Notification', +'LBL_BIG_DEAL_DESCRIPTION'=>'Notify on completion of big deal', +'LBL_SUPPORT_NOTICIATION'=>'Support End Notification', +'LBL_SUPPORT_DESCRIPTION'=>'Notify when support is about to end', +'LBL_BUTTON_UPDATE'=>'Update', +'LBL_MODULENAMES'=>'Module', + +//Added fields in ListFieldPermissions.html +'LBL_FIELD_PERMISSION_FIELD_NAME'=>'Field Name', +'LBL_FIELD_PERMISSION_VISIBLE'=>'Visible', +'LBL_FIELD_PERMISSIOM_TABLE_HEADER'=>'Standard Fields', +'LBL_FIELD_LEVEL_ACCESS'=>'Field Level Access', + +//Added fields after 4.0.1 +'LBL_SIGNATURE'=>'Signature', + +//Added for Event Reminder 4.2 Alpha release +'LBL_ACTIVITY_NOTIFICATION'=>'Event Reminder Notification', +'LBL_ACTIVITY_REMINDER_DESCRIPTION'=>'Notify before an event to occur based on the reminder set', +'LBL_MESSAGE'=>'Message', + +//Added for Global Privileges + +'Public: Read Only'=>'Public: Read Only', +'Public: Read, Create/Edit'=>'Public: Read, Create/Edit', +'Public: Read, Create/Edit, Delete'=>'Public: Read, Create/Edit, Delete', +'Private'=>'Private', +'Hide Details'=>'Hide Details', +'Hide Details and Add Events'=>'Hide Details and Add Events', +'Show Details'=>'Show Details', +'Show Details and Add Events'=>'Show Details and Add Events', + +'LBL_USR_CANNOT_ACCESS'=>'Users cannot access other users ', +'LBL_USR_CAN_ACCESS'=>'Users can ', +'LBL_USR_OTHERS'=>' other users ', + +'Read Only '=>'Read Only ', +'Read, Create/Edit, Delete '=>'Read, Create/Edit, Delete ', +'Read, Create/Edit '=>'Read, Create/Edit ', +'Read/Write'=>'Read/Write', +'LBL_GO_TO_TOP'=>'Go to Top', +'LNK_CLICK_HERE'=>'Click here', +'LBL_RULE_NO'=>'Rule No.', +'LBL_CAN_BE_ACCESSED'=>'can be accessed by', +'LBL_PRIVILEGES'=>'Privileges', +'LBL_OF'=>'of', + + + +//Added for 4.2GA support for mail server integration +'LBL_ADD_MAILSERVER_BUTTON_TITLE'=>'Add Mail Server', +'LBL_ADD_MAILSERVER_BUTTON_KEY'=>'M', +'LBL_ADD_MAILSERVER_BUTTON_LABEL'=>'Add Mail Server', + +'LBL_LIST_MAILSERVER_BUTTON_TITLE'=>'List Mail Server', +'LBL_LIST_MAILSERVER_BUTTON_KEY'=>'L', +'LBL_LIST_MAILSERVER_BUTTON_LABEL'=>'List Mail Server', +//added for inventory terms and conditions +'INV_TANDC'=>'Terms & Coditions', +'INV_TERMSANDCONDITIONS'=>'Inventory Terms & Coditions', +'LBL_INV_TERMSANDCONDITIONS'=>'Inventory Management', + + +'INVENTORYNOTIFICATION'=>'Inventory Notifications', +'LBL_INVENTORY_NOTIFICATIONS'=>'Edit Inventory Email Notifications', +'LBL_INV_NOT_DESC'=>'The following are the list of notifications that are sent to the product handler regarding the demand and the current quantity in hand during the creation of a Quote, SalesOrder and Invoice.', + +'InvoiceNotification'=>'Product Stock Notification during Invoice Generation', +'InvoiceNotificationDescription'=>'When the product stock level goes below the re-order level, notification will be sent to the product handler', + +'QuoteNotification'=>'Product Stock Notification during Quote Generation', +'QuoteNotificationDescription'=>'During quote generation if the product stock in warehouse is lesser than the quantity mentioned in quote then this notification will be sent to the product handler', + +'SalesOrderNotification'=>'Product Stock Notification during Sales Order Generation', +'SalesOrderNotificationDescription'=>'During sales order generation if the product stock in warehouse is lesser than the quantity mentioned in sales order then this notification will be sent to the product handler', + +//New addition for 4.2 GA +'LBL_USER_FIELDS'=>'User Fields', +'LBL_NOTE_DO_NOT_REMOVE_INFO'=>'Note: Donot remove or alter the values within { }', + +//Added for patch2 +'LBL_FILE_INFORMATION'=>'File Information', + +//Added after pathc2 +'LBL_LEAD_FIELD_ACCESS'=>'Lead Field Access', + +'LBL_ACCOUNT_FIELD_ACCESS'=>'Account Field Access', + +'LBL_CONTACT_FIELD_ACCESS'=>'Contact Field Access', + +'LBL_OPPORTUNITY_FIELD_ACCESS'=>'Potential Field Access', + +'LBL_HELPDESK_FIELD_ACCESS'=>'HelpDesk Field Access', + +'LBL_PRODUCT_FIELD_ACCESS'=>'Product Field Access', + +'LBL_NOTE_FIELD_ACCESS'=>'Document Field Access', + +'LBL_EMAIL_FIELD_ACCESS'=>'Email Field Access', + +'LBL_TASK_FIELD_ACCESS'=>'Task Field Access', + +'LBL_EVENT_FIELD_ACCESS'=>'Event Field Access', +'LBL_VENDOR_FIELD_ACCESS'=>'Vendor Field Access', +'LBL_PB_FIELD_ACCESS'=>'PriceBook Field Access', +'LBL_QUOTE_FIELD_ACCESS'=>'Quote Field Access', +'LBL_PO_FIELD_ACCESS'=>'Purchase Order Field Access', +'LBL_SO_FIELD_ACCESS'=>'Sales Order Access', +'LBL_INVOICE_FIELD_ACCESS'=>'Invoice Field Access', + +//given for calendar color for an user user +'LBL_COLOR'=>'Color in Calendar', +//added for activity view in home page +'LBL_ACTIVITY_VIEW'=>'Default Activity View', +//Added to change Home page order +'LBL_HOMEPAGE_ORDER_UPDATE'=>'Update Home Page Block Order', +'LBL_HOMEPAGE_ID'=>'Block Order', +'ERR_INVALID_USER'=>'Invalid access--Please call from My Accounts', +'ALVT'=>'Top Accounts', +'PLVT'=>'Top Potentials', +'QLTQ'=>'Top Quotes', +'CVLVT'=>'Key Metrics', +'HLT'=>'Top Trouble Tickets', +'OLV'=>'Upcoming & Pending Activities', +'GRT'=>'My Group Allocation', +'OLTSO'=>'Top Sales Orders', +'ILTI'=>'Top Invoices', +'HDB'=>'Home Page Dashboard', +'OLTPO'=>'Top Purchase Orders', +'LTFAQ'=>'My Recent FAQs', +'UA'=>'Upcoming Activities', +'PA'=>'Pending Activities', + +//Added for 5.0 alpha +'LBL_GROUP_NAME_ERROR'=>'Group Name already exists!', +'MNL'=>'My New Leads', +'LBL_LEAD_VIEW'=>'Default Leads View', +'LBL_TAG_CLOUD'=>'Tag Cloud', +'LBL_LIST_TOOLS'=>'Tools', +'LBL_STATISTICS'=>'Statistics', +'LBL_TOTAL'=>'Total :', +'LBL_OTHERS'=>'Others :', +'LBL_USERS'=>'User(s)', +'LBL_USER_LOGIN_ROLE'=>'User Login & Role', +'LBL_USER_MORE_INFN'=>'More Information', +'LBL_USER_ADDR_INFN'=>'Address Information', +'LBL_USER_IMAGE'=>'User Image', +'LBL_USR'=>'Users', + +'LBL_MY'=>'My', +'LBL_MY_DEFAULTS'=>'My Defaults', +'LBL_MY_DESG'=>'My Designation & Contact Details', +'LBL_MY_ADDR'=>'My Postal Address', +'LBL_MY_PHOTO'=>'My Photo', +'LBL_CHANGE_PHOTO'=>'Change Photo...', +'LBL_CHANGE'=>'Change', + + +//Added for Access Privileges + +'LBL_GLOBAL_FIELDS_MANAGER'=>'Global Fields Manager', +'LBL_GLOBAL_ACCESS_PRIVILEGES'=>'Organization-level Sharing Rules', +'LBL_CUSTOM_ACCESS_PRIVILEGES'=>'Custom Sharing Rules', +'LBL_BOTH'=>'Both', +'LBL_VIEW'=>'View', +'LBL_RECALCULATE_BUTTON'=>'Recalculate', +'LBL_ADD_PRIVILEGES_BUTTON'=>'Add Privileges', +'LBL_CUSTOM_ACCESS_MESG'=>'No Custom Access Rules defined .', +'LBL_CREATE_RULE_MESG'=>'to create a new Rule', +'LBL_SELECT_SCREEN'=>'Select the Screen / Module :', +'LBL_FIELDS_AVLBL'=>'Fields Available in', +'LBL_FIELDS_SELECT_DESELECT'=>'Fields to be shown', +'LBL_ROLE_TO_BE_DELETED'=>'Role to be Deleted', +'LBL_TRANSFER_USER_ROLE'=>'Transfer Users to Role', +'LBL_DELETE_ROLE'=>'Delete Role', +'LBL_MORE_INFORMATION'=>'More Information', +'LBL_USERLOGIN_ROLE'=>'User Login & Role', +'LBL_USER_IMAGE_INFORMATION'=>'User Photograph', + +//Added for 5.0 for all fields +'Role'=>'Role', +'Email'=>'Email', +'Admin'=>'Admin', +'User Name'=>'User Name', +'First Name'=>'First Name', +'Last Name'=>'Last Name', +'Status'=>'Status', +'Default Activity View'=>'Default Calendar View', +'Default Lead View'=>'Default Lead View', +'Currency'=>'Currency', +'Title'=>'Title', +'Office Phone'=>'Office Phone', +'Department'=>'Department', +'Mobile'=>'Mobile', +'Reports To'=>'Reports To', +'Other Phone'=>'Other Phone', +'Other Email'=>'Other Email', +'Fax'=>'Fax', +'Yahoo id'=>'Yahoo id', +'Home Phone'=>'Home Phone', +'User Image'=>'Upload Photograph', +'Date Format'=>'Date Format', +'Tag Cloud'=>'Tag Cloud', +'Signature'=>'Signature', +'Documents'=>'Notes', +'Street Address'=>'Street Address', +'City'=>'City', +'State'=>'State', +'Postal Code'=>'Postal Code', +'Country'=>'Country', +'Password'=>'Password', +'Confirm Password'=>'Confirm Password', +'LBL_SHOWN'=>'Shown', +'LBL_HIDDEN'=>'Hidden', +'LBL_SHOW'=>'Show', +'LBL_HIDE'=>'Hide', +'LBL_HOME_PAGE_COMP'=>'Home Page Components', +'LBL_LOGIN_HISTORY'=>'Login History', +'LBL_USERDETAIL_INFO'=>'Viewing details about the user', +'LBL_DELETE_GROUP'=>'Delete Group', +'LBL_DELETE_GROUPNAME'=>'Group to be Deleted', +'LBL_TRANSFER_GROUP'=>'Transfer Ownership to: ', +'LBL_DELETE_USER'=>'User to be Deleted', +'LBL_TRANSFER_USER'=>'Transfer Ownership to User', +'LBL_DELETE_PROFILE'=>'Delete Profile', +'LBL_TRANSFER_ROLES_TO_PROFILE'=>'Transfer Roles to Profile', +'LBL_PROFILE_TO_BE_DELETED'=>'Profile to be Deteted', + +//Added for disabling window Recalculate + +'LBL_RECALC_MSG'=>'Are you sure, you wish to Recalculate Sharing Access?', +'LBL_YES'=>'Yes', +'LBL_NO'=>'No', + +'LBL_MANDATORY_MSG'=>'Mandatory Fields', +'LBL_DISABLE_FIELD_MSG'=>'Fields Disabled from Global Field Access Settings', + +//Added for About Us + +'LBL_CONTACT_US'=>'Contact Us', +'LBL_READ_LICENSE'=>'Read License', +'LBL_VERSION'=>'Version', +'LBL_TEAM'=>'Team', +'LBL_CREDITS'=>'Credits', +'LBL_THIRD_PARTY'=>'Third Party Packages', +'LBL_COMMUNITY'=>'And vtiger Community', + +'LBL_ASSIGN_ROLE'=>'Assign Role', + +//Moved from Settings to here for Webmail client integration (for 5.0.3 release) + +'LBL_ADD_MAIL_ACCOUNT'=>'Add Mail Account', +'LBL_NEW_MAIL_ACCOUNT_TITLE'=>'New Mail Account [Alt+M]', +'LBL_NEW_MAIL_ACCOUNT_KEY'=>'M', +'LBL_NEW_MAIL_ACCOUNT_LABEL'=>'New Mail Account', +'LBL_GENERAL_INFO'=>'General Information', +'LBL_DISPLAY_NAME'=>'Display Name', +'LBL_MAIL_PROTOCOL'=>'Mail Protocol', +'LBL_LIST_PASSWORD'=>'Password', +'LBL_MAIL_SERVER_NAME'=>'Mail Server Name or IP', +'LBL_INCOME_SERVER_SETTINGS'=>'Incoming Server', +'LBL_TEST_SETTINGS'=>'Test my account setting immediately', +'LBL_TEST_BUTTON_TITLE'=>'Test my account now! [Alt+T]', +'LBL_TEST_BUTTON_KEY'=>'T', +'LBL_TEST_BUTTON_LABEL'=>'Test my account now!', +'LBL_DEFAULT'=>'Default', +'LBL_IMAP2'=>'IMAP2', +'LBL_IMAP4'=>'IMAP4', +'LBL_POP'=>'POP', +'LBL_IMAP'=>'IMAP', +'LBL_MAIL_DISCLAIM'=>'Items marked with * are required', +'LBL_SSL_OPTIONS'=>'SSL Options', +'LBL_TLS'=>'TLS', +'LBL_NO_TLS'=>'No TLS', +'LBL_CERT_VAL'=>'Certificate Validations', +'LBL_INT_MAILER'=>'Use Internal Mailer?', +'LBL_INT_MAILER_USE'=>'Yes', +'LBL_INT_MAILER_NOUSE'=>'No', +'LBL_VAL_SSL_CERT'=>'Validate SSL Cert', +'LBL_DONOT_VAL_SSL_CERT'=>'Do Not Validate SSL Cert', +'LBL_WEB_MAIL_CONFIG'=>'Web Mail Configuration', +'LBL_CONFIGURE_WEB_MAIL'=>' - Configure Web Mail', +'LBL_LIST_MAIL_ACCOUNT'=>' List Mail Account', +'LBL_MY_MAIL_SERVER_DET'=>'My Incoming Mail Server Details', +'LBL_MY_DETAILS'=>'My Details', +'LBL_EMAIL_ID'=>'Email ID', +'LBL_EMAIL_ADDRESS'=>'Email', +'LBL_NAME_EXAMPLE'=>'(example : John Fenner)', +'LBL_EMAIL_EXAMPLE'=>'(example : johnfenner@xyz.com)', +'LBL_REFRESH_TIMEOUT'=>'Refresh Timeout', +'LBL_1_MIN'=>'1 minute', +'LBL_2_MIN'=>'2 minutes', +'LBL_3_MIN'=>'3 minutes', +'LBL_4_MIN'=>'4 minutes', +'LBL_5_MIN'=>'5 minutes', +'LBL_EMAILS_PER_PAGE'=>'Email per Page', +// Added for 5.0.3 + +'LBL_ENTER_PROFILE'=>'Enter The Profile Name', +'TITLE_USER_DOCUMENT'=>'Untitled Document', +'TITLE_VTIGER_CRM_5'=>'vtiger CRM 5 - Free, Commercial grade Open Source CRM', +'ROLE_DRAG_ERR_MSG'=>'You cannot move a Parent Node under a Child Node', + +'LBL_NOTIFICATION_ACTIVITY'=>'Notification Activity', +'LBL_NOTIFICATION_EMAIL_INFO'=>'Notification Email Information', +'LBL_GOTO_LISTVIEW_BUTTON'=>'Goto ListView', + +// Added/Updated for vtiger CRM 5.0.4 + +'LBL_SSL' => 'SSL', +//Added to fix the issue #4081 +'LBL_USERNAME_EXIST' => 'A User with the specified name Already Exists!', +'LBL_UNAUTHORIZED_ACCESS' => 'Unauthorized access to user administration', +//Added to provide User based TagCloud +'LBL_TAGCLOUD_DISPLAY'=>'Tag Cloud Display', +'INTERNAL_MAIL_COMPOSER'=>'Internal Mail Composer', + +// Added for 5.0.4 to Support Email notication on User Creation +'User Login Details'=>'User Login Details', +'LBL_TO_LOGIN' => 'to Login', + +// Added after 5.0.4 GA + +'LBL_USER_ADV_OPTIONS'=>'User Advanced Options', +'Reminder Interval'=>'Reminder Interval', +'Webservice Access Key'=>'Access Key', + +//user-group fixes +'LBL_GROUPNAME_EXIST' => 'A Group with the specified name Already Exists!', +'LBL_PROFILENAME_EXIST' => 'A Profile with the specified name Already Exists!', +); + +?> diff --git a/oss/vtiger/trunk/modules/Users/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Users/language/zh_cn.lang.php new file mode 100644 index 00000000..66a47a55 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/language/zh_cn.lang.php @@ -0,0 +1,671 @@ + '用户', + 'LBL_MODULE_TITLE' => '用户: 首页', + 'LBL_SEARCH_FORM_TITLE' => '搜寻用户', + 'LBL_LIST_FORM_TITLE' => '用户列表', + 'LBL_NEW_FORM_TITLE' => '新增用户', + 'LBL_CREATE_NEW_USER' => '建立用户', + 'LBL_LOGIN' => '登入', + 'LBL_USER_ROLE' => '职位', + 'LBL_LIST_NAME' => '姓名', + 'LBL_LIST_LAST_NAME' => '名', + 'LBL_LIST_USER_NAME' => '用户名', + 'LBL_LIST_DEPARTMENT' => '部门', + 'LBL_LIST_EMAIL' => '电子邮件', + 'LBL_LIST_PRIMARY_PHONE' => '主要电话', + 'LBL_LIST_ADMIN' => '管理员', + 'LBL_LIST_CONFIRM_PASSWORD' => '确认密码', + 'LBL_LIST_USER_NAME_ROLE' => '账号、名称与角色', + 'LBL_LIST_SELECT' => '选择', + 'LBL_LIST_PHONE' => '电话', + 'LBL_LIST_NO' => '#', + +'LBL_ADMINS' => '管理', + 'LBL_STD_USERS' => '标准用户', + + 'UserName' => '账号', + 'Name' => '名称', + 'Tools' => '工具', + + +//added for patch2 + 'LBL_GROUP' => '群组', + 'LBL_CURRENCY_NAME' => '货币', + + 'LBL_NEW_USER_BUTTON_TITLE' => '新增用户 [Alt+N]', + 'LBL_NEW_USER_BUTTON_LABEL' => '新增用户', + 'LBL_NEW_USER_BUTTON_KEY' => 'N', + 'LBL_DATE_FORMAT' => '日期格式', + +'LBL_ERROR' => '错误:', + 'LBL_PASSWORD' => '密码:', + 'LBL_USER_NAME' => '用户名:', + 'LBL_CRM_ID' => 'CRM 代号', + 'LBL_FIRST_NAME' => '姓名:', + 'LBL_LAST_NAME' => '姓氏:', + 'LBL_YAHOO_ID' => 'Yahoo账号:', + 'LBL_THEME' => '样式:', + 'LBL_LANGUAGE' => '语言:', + 'LBL_ADMIN' => '管理员:', + 'LBL_OFFICE_PHONE' => '办公室电话:', + 'LBL_REPORTS_TO' => '报告给:', + 'LBL_OTHER_PHONE' => '其它:', + 'LBL_OTHER_EMAIL' => '其它电子邮件:', + 'LBL_DEPARTMENT' => '部门:', + 'LBL_STATUS' => '身份:', + 'LBL_TITLE' => '标题:', +'LBL_ANY_PHONE' => '其它电话:', + 'LBL_ANY_EMAIL' => '其它邮件:', + 'LBL_ADDRESS' => '地址:', + 'LBL_CITY' => '乡镇市区:', + 'LBL_STATE' => '市(县):', + 'LBL_POSTAL_CODE' => '邮政编码:', + 'LBL_COUNTRY' => '省(市/自治区):', + 'LBL_USER_SETTINGS' => '用户设定', + 'LBL_USER_INFORMATION' => '用户信息', + 'LBL_MOBILE_PHONE' => '手机:', + 'LBL_OTHER' => '其它:', + 'LBL_FAX' => '传真:', + 'LBL_EMAIL' => '电子邮件:', + 'LBL_HOME_PHONE' => '家用电话:', + 'LBL_ADDRESS_INFORMATION' => '地址信息', + 'LBL_CAL_HRFORMAT' => '行事历时间格式', + 'LBL_CAL_DURATION' => '一周开始日', + 'LBL_PRIMARY_ADDRESS' => '主要地址:', + +'LBL_CHANGE_PASSWORD_BUTTON_TITLE' => '变更密码 [Alt+P]', + 'LBL_CHANGE_PASSWORD_BUTTON_KEY' => 'P', + 'LBL_CHANGE_PASSWORD_BUTTON_LABEL' => '变更密码', + 'LBL_LOGIN_BUTTON_TITLE' => '登入 [Alt+L]', + 'LBL_LOGIN_BUTTON_KEY' => 'L', + 'LBL_LOGIN_BUTTON_LABEL' => '登入', + 'LBL_LOGIN_HISTORY_BUTTON_TITLE' => '登入记录 [Alt+H]', + 'LBL_LOGIN_HISTORY_BUTTON_KEY' => 'H', + 'LBL_LOGIN_HISTORY_BUTTON_LABEL' => '登入记录', + 'LBL_LOGIN_HISTORY_TITLE' => '用户: 登入记录', + 'LBL_RESET_PREFERENCES' => '重新设定默认值', + +'LBL_CHANGE_PASSWORD' => '变更密码', + 'LBL_OLD_PASSWORD' => '旧密码:', + 'LBL_NEW_PASSWORD' => '新密码:', + 'LBL_CONFIRM_PASSWORD' => '再确认新密码:', + 'ERR_ENTER_OLD_PASSWORD' => '请输入您的旧密码.', + 'ERR_ENTER_NEW_PASSWORD' => '请输入您的新密码.', + 'ERR_ENTER_CONFIRMATION_PASSWORD' => '请再次输入您的新密码.', + 'ERR_REENTER_PASSWORDS' => '请重新输入密码,新密码与再确认新密码的值不符.', + 'ERR_INVALID_PASSWORD' => '您必须正确输入用户名及密码.', + 'ERR_PASSWORD_CHANGE_FAILED_1' => '用户密码变更失败: ', + 'ERR_PASSWORD_CHANGE_FAILED_2' => ' 失败. 新密码必须要设定.', + 'ERR_PASSWORD_INCORRECT_OLD' => '不正确的旧密码: $this->user_name. 请再重新输入.', + 'ERR_USER_NAME_EXISTS_1' => '用户名 ', + 'ERR_USER_NAME_EXISTS_2' => ' 已经存在. 不予许用户名重复.
    请换一个不同的用户名.', + 'ERR_LAST_ADMIN_1' => '用户名 ', + 'ERR_LAST_ADMIN_2' => ' 最后一位用户成为管理员.
    请检查管理员设定.', + 'ERR_DELETE_RECORD' => '必须指定一笔记录编号才能删除客户', + +// Additional Fields for i18n --- Release vtigerCRM 3.2 Patch 2 +// Users--listroles.php , createrole.php , ListPermissions.php , editpermissions.php + + 'LBL_ROLES' => '职位', + 'LBL_ROLES_SUBORDINATES' => '角色与附属', + + 'LBL_CREATE_NEW_ROLE' => '建立新的职位', + 'LBL_INDICATES_REQUIRED_FIELD' => '指定必须字段', + 'LBL_NEW_ROLE' => '新增职位', + 'LBL_PARENT_ROLE' => '该职位的上司', + + 'LBL_LIST_ROLES' => '列出职位', + 'LBL_ENTITY_LEVEL_PERMISSIONS' => '实体层级权限', + 'LBL_ENTITY' => '实体', + 'LBL_CREATE_EDIT' => '建立/编辑', + 'LBL_DELETE' => '删除', + 'LBL_LEADS' => '潜在客户', + 'LBL_ACCOUNTS' => '客户', + 'LBL_CONTACTS' => '联络人', + 'LBL_OPPURTUNITIES' => '潜在案件', + 'LBL_TASKS' => '任务', + 'LBL_CASES' => '案件', + 'LBL_EMAILS' => '电子邮件', + 'LBL_NOTES' => '备忘录', + 'LBL_MEETINGS' => '会议', + 'LBL_CALLS' => '电话记录', + 'LBL_IMPORT_PERMISSIONS' => '汇入权限', + 'LBL_IMPORT_LEADS' => '汇入潜在客户', + 'LBL_IMPORT_ACCOUNTS' => '汇入客户', + 'LBL_IMPORT_CONTACTS' => '汇入联络人', + 'LBL_IMPORT_OPPURTUNITIES' => '汇入潜在案件', + + 'LBL_ROLE_DETAILS' => '职位细节', +//added for vtigercrm4 rc + 'LBL_FILE' => '文件名称', + 'LBL_FILE_TYPE' => '档案类型', + 'LBL_UPLOAD' => '上传档案', + 'LBL_ATTACH_FILE' => '附加邮件合并样版', + 'LBL_EMAIL_TEMPLATES' => '电子邮件样版', + 'LBL_TEMPLATE_HEADER' => '样板', + 'LBL_TEMPLATE_DETAILS' => '样板细节', + 'LBL_EDIT_TEMPLATE' => '编辑样板', + 'LBL_TEMPLATE_FILE' => '样板档案', + 'LBL_EMAIL_TEMPLATES_LIST' => '通讯样板 > 邮件样板', + 'LBL_MAILMERGE_TEMPLATES_LIST' => '> 通讯样板 > 邮件合并样板', + 'LBL_MAILMERGE_TEMPLATES_ATTACHMENT' => '> 通讯样板 > 附加邮件合并样板', + 'LBL_DOWNLOAD_NOW' => '现在下载', + 'LBL_DOWNLOAD' => '下载', + 'LBL_SELECT_MODULE' => '选择模块', + 'LBL_MERGE_FILE' => '档案:', + 'LBL_MERGE_MSG' => '选择要使用这个样板的模块', + 'LBL_MERGE_FIELDS' => '合并字段', + 'LBL_COPY_PASTE' => '复制与贴上', + 'LNK_GO_TO_TOP' => '回到页首', + 'LNK_SAMPLE_EMAIL' => '检视范例信件', + 'LBL_COLON' => ':', + 'LBL_EMAIL_TEMPLATE' => '电子邮件样版', + 'LBL_NEW_TEMPLATE' => '新增样版', + 'LBL_ADD_TEMPLATE' => '新增样板', + 'LBL_USE_MERGE_FIELDS_TO_EMAIL_CONTENT' => '使用您的个人化样版. 您可以新增替代文字去合并任何字段.', + 'LBL_AVAILABLE_MERGE_FIELDS' => '目前可以的合并字段', + 'LBL_SELECT_FIELD_TYPE' => '选择字段类别', + 'LBL_SELECT_FIELD' => '选择字段', + 'LBL_MERGE_FIELD_VALUE' => '复制合并字段值', + 'LBL_ACCOUNT_FIELDS' => '客户字段', + 'LBL_CONTACT_FIELDS' => '联络人字段', + 'LBL_LEAD_FIELDS' => '潜在客户字段', + 'LBL_COPY_AND_PASTE_MERGE_FIELD' => '复制并且贴上合并的字段值到您的样版里.', + 'LBL_EMAIL_TEMPLATE_INFORMATION' => '电子邮件样版信息:', + 'LBL_FOLDER' => '资料夹:', + 'LBL_PERSONAL' => '个人', + 'LBL_PUBLIC' => '公开', + 'LBL_TEMPLATE_NAME' => '样版名称:', + 'LBL_SUBJECT' => '标题', + 'LBL_BODY' => '电子邮件内容', + 'LBL_TEMPLATE_TOOLS' => '工具', + 'LBL_TEMPLATE_PUBLIC' => '公开', + 'LBL_TEMPLATE_PRIVATE' => '私人', + 'LBL_TEMPLATE_SUBJECT' => '邮件主旨', + 'LBL_TEMPLATE_MESSAGE' => '邮件内容', + 'LBL_VIEWING' => '检视中', + 'LBL_PROPERTIES' => '属性', + + + +// Added fields in createnewgroup.php +'LBL_CREATE_NEW_GROUP' => '建立新的群组', + 'LBL_NEW_GROUP' => '新增群组', + 'LBL_EDIT_GROUP' => '编辑寻组', + 'LBL_GROUP_NAME' => '群组名称', + 'LBL_GROUP_DETAILS' => '群组细节', + 'LBL_MEMBER' => '成员', + 'LBL_MEMBER_AVLBL' => '现有会员', + 'LBL_MEMBER_SELECTED' => '选择的会员', + 'LBL_DESCRIPTION' => '描述', + 'LBL_GROUP_MESG1' => '如果定义了比较复杂的存取权限,透过群组指派会比较有弹性。您可以透过群组合并多笔角色、用户与数据等。', + 'LBL_GROUP_MESG2' => '要新增时,选择左边的会员数据后点选 "》" 按钮', + 'LBL_GROUP_MESG3' => '要移除时,选择右边的会员数据后点选 "《" 按钮', + + +// Added fields in detailViewmailtemplate.html,listgroupmembers.php,listgroups.php + 'LBL_DETAIL_VIEW_OF_EMAIL_TEMPLATE' => '观看电子邮件样版细节', + 'LBL_DETAIL_VIEW' => '细节', + 'LBL_EDIT_VIEW' => '编辑', + 'LBL_EDITING' => '编辑用户', + + 'LBL_GROUP_MEMBERS_LIST' => '群组会员列表', + 'LBL_GROUPS' => '群组', + 'LBL_MY_GROUPS' => '我的群组', + 'LBL_ADD_GROUP_BUTTON' => '新增群组', + 'LBL_WORD_TEMPLATES' => '电子邮件合并样版', + 'LBL_NEW_WORD_TEMPLATE' => '新增样版', + 'LBL_EMAIL_TEMPLATE_DESC' => '管理活动与大量邮件使用的邮件样板', + 'LBL_NAME' => '名称:', + +// Added fields in TabCustomise.php,html and UpdateTab.php,html + 'LBL_CUSTOMISE_TABS' => '自订表格', + 'LBL_CHOOSE_TABS' => '选择表格', + 'LBL_AVAILABLE_TABS' => '现有表格', + 'LBL_SELECTED_TABS' => '已选表格', + 'LBL_USER' => '用户', + 'LBL_TAB_MENU_UPDATED' => '表格清单已更新! ', + 'LBL_TO_VIEW_CHANGES' => ' 观看相关的变更', + +// Added to change homepage order + 'LBL_CHANGE_HOMEPAGE_LABEL' => '网页顺序', + 'LBL_CHANGE_HOMEPAGE_TITLE' => '网页', + +// Added fields in binaryfilelist.php + 'LBL_OERATION' => '作业', + +// Added fields in CreateProfile.php + 'LBL_PROFILE_NAME' => '建立新的权限名称:', + 'LBL_NEW_PROFILE' => '新增权限名称', + 'LBL_NEW_PROFILE_NAME' => '权限名称', + 'LBL_PARENT_PROFILE' => '继承权限', + 'LBL_BASIC_PROFILE_DETAILS' => '权限基本细节', + 'LBL_STEP_1_2' => '步骤1之2', + 'LBL_STEP_2_2' => '步骤2之2', + 'LBL_STEP' => '步骤', + 'LBL_SELECT_BASE_PROFILE' => '选择基础权限', + 'LBL_PROFILE_PRIVILEGES' => '权限', + 'LBL_GLOBAL_PRIVILEGES' => '全域权限', + 'LBL_TAB_PRIVILEGES' => '标签权限', + 'LBL_FIELD_PRIVILEGES' => '字段权限', + 'LBL_STANDARD_PRIVILEGES' => '标准权限', + 'LBL_UTILITY_PRIVILEGES' => '工具权限', + 'LBL_UTILITIES' => '工具', + 'LBL_BASE_PROFILE_MESG' => '我要建立一个基础权限名称并且编辑权限 (建议)', + 'LBL_BASE_PROFILE' => '基础权限名称:', + 'LBL_OR' => '或', + 'LBL_BASE_PROFILE_MESG_ADV' => '我要重新选择权限 (进阶用户)', + 'LBL_FOR' => '于', + 'LBL_GLOBAL_MESG_OPTION' => '选择下面选项来修改全域权限', + 'LBL_VIEW_ALL' => '检视全部', + 'LBL_EDIT_ALL' => '编辑全部', + 'LBL_ALLOW' => '允许', + 'LBL_MESG_VIEW' => '检视所有信息 / 模块', + 'LBL_MESG_EDIT' => '编辑所有信息 / 模块', + 'LBL_STD_MESG_OPTION' => '选择允许的标准操作', + 'LBL_TAB_MESG_OPTION' => '选择允许的卷标/模块', + 'LBL_UTILITY_MESG_OPTION' => '选择允许的工具', + 'LBL_FIELD_MESG_OPTION' => '选择允许的字段', + 'LBL_FINISH_BUTTON' => '完成', + 'LBL_PROFILE_DETAIL_VIEW' => '权限细节', + 'LBL_PROFILE_MESG' => '检视存取权限于', + 'LBL_PROFILE_M' => '权限', + 'LBL_DEFINE_PRIV_FOR' => '定义权限于', + 'LBL_USE_OPTION_TO_SET_PRIV' => '使用下面选项设定权限', + 'LBL_SUPER_USER_PRIV' => '超级用户权限', + 'LBL_SET_PRIV_FOR_EACH_MODULE' => '设定每个模块的权限', + 'LBL_FIELDS_AND_TOOLS_SETTINGS' => '字段与工具设定', + 'LBL_SHOW_FIELDS' => '显示字段', + 'LBL_TOOLS_TO_BE_SHOWN' => '要显示的工具', + 'LBL_WELCOME_PROFILE_CREATE' => '欢迎使用权限资料精灵', + 'LBL_SELECT_CHOICE_NEW_PROFILE' => '选择您希望使用的项目来建立新的权限名称', + 'LBL_ADD_CUSTOM_RULE' => '新增自订权限规则', + 'LBL_EDIT_CUSTOM_RULE' => '编辑自订权限规则', + 'LBL_CLOSE' => '关闭', + 'LBL_SELECT_ENTITY' => '从下面选择一个项目', + 'LBL_CAN_BE_ACCESSED_BY' => '可以存取于', + 'LBL_PERMISSIONS' => '权限', + 'LBL_ACCESS_RIGHTS_FOR_MODULES' => '相关模块存取权限', + 'LBL_RULE_CONSTRUCTION' => '显示规则架构', + 'LBL_ADD_RULE' => '新增规则', + 'LBL_RELATED_MODULE_RIGHTS' => '相关模块权限', + 'LBL_IN_PERMISSION' => '在权限', + +//Added fields in createrole.php + 'LBL_HDR_ROLE_NAME' => '建立新的职位:', + 'LBL_TITLE_ROLE_NAME' => '新增职位', + 'LBL_ROLE_NAME' => '职位名称', + 'LBL_ROLE_PROFILE_NAME' => '结合权限名称', + 'LBL_SPECIFY_ROLE_NAME' => '指定新角色名称:', + 'LBL_ASSIGN_PROFILE' => '指定权限名称', + 'LBL_PROFILE_SELECT_TEXT' => '选择下面权限名称后点选指定按钮', + 'LBL_PROFILES_AVLBL' => '可用权限名称', + 'LBL_ASSIGN_PROFILES' => '指定的权限名称', + 'LBL_REPORTS_TO_ROLE' => '回报给角色', + 'LBL_ASSOCIATED_PROFILES' => '相关权限名称:', + 'LBL_ASSOCIATED_USERS' => '相关用户:', + + +//Added fields in OrgSharingDetailsView.php +'LBL_ORG_SHARING_PRIVILEGES' => '组织单位享有之特别权限', + 'LBL_EDIT_PERMISSIONS' => '编辑权限', + 'LBL_SAVE_PERMISSIONS' => '储存权限', + 'LBL_READ_ONLY' => '公众: 只能读', + 'LBL_EDIT_CREATE_ONLY' => '公众: 读, 建立/编辑', + 'LBL_READ_CREATE_EDIT_DEL' => '公众: 读, 建立/编辑, 删除', + 'LBL_PRIVATE' => '私人', + +//Added fields in listnotificationschedulers.php +'LBL_HDR_EMAIL_SCHDS' => '用户 : 电子邮件通知', + 'LBL_EMAIL_SCHDS_DESC' => '当相应事件已经发生时,下列是被自动开动的通知的目录.', + 'LBL_ACTIVE' => '启用', + 'LBL_INACTIVE' => '停用', + 'LBL_NOTIFICATION' => '通知', + 'LBL_DESCRIPTION'=>'描述', + 'LBL_TASK_NOTIFICATION' => '延迟任务通知', + 'LBL_TASK_NOTIFICATION_DESCRITPION' => '当任务延迟24小时后,执行通知', + 'LBL_MANY_TICKETS' => '当有太多的记事签时,执行通知', + 'LBL_MANY_TICKETS_DESCRIPTION' => '当同一个实体发出太多的记事签时,执行通知', + 'LBL_PENDING_TICKETS' => '未决定之记事签通知', + 'LBL_TICKETS_DESCRIPTION' => '通知注意,未决定之记事签', + 'LBL_START_NOTIFICATION' => '支持开始通知', + 'LBL_START_DESCRIPTION' => '声明通知 支持/服务', + 'LBL_BIG_DEAL' => '折扣通知', + 'LBL_BIG_DEAL_DESCRIPTION' => '重要交易,执行通知', + 'LBL_SUPPORT_NOTICIATION' => '支持结束通知', + 'LBL_SUPPORT_DESCRIPTION' => '当支持结束时,执行通知', + 'LBL_BUTTON_UPDATE' => '更新', + 'LBL_MODULENAMES' => '模块', + +//Added fields in ListFieldPermissions.html +'LBL_FIELD_PERMISSION_FIELD_NAME' => '字段名称', + 'LBL_FIELD_PERMISSION_VISIBLE' => '显示', + 'LBL_FIELD_PERMISSIOM_TABLE_HEADER' => '标准字段', + 'LBL_FIELD_LEVEL_ACCESS' => '字段层级存取', + +//Added fields after 4.0.1 + 'LBL_SIGNATURE' => '签名', + +//Added for Event Reminder 4.2 Alpha release +'LBL_ACTIVITY_NOTIFICATION' => '事件提醒通知', + 'LBL_ACTIVITY_REMINDER_DESCRIPTION' => '基于提醒设定在事件发生前通知', + 'LBL_MESSAGE' => '信件', + +//Added for Global Privileges + +'Public: Read Only' => '公开:只读', + 'Public: Read, Create/Edit' => '公开:读取、建立/编辑', + 'Public: Read, Create/Edit, Delete' => '公开:读取、建立/编辑、删除', + 'Private' => '私人', + 'Hide Details' => '隐藏细节', + 'Hide Details and Add Events' => '隐藏细节与新增事件', + 'Show Details' => '显示细节', + 'Show Details and Add Events' => '显示细节与新增事件', + +'LBL_USR_CANNOT_ACCESS' => '用户无法存取其它账号', + 'LBL_USR_CAN_ACCESS' => '用户可以', + 'LBL_USR_OTHERS' => '其它用户', + +'Read Only ' => '只读', + 'Read, Create/Edit, Delete ' => '读取、建立/编辑、删除', + 'Read, Create/Edit ' => '读取、建立/编辑', + 'Read/Write' => '读取/写入', + 'LBL_GO_TO_TOP' => '回到页首', + 'LNK_CLICK_HERE' => '点选这里', + 'LBL_RULE_NO' => '规则编号', + 'LBL_CAN_BE_ACCESSED' => '可以存取者', + 'LBL_PRIVILEGES' => '权限', + 'LBL_OF' => '于', + + +//Added for 4.2GA support for mail server integration +'LBL_ADD_MAILSERVER_BUTTON_TITLE' => '新增邮件服务器', + 'LBL_ADD_MAILSERVER_BUTTON_KEY' => 'M', + 'LBL_ADD_MAILSERVER_BUTTON_LABEL' => '新增邮件服务器', + +'LBL_LIST_MAILSERVER_BUTTON_TITLE' => '邮件服务器列表', + 'LBL_LIST_MAILSERVER_BUTTON_KEY' => 'L', + 'LBL_LIST_MAILSERVER_BUTTON_LABEL' => '邮件服务器列表', +//added for inventory terms and conditions +'INV_TANDC' => '期限与条款', + 'INV_TERMSANDCONDITIONS' => '库存期限与条款', + 'LBL_INV_TERMSANDCONDITIONS' => '库存管理', + + +'INVENTORYNOTIFICATION' => '库存通知', + 'LBL_INVENTORY_NOTIFICATIONS' => '编辑库存通知邮件', + 'LBL_INV_NOT_DESC' => '下面是提醒通知的列表,用来在手动建立报价单、销售订单与发票时寄送给产品处理者,包括需求与目前数量等信息', + + 'InvoiceNotification' => '在建立发票时提醒产品库存', + 'InvoiceNotificationDescription' => '当产品库存低于安全存量时,提醒通知会发送给产品处理者', + + 'QuoteNotification' => '在建立报价单时提醒产品库存', + 'QuoteNotificationDescription' => '在报价单产生时,如果仓库中的产品库存低于报价单中提到的数量,这个提醒通知就会发出给相关人员', + + 'SalesOrderNotification' => '在建立销售订单时提醒产品库存', + 'SalesOrderNotificationDescription' => '在销售订单产生时,如果仓库中的产品库存低于销售订单中提到的数量,这个提醒通知就会发出给相关人员', + +//New addition for 4.2 GA + 'LBL_USER_FIELDS' => '用户字段', + 'LBL_NOTE_DO_NOT_REMOVE_INFO' => '注意:不要移除或是取代大括号 { } 中的数值', + +//Added for patch2 + 'LBL_FILE_INFORMATION' => '档案信息', + +//Added after pathc2 + 'LBL_LEAD_FIELD_ACCESS' => '潜在客户字段权限', + 'LBL_ACCOUNT_FIELD_ACCESS' => '客户字段权限', + 'LBL_CONTACT_FIELD_ACCESS' => '联络人字段权限', + 'LBL_OPPORTUNITY_FIELD_ACCESS' => '潜在机会字段权限', + 'LBL_HELPDESK_FIELD_ACCESS' => '服务台字段权限', + 'LBL_PRODUCT_FIELD_ACCESS' => '产品字段权限', + 'LBL_NOTE_FIELD_ACCESS' => '记事字段权限', + 'LBL_EMAIL_FIELD_ACCESS' => '电子邮件字段权限', + 'LBL_TASK_FIELD_ACCESS' => '任务字段权限', + 'LBL_EVENT_FIELD_ACCESS' => '事件字段权限', + 'LBL_VENDOR_FIELD_ACCESS' => '厂商字段权限', + 'LBL_PB_FIELD_ACCESS' => '价目表字段权限', + 'LBL_QUOTE_FIELD_ACCESS' => '报价单字段权限', + 'LBL_PO_FIELD_ACCESS' => '采购订单字段权限', + 'LBL_SO_FIELD_ACCESS' => '销售订单字段权限', + 'LBL_INVOICE_FIELD_ACCESS' => '发票字段权限', + +//given for calendar color for an user user + 'LBL_COLOR' => '行事历颜色', +//added for activity view in home page + 'LBL_ACTIVITY_VIEW' => '预设活动检视', +//Added to change Home page order +'LBL_HOMEPAGE_ORDER_UPDATE' => '更新网页区块顺序', + 'LBL_HOMEPAGE_ID' => '区块顺序', + 'ERR_INVALID_USER' => '操作错误 -- 请透过我的客户功能存取', + 'ALVT' => '最佳客户', + 'PLVT' => '最佳潜在机会', + 'QLTQ' => '最佳报价单', + 'CVLVT' => '关键点', + 'HLT' => '服务台最佳传票', + 'OLV' => '最热门活动', + 'GRT' => '最佳群组任务', + 'OLTSO' => '最佳销售订单', + 'ILTI' => '最佳发票', + 'HDB' => '统计图表', + 'OLTPO' => '顶部订购单', + 'LTFAQ' => '我的常见问题', +'UA'=>'近期活动', +'PA'=>'尚待进行的活动', + +//Added for 5.0 alpha +'LBL_GROUP_NAME_ERROR' => '群组名称重复!', + 'MNL' => '我的新准客户', + 'LBL_LEAD_VIEW' => '预设准客户检视方式', + 'LBL_TAG_CLOUD' => '标签区', + 'LBL_LIST_TOOLS' => '工具', + 'LBL_STATISTICS' => '统计', + 'LBL_TOTAL' => '总计:', + 'LBL_OTHERS' => '其它:', + 'LBL_USERS' => '个用户', + 'LBL_USER_LOGIN_ROLE' => '用户账号与角色', + 'LBL_USER_MORE_INFN' => '更多信息', + 'LBL_USER_ADDR_INFN' => '住址信息', + 'LBL_USER_IMAGE' => '用户照片', + 'LBL_USR' => '用户', + + 'LBL_MY' => '我的', + 'LBL_MY_DEFAULTS' => '我的默认值', + 'LBL_MY_DESG' => '我的署名与联络信息', + 'LBL_MY_ADDR' => '我的邮政信箱', + 'LBL_MY_PHOTO' => '我的照片', + 'LBL_CHANGE_PHOTO' => '修改照片...', + 'LBL_CHANGE' => '修改', + + +//Added for Access Privileges + + 'LBL_GLOBAL_FIELDS_MANAGER' => '全域字段管理', + 'LBL_GLOBAL_ACCESS_PRIVILEGES' => '全域存取权限', + 'LBL_CUSTOM_ACCESS_PRIVILEGES' => '自订存取权限', + 'LBL_BOTH' => '两者', + 'LBL_VIEW' => '检视', + 'LBL_RECALCULATE_BUTTON' => '重新计算', + 'LBL_ADD_PRIVILEGES_BUTTON' => '新增权限', + 'LBL_CUSTOM_ACCESS_MESG' => '未定义自订存取规则。', + 'LBL_CREATE_RULE_MESG' => '建立新规则', + 'LBL_SELECT_SCREEN' => '选择画面/模块:', + 'LBL_FIELDS_AVLBL' => '字段可用于', + 'LBL_FIELDS_SELECT_DESELECT' => '选择或取消选择要显示的字段', + 'LBL_ROLE_TO_BE_DELETED' => '要删除的角色', + 'LBL_TRANSFER_USER_ROLE' => '转换用户为角色', + 'LBL_DELETE_ROLE' => '删除角色', + 'LBL_MORE_INFORMATION' => '更多信息', + 'LBL_USERLOGIN_ROLE' => '用户账号与角色', + 'LBL_USER_IMAGE_INFORMATION' => '照片', + +//Added for 5.0 for all fields +'Role' => '角色', + 'Email' => '信箱', + 'Admin' => '管理', + 'User Name' => '账号', + 'First Name' => '姓名', + 'Last Name' => '姓氏', + 'Status' => '状态', + 'Default Activity View' => '预设检视待办事项', + 'Default Lead View' => '预设检视准客户', + 'Currency' => '货币', + 'Title' => '职称', + 'Office Phone' => '公司电话', + 'Department' => '部门', + 'Mobile' => '手机', + 'Reports To' => '负责业务', + 'Other Phone' => '其它电话', + 'Other Email' => '其它信箱', + 'Fax' => '传真', + 'Yahoo id' => 'Yahoo账号', + 'Home Phone' => '家里电话', + 'User Image' => '照片', + 'Date Format' => '日期格式', + 'Tag Cloud' => '常用关键词', + 'Signature' => '签名', +'Documents'=>'文件', + 'Street Address' => '街道巷弄', + 'City' => '乡镇市区', + 'State' => '市(县)', + 'Postal Code' => '邮政编码', + 'Country' => '省(市/自治区)', + 'Password' => '密码', + 'Confirm Password' => '密码确认', + 'LBL_SHOWN' => '显示', + 'LBL_HIDDEN' => '隐藏', + 'LBL_SHOW' => '显示', + 'LBL_HIDE' => '隐藏', + 'LBL_HOME_PAGE_COMP' => '首页组件', + 'LBL_LOGIN_HISTORY' => '登入纪录', + 'LBL_USERDETAIL_INFO' => '检视用户细节', + 'LBL_DELETE_GROUP' => '删除群组', + 'LBL_DELETE_GROUPNAME' => '要删除的群组', + 'LBL_TRANSFER_GROUP' => '转换负责人为:', + 'LBL_DELETE_USER' => '要删除的用户', + 'LBL_TRANSFER_USER' => '转换负责人到用户', + 'LBL_DELETE_PROFILE' => '删除权限名称', + 'LBL_TRANSFER_ROLES_TO_PROFILE' => '转换角色的权限名称', + 'LBL_PROFILE_TO_BE_DELETED' => '要删除的权限名称', + +//Added for disabling window Recalculate + + 'LBL_RECALC_MSG' => '您确定要重新计算共享权限?', + 'LBL_YES' => '是', + 'LBL_NO' => '否', + + 'LBL_MANDATORY_MSG' => '必填字段', + 'LBL_DISABLE_FIELD_MSG' => '这个字段在全域字段存取设定中停用了', + +//Added for About Us + + 'LBL_CONTACT_US' => '联络我们', + 'LBL_READ_LICENSE' => '阅读授权', + 'LBL_VERSION' => '版本', + 'LBL_TEAM' => '团队', + 'LBL_CREDITS' => '贡献', + 'LBL_THIRD_PARTY' => '第三方程式', + 'LBL_COMMUNITY' => '以及 vtiger 社群', + + 'LBL_ASSIGN_ROLE' => '指定角色', + +//Moved from Settings to here for Webmail client integration (for 5.0.3 release) + + 'LBL_ADD_MAIL_ACCOUNT' => '新增邮件账号', + 'LBL_NEW_MAIL_ACCOUNT_TITLE' => '新增邮件账号 [Alt+M]', + 'LBL_NEW_MAIL_ACCOUNT_KEY' => 'M', + 'LBL_NEW_MAIL_ACCOUNT_LABEL' => '新增邮件账号', + 'LBL_GENERAL_INFO' => '一般信息', + 'LBL_DISPLAY_NAME' => '显示名称', + 'LBL_MAIL_PROTOCOL' => '邮件协定', + 'LBL_LIST_PASSWORD' => '密码', + 'LBL_MAIL_SERVER_NAME' => '邮件服务器名称', + 'LBL_INCOME_SERVER_SETTINGS' => '收件服务器', + 'LBL_TEST_SETTINGS' => '立刻测试我的设定', + 'LBL_TEST_BUTTON_TITLE' => '测试我的设定![Alt+T]', + 'LBL_TEST_BUTTON_KEY' => 'T', + 'LBL_TEST_BUTTON_LABEL' => '测试我的设定!', + 'LBL_DEFAULT' => '预设', + 'LBL_IMAP2' => 'IMAP2', + 'LBL_IMAP4' => 'IMAP4', + 'LBL_POP' => 'POP', + 'LBL_IMAP' => 'IMAP', + 'LBL_MAIL_DISCLAIM' => '有 * 符号表示必填,标示 * * 表示完全支持', + 'LBL_SSL_OPTIONS' => 'SSL 选项', + 'LBL_TLS' => 'TLS', + 'LBL_NO_TLS' => 'No TLS', + 'LBL_CERT_VAL' => '验证执照', + 'LBL_INT_MAILER' => '使用内部邮件服务器?', + 'LBL_INT_MAILER_USE' => '是', + 'LBL_INT_MAILER_NOUSE' => '否', + 'LBL_VAL_SSL_CERT' => '验证 SSL 执照', + 'LBL_DONOT_VAL_SSL_CERT' => '不去验证 SSL 执照', + 'LBL_WEB_MAIL_CONFIG' => '网页邮件设定', + 'LBL_CONFIGURE_WEB_MAIL' => ' - 设定网页邮件', + 'LBL_LIST_MAIL_ACCOUNT' => '邮件账号列表', + 'LBL_MY_MAIL_SERVER_DET' => '我的邮件服务器细节', + 'LBL_MY_DETAILS' => '我的细节', + 'LBL_EMAIL_ID' => '信箱代号', + 'LBL_EMAIL_ADDRESS' => '电子邮件', + 'LBL_NAME_EXAMPLE' => '(例: John Fenner)', + 'LBL_EMAIL_EXAMPLE' => '(例: johnfenner@mailserver.com)', + 'LBL_REFRESH_TIMEOUT' => '重新整理频率', + 'LBL_1_MIN' => '1 分钟', + 'LBL_2_MIN' => '2 分钟', + 'LBL_3_MIN' => '3 分钟', + 'LBL_4_MIN' => '4 分钟', + 'LBL_5_MIN' => '5 分钟', + 'LBL_EMAILS_PER_PAGE' => '每页显示邮件数量', +// Added for 5.0.3 + +'LBL_ENTER_PROFILE'=>'输入概况', +'TITLE_USER_DOCUMENT'=>'没有文件名', +'TITLE_VTIGER_CRM_5'=>'vtiger CRM 5 - Free, Commercial grade Open Source CRM', +'ROLE_DRAG_ERR_MSG'=>'You cannot move a Parent Node under a Child Node', + +'LBL_NOTIFICATION_ACTIVITY'=>'活动通知', +'LBL_NOTIFICATION_EMAIL_INFO'=>'通知电子邮件信息', +'LBL_GOTO_LISTVIEW_BUTTON'=>'转到列表', +// Added/Updated for vtiger CRM 5.0.4 +'LBL_SSL' => 'SSL', +//Added to fix the issue #4081 +'LBL_USERNAME_EXIST' => '指定名称的用户已经存在! ', +'LBL_UNAUTHORIZED_ACCESS' => '未经授权访问用户管理 ', +//Added to provide User based TagCloud +'LBL_TAGCLOUD_DISPLAY'=>'标签关闭展示', +'INTERNAL_MAIL_COMPOSER'=>'内部邮件作者', + +// Added for 5.0.4 to Support Email notication on User Creation +'User Login Details'=>'用户登录细节', +'LBL_TO_LOGIN' => '登录', +// Added after 5.0.4 GA + +'LBL_USER_ADV_OPTIONS'=>'用户扩展选项', +'Reminder Interval'=>'提醒区间 ', +'Webservice Access Key'=>'Access Key', + +//user-group fixes +'LBL_GROUPNAME_EXIST' => '指定名称的用户组已经存在!', +'LBL_PROFILENAME_EXIST' => '概况与指定名称已经存在! ', +); + +?> diff --git a/oss/vtiger/trunk/modules/Users/lookupemailtemplates.php b/oss/vtiger/trunk/modules/Users/lookupemailtemplates.php new file mode 100644 index 00000000..0dcff2ba --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/lookupemailtemplates.php @@ -0,0 +1,76 @@ + + + + + + <?php echo $mod_strings['LBL_EMAIL_TEMPLATES_LIST']; ?> + + + +
    +
    +
    + + + + + + +pquery($sql, array()); + $temprow = $adb->fetch_array($result); + +$cnt=1; + +require_once('include/utils/UserInfoUtil.php'); +require('user_privileges/user_privileges_'.$current_user->id.'.php'); +do +{ + $templatename = $temprow["templatename"]; + if($is_admin == false) + { + $folderName = $temprow['foldername']; + if($folderName != 'Personal') + { + printf(""; + printf("",$temprow["description"]); + } + } + else + { + printf(""; + printf("",$temprow["description"]); + } + $cnt++; + +}while($temprow = $adb->fetch_array($result)); +?> +
    +
    "); + echo "".$temprow["templatename"]."%s
    "); + echo "".$temprow["templatename"]."%s
    + + + diff --git a/oss/vtiger/trunk/modules/Users/massChangeStatus.php b/oss/vtiger/trunk/modules/Users/massChangeStatus.php new file mode 100644 index 00000000..11aebd50 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/massChangeStatus.php @@ -0,0 +1,139 @@ +'lead_status_dom'); +$comboFieldArray = getComboArray($comboFieldNames); + +?> + + + + +
    + + + + + + + +
    Status Information
    + + + + +
    Select New Status:
    +
    + + + + +
    + + +
    + + +
    +pquery("select * from vtiger_users", array()); + for($i=0;$i<$adb->num_rows($result);$i++) + { + $useridlist[$i]=$adb->query_result($result,$i,'id'); + $usernamelist[$useridlist[$i]]=$adb->query_result($result,$i,'user_name'); + } + +?> +
    + +
    + + + + + + + +
    Owner Information
    + + + + +
    Select New Owner:
    +
    + + + + +
    + + +
    + + +
    + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/massdelete.php b/oss/vtiger/trunk/modules/Users/massdelete.php new file mode 100644 index 00000000..a3b10a6c --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/massdelete.php @@ -0,0 +1,80 @@ + 0) { + $ret = getEntityName($returnmodule,$ids_list); + if(count($ret) > 0) + { + $errormsg = implode(',',$ret); + } +} + +if(isset($_REQUEST['smodule']) && ($_REQUEST['smodule']!='')) +{ + $smod = "&smodule=".vtlib_purify($_REQUEST['smodule']); +} +if(isset($_REQUEST['start']) && ($_REQUEST['start']!='')) +{ + $rstart = "&start=".vtlib_purify($_REQUEST['start']); +} +if($returnmodule == 'Emails') +{ + if(isset($_REQUEST['folderid']) && $_REQUEST['folderid'] != '') + { + $folderid = vtlib_purify($_REQUEST['folderid']); + }else + { + $folderid = 1; + } + header("Location: index.php?module=".$returnmodule."&action=".$returnmodule."Ajax&folderid=".$folderid."&ajax=delete".$rstart."&file=ListView&errormsg=".$errormsg.$url); +} +elseif($return_action == 'ActivityAjax') +{ + $subtab = vtlib_purify($_REQUEST['subtab']); + header("Location: index.php?module=".$returnmodule."&action=".$return_action."".$rstart."&view=".vtlib_purify($_REQUEST['view'])."&hour=".vtlib_purify($_REQUEST['hour'])."&day=".vtlib_purify($_REQUEST['day'])."&month=".vtlib_purify($_REQUEST['month'])."&year=".vtlib_purify($_REQUEST['year'])."&type=".vtlib_purify($_REQUEST['type'])."&viewOption=".vtlib_purify($_REQUEST['viewOption'])."&subtab=".$subtab.$url); +} + +elseif($returnmodule!='Faq') +{ + header("Location: index.php?module=".$returnmodule."&action=".$returnmodule."Ajax&ajax=delete".$rstart."&file=ListView&viewname=".$viewid."&errormsg=".$errormsg.$url); +} +else +{ + header("Location: index.php?module=".$returnmodule."&action=".$returnmodule."Ajax&ajax=delete".$rstart."&file=ListView&errormsg=".$errormsg.$url); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/notify_detail.php b/oss/vtiger/trunk/modules/Users/notify_detail.php new file mode 100644 index 00000000..137dbbee --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/notify_detail.php @@ -0,0 +1,69 @@ + + + + + + +<?php echo $mod_strings['TITLE_USER_DOCUMENT']; ?> + + + +
    + + + + +
    : +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    :
    :
    :
    : <?php echo $mod_strings['LBL_INACTIVE']; ?> + [Deactivate]
    :
    :
    + + + +
      + +  
    +
    + + diff --git a/oss/vtiger/trunk/modules/Users/populatetemplate.php b/oss/vtiger/trunk/modules/Users/populatetemplate.php new file mode 100644 index 00000000..68c6904e --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/populatetemplate.php @@ -0,0 +1,100 @@ +pquery($sql, array($_REQUEST["templateid"])); +$tempArray = $adb->fetch_array($tempresult); +$fileContent = $tempArray["body"]; + +checkFileAccess($root_directory.'/modules/Emails/templates/'.$_REQUEST["templatename"]); +$handle = fopen($root_directory.'/modules/Emails/templates/'.$_REQUEST["templatename"],"wb") ; +fwrite($handle,$fileContent,89999999); +fclose($handle); + +//create a file and write to it so that it can be used as the emailtemplateusage.php file + +if (is_file($root_directory.'/modules/Emails/templates/testemailtemplateusage.php')) { + $is_writable = is_writable($root_directory.'/modules/Emails/templates/testemailtemplateusage.php'); +} else { + $is_writable = is_writable('.'); +} + +$myString = "retrieve_entity_info($recordid,$module); + +$i=0; +$m=0; +$n=0; +$myString; + +//storing the columnname and the value pairs +foreach ($focus->column_fields as $columnName=>$value) { + $myString .= "$" .$module ."_" .$columnName.' = "'. $value."\";\n\n"; + $colName[$i] = $columnName; + $i++; + $j=$i; +} + +global $current_user; +global $adb; +$query = 'select * from vtiger_users where id= ?'; +$result = $adb->pquery($query, array($current_user->id)); +$res_row = $adb->fetchByAssoc($result); +foreach ($res_row as $columnName=>$value) { + $myString .='$users_' .$columnName.' = "'. $value."\";\n\n"; + $usercolName[$n] = $columnName; + $n++; + $m=$n; +} + +$myString .= "\$globals = \""; + +for($i=0;$i<$j-1;$i++) { + $myString .= "\\$" .$module ."_" .$colName[$i].", "; +} +for($n=0;$n<$m;$n++) { + $myString .= '\\$users_' .$usercolName[$n].", "; +} + +$myString .= "\\$" .$module ."_" .$colName[$i]; +$myString .="\"; \n\n"; + +$myString .= "?> \n"; +if ($is_writable && ($config_file = @ fopen($root_directory.'/modules/Emails/templates/testemailtemplateusage.php', "w"))) { + $log->debug("writing to the testemailtemplatuseage.php file"); + fputs($config_file, $myString, strlen($myString)); + fclose($config_file); +} +checkFileAccess($root_directory.'/modules/Emails/templates/'.$_REQUEST["templatename"]); +$templatename = $root_directory.'/modules/Emails/templates/'.$_REQUEST["templatename"]; +header("Location:index.php?module=Users&action=TemplateMerge&templatename=".$templatename); + +?> + diff --git a/oss/vtiger/trunk/modules/Users/updateLeadDBStatus.php b/oss/vtiger/trunk/modules/Users/updateLeadDBStatus.php new file mode 100644 index 00000000..649de193 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/updateLeadDBStatus.php @@ -0,0 +1,104 @@ +pquery($del_act,array($id, $id)); + if($_REQUEST['owner_type'] == 'User') { + $count_r = $adb->pquery("select * from vtiger_salesmanactivityrel where smid=? and activityid=?",array($idval, $id)); + if($adb->num_rows($count_r) == 0) { + $insert = "insert into vtiger_salesmanactivityrel values(?,?)"; + $result = $adb->pquery($insert, array($idval, $id)); + } + } + } + //Now we have to update the smownerid + $sql = "update vtiger_crmentity set modifiedby=?, smownerid=?, modifiedtime=? where crmid=?"; + $result = $adb->pquery($sql, array($current_user->id, $idval, $adb->formatDate($date_var, true), $id)); + } + else + { + $ids_list[] = $id; + } + } +} +elseif(isset($_REQUEST['leadval']) && $_REQUEST['leadval']!='') +{ + + foreach($storearray as $id) + { + if(isPermitted($return_module,'EditView',$id) == 'yes') + { + if($id != '') { + $sql = "update vtiger_leaddetails set leadstatus=? where leadid=?"; + $result = $adb->pquery($sql, array($leadstatusval, $id)); + $query = "update vtiger_crmentity set modifiedby=?, modifiedtime=? where crmid=?"; + $result1 = $adb->pquery($query, array($current_user->id, $adb->formatDate($date_var, true), $id)); + } + } + else + { + $ids_list[] = $id; + } + + } +} +if(count($ids_list) > 0) { + $ret_owner = getEntityName($return_module,$ids_list); + $errormsg = implode(',',$ret_owner); +} else { + $errormsg = ''; +} +if($return_action == 'ActivityAjax') { + $view = vtlib_purify($_REQUEST['view']); + $day = vtlib_purify($_REQUEST['day']); + $month = vtlib_purify($_REQUEST['month']); + $year = vtlib_purify($_REQUEST['year']); + $type = vtlib_purify($_REQUEST['type']); + $viewOption = vtlib_purify($_REQUEST['viewOption']); + $subtab = vtlib_purify($_REQUEST['subtab']); + + header("Location: index.php?module=$return_module&action=".$return_action."&type=".$type.$rstart."&view=".$view."&day=".$day."&month=".$month."&year=".$year."&viewOption=".$viewOption."&subtab=".$subtab.$url); +} else { + header("Location: index.php?module=$return_module&action=".$return_module."Ajax&file=ListView&ajax=changestate".$rstart."&viewname=".$viewid."&errormsg=".$errormsg.$url); +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Users/updateNotificationSchedulers.php b/oss/vtiger/trunk/modules/Users/updateNotificationSchedulers.php new file mode 100644 index 00000000..55a000e5 --- /dev/null +++ b/oss/vtiger/trunk/modules/Users/updateNotificationSchedulers.php @@ -0,0 +1,47 @@ +pquery($sql, array($flag, $i)); +} + +header("Location:index.php?module=Users&action=listnotificationschedulers"); + + + + + +?> diff --git a/oss/vtiger/trunk/modules/Utilities/Calculator.php b/oss/vtiger/trunk/modules/Utilities/Calculator.php new file mode 100644 index 00000000..54d87743 --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/Calculator.php @@ -0,0 +1,30 @@ +assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGEPATH",$image_path); +$smarty->assign("CALC",get_calc($image_path)); +$smarty->display("Calculator.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Utilities/Clock.php b/oss/vtiger/trunk/modules/Utilities/Clock.php new file mode 100644 index 00000000..221bcca0 --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/Clock.php @@ -0,0 +1,27 @@ +assign("THEME", $theme); +$smarty->assign("IMAGEPATH",$image_path); +$smarty->display("Clock.tpl"); +?> diff --git a/oss/vtiger/trunk/modules/Utilities/Currencies.php b/oss/vtiger/trunk/modules/Utilities/Currencies.php new file mode 100644 index 00000000..73f393b1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/Currencies.php @@ -0,0 +1,132 @@ + array('ALL' ,'Lek'), + 'Argentina, Pesos' => array('ARS' ,'$'), + 'Aruba, Guilders' => array('AWG' ,'ƒ'), + 'Australia, Dollars' => array('AUD' ,'$'), + 'Azerbaijan, New Manats' => array('AZN' ,'ман'), + 'Bahamas, Dollars' => array('BSD' ,'$'), + 'Bahrain, Dinar'=>array('BHD','BD'), + 'Barbados, Dollars' => array('BBD' ,'$'), + 'Belarus, Rubles' => array('BYR' ,'p.'), + 'Belize, Dollars' => array('BZD' ,'BZ$'), + 'Bermuda, Dollars' => array('BMD' ,'$'), + 'Bolivia, Bolivianos' => array('BOB' ,'$b'), + 'Convertible Marka' => array('BAM' ,'KM'), + 'Botswana, Pulas' => array('BWP' ,'P'), + 'Bulgaria, Leva' => array('BGN' ,'лв'), + 'Brazil, Reais' => array('BRL' ,'R$'), + 'Great Britain Pounds' => array('GBP' ,'£'), + 'Brunei Darussalam, Dollars' => array('BND' ,'$'), + 'Canada, Dollars'=>array('CAD','$'), + 'Cayman Islands, Dollars'=>array('KYD','$'), + 'Chile, Pesos'=>array('CLP','$'), + 'Colombia, Pesos'=>array('COP','$'), + 'Costa Rica, Colón'=>array('CRC','₡'), + 'Croatia, Kuna'=>array('HRK','kn'), + 'Cuba, Pesos'=>array('CUP','₱'), + 'Czech Republic, Koruny'=>array('CZK','Kč'), + 'Denmark, Kroner'=>array('DKK','kr'), + 'Dominican Republic, Pesos'=>array('DOP','RD$'), + 'East Caribbean, Dollars'=>array('XCD','$'), + 'Egypt, Pounds'=>array('EGP','£'), + 'El Salvador, Colones'=>array('SVC','$'), + 'England, Pounds'=>array('GBP','£'), + 'Estonia, Krooni'=>array('EEK','kr'), + 'Euro'=>array('EUR','€'), + 'Falkland Islands, Pounds'=>array('FKP','£'), + 'Fiji, Dollars'=>array('FJD','$'), + 'Ghana, Cedis'=>array('GHC','¢'), + 'Gibraltar, Pounds'=>array('GIP','£'), + 'Guatemala, Quetzales'=>array('GTQ','Q'), + 'Guernsey, Pounds'=>array('GGP','£'), + 'Guyana, Dollars'=>array('GYD','$'), + 'Honduras, Lempiras'=>array('HNL','L'), + 'LvHong Kong, Dollars '=>array('HKD','HK$'), + 'Hungary, Forint'=>array('HUF','Ft'), + 'Iceland, Krona'=>array('ISK','kr'), + 'India, Rupees'=>array('INR','₨'), + 'Indonesia, Rupiahs'=>array('IDR','Rp'), + 'Iran, Rials'=>array('IRR','﷼'), + 'Isle of Man, Pounds'=>array('IMP','£'), + 'Israel, New Shekels'=>array('ILS','₪'), + 'Jamaica, Dollars'=>array('JMD','J$'), + 'Japan, Yen'=>array('JPY','¥'), + 'Jersey, Pounds'=>array('JEP','£'), + 'Kazakhstan, Tenge'=>array('KZT','лв'), + 'Korea (North), Won'=>array('KPW','₩'), + 'Korea (South), Won'=>array('KRW','₩'), + 'Kyrgyzstan, Soms'=>array('KGS','лв'), + 'Laos, Kips'=>array('LAK','₭'), + 'Latvia, Lati'=>array('LVL','Ls'), + 'Lebanon, Pounds'=>array('LBP','£'), + 'Liberia, Dollars'=>array('LRD','$'), + 'Switzerland Francs'=>array('CHF','CHF'), + 'Lithuania, Litai'=>array('LTL','Lt'), + 'Macedonia, Denars'=>array('MKD','ден'), + 'Malaysia, Ringgits'=>array('MYR','RM'), + 'Mauritius, Rupees'=>array('MUR','₨'), + 'Mexico, Pesos'=>array('MXN','$'), + 'Mongolia, Tugriks'=>array('MNT','₮'), + 'Mozambique, Meticais'=>array('MZN','MT'), + 'Namibia, Dollars'=>array('NAD','$'), + 'Nepal, Rupees'=>array('NPR','₨'), + 'Netherlands Antilles, Guilders'=>array('ANG','ƒ'), + 'New Zealand, Dollars'=>array('NZD','$'), + 'Nicaragua, Cordobas'=>array('NIO','C$'), + 'Nigeria, Nairas'=>array('NGN','₦'), + 'North Korea, Won'=>array('KPW','₩'), + 'Norway, Krone'=>array('NOK','kr'), + 'Oman, Rials'=>array('OMR','﷼'), + 'Pakistan, Rupees'=>array('PKR','₨'), + 'Panama, Balboa'=>array('PAB','B/.'), + 'Paraguay, Guarani'=>array('PYG','Gs'), + 'Peru, Nuevos Soles'=>array('PEN','S/.'), + 'Philippines, Pesos'=>array('PHP','Php'), + 'Poland, Zlotych'=>array('PLN','zł'), + 'Romania, New Lei'=>array('RON','lei'), + 'Russia, Rubles'=>array('RUB','руб'), + 'Saint Helena, Pounds'=>array('SHP','£'), + 'Saudi Arabia, Riyals'=>array('SAR','﷼'), + 'Serbia, Dinars'=>array('RSD','Дин.'), + 'Seychelles, Rupees'=>array('SCR','₨'), + 'Singapore, Dollars'=>array('SGD','$'), + 'Solomon Islands, Dollars'=>array('SBD','$'), + 'Somalia, Shillings'=>array('SOS','S'), + 'South Africa, Rand'=>array('ZAR','R'), + 'South Korea, Won'=>array('KRW','₩'), + 'Sri Lanka, Rupees'=>array('LKR','₨'), + 'Sweden, Kronor'=>array('SEK','kr'), + 'Switzerland, Francs'=>array('CHF','CHF'), + 'Suriname, Dollars'=>array('SRD','$'), + 'Syria, Pounds'=>array('SYP','£'), + 'Taiwan, New Dollars'=>array('TWD','NT$'), + 'Thailand, Baht'=>array('THB','฿'), + 'Trinidad and Tobago, Dollars'=>array('TTD','TT$'), + 'Turkey, New Lira'=>array('TRY','YTL'), + 'Turkey, Liras'=>array('TRL','₤'), + 'Tuvalu, Dollars'=>array('TVD','$'), + 'Ukraine, Hryvnia'=>array('UAH','₴'), + 'United Kingdom, Pounds'=>array('GBP','£'), + 'USA, Dollars' => array('USD' ,'$'), + 'Uruguay, Pesos'=>array('UYU','$U'), + 'Uzbekistan, Sums'=>array('UZS','лв'), + 'Venezuela, Bolivares Fuertes'=>array('VEF','Bs'), + 'Vietnam, Dong'=>array('VND','₫'), + 'Zimbabwe Dollars'=>array('ZWD','Z$'), + ); +/* + 'China, Yuan Renminbi'=>array('SAR','﷼'), + 'Afghanistan, Afghanis'=>array('SAR','﷼'), + 'Cambodia, Riels'=>array('SAR','﷼'), +*/ +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Utilities/Merge.php b/oss/vtiger/trunk/modules/Utilities/Merge.php new file mode 100644 index 00000000..35890b4c --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/Merge.php @@ -0,0 +1,88 @@ + + +pquery($sql, array($mergeFileName)); +$temparray = $adb->fetch_array($result); + +$fileContent = $temparray['data']; +$filename=html_entity_decode($temparray['filename'], ENT_QUOTES, $default_charset); +// Fix For: http://trac.vtiger.com/cgi-bin/trac.cgi/ticket/2107 +$filename= $randomfilename . "_word.doc"; + +$filesize=$temparray['filesize']; +$wordtemplatedownloadpath =$_SERVER['DOCUMENT_ROOT'] ."/test/wordtemplatedownload/"; +checkFileAccess($wordtemplatedownloadpath); +$handle = fopen($wordtemplatedownloadpath .$filename,"wb") ; +fwrite($handle,base64_decode($fileContent),$filesize); +fclose($handle); + + +$query = "SELECT * FROM " .$adb->sql_escape_string($_REQUEST["module"]) ." WHERE id = ?"; +$result = $adb->pquery($query, array($_REQUEST['record'])); + +$y=$adb->num_fields($result); + +for ($x=0; $x<$y; $x++) +{ + $columnNames[$x] = "CONTACT_".strtoupper($adb->field_name($result, $x)); +} + +$columnValues = $adb->fetch_array($result); +for ($x=0; $x<$y; $x++) +{ + $columnValString[$x] = $columnValues[$x]; +} + +$columnString = implode(",",$columnNames); +$columnValString = implode(",",$columnValString); + +echo""; +?> + +/modules/Settings/vtigerVM.CAB#Version1,0,0,1" +id="objMMPage" classid="clsid:42C50C38-1984-4393-A736-890357E7112B" width=0 height=0> + + + + diff --git a/oss/vtiger/trunk/modules/Utilities/UtilitiesAjax.php b/oss/vtiger/trunk/modules/Utilities/UtilitiesAjax.php new file mode 100644 index 00000000..e12e4ba8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/UtilitiesAjax.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Utilities/language/en_us.lang.php b/oss/vtiger/trunk/modules/Utilities/language/en_us.lang.php new file mode 100644 index 00000000..57d771c3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/language/en_us.lang.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Utilities/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/Utilities/language/zh_cn.lang.php new file mode 100644 index 00000000..57d771c3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Utilities/language/zh_cn.lang.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/CallRelatedList.php b/oss/vtiger/trunk/modules/Vendors/CallRelatedList.php new file mode 100644 index 00000000..169f8061 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/CallRelatedList.php @@ -0,0 +1,75 @@ +retrieve_entity_info($RECORD,$currentmodule); + $focus->id = $RECORD; + $focus->name=$focus->column_fields['vendorname']; + $log->debug("Vendor id =".$focus->id); + $log->debug("Vendor name =".$focus->name); + } + if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') { + $focus->id = ""; + } + + $related_array=getRelatedLists($currentmodule,$focus); + + global $mod_strings; + global $app_strings; + global $theme, $currentModule; + $theme_path="themes/".$theme."/"; + $image_path=$theme_path."images/"; + + $smarty = new vtigerCRM_Smarty; + + $smarty->assign("CATEGORY",$category); + + if(isset($_REQUEST['mode']) && $_REQUEST['mode'] != ' ') { + $smarty->assign("OP_MODE",vtlib_purify($_REQUEST['mode'])); + } + if(isset($focus->name)) + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("NAME", $focus->name); + $smarty->assign("ID",$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 + + $smarty->assign("MODULE",$currentModule); + $smarty->assign("SINGLE_MOD",$app_strings['Vendor']); + $smarty->assign("RELATEDLISTS", $related_array); + $smarty->assign("MOD",$mod_strings); + $smarty->assign("APP",$app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + + $check_button = Button_Check($module); + $smarty->assign("CHECK", $check_button); + $smarty->display("RelatedLists.tpl"); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/CustomView.php b/oss/vtiger/trunk/modules/Vendors/CustomView.php new file mode 100644 index 00000000..93231ed6 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/CustomView.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/Delete.php b/oss/vtiger/trunk/modules/Vendors/Delete.php new file mode 100644 index 00000000..a2ee6241 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/Delete.php @@ -0,0 +1,38 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/DetailView.php b/oss/vtiger/trunk/modules/Vendors/DetailView.php new file mode 100644 index 00000000..97d350ed --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/DetailView.php @@ -0,0 +1,105 @@ +retrieve_entity_info($_REQUEST['record'],"Vendors"); + $focus->id = $_REQUEST['record']; + $focus->name = $focus->column_fields['vendorname']; +} + +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; +} + +global $app_strings,$mod_strings,$theme,$currentModule,$singlepane_view; + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty = new vtigerCRM_Smarty; +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +if(isset($focus->name)) + $smarty->assign("NAME", $focus->name); + +$smarty->assign("BLOCKS", getBlocks($currentModule,"detail_view",'',$focus->column_fields)); + +$smarty->assign("CUSTOMFIELD", $cust_fld); + +if(isPermitted("Vendors","VendorEditView",$_REQUEST['record']) == 'yes') + $smarty->assign("EDIT_DUPLICATE","permitted"); +if(isPermitted("Vendors","DeleteVendor",$_REQUEST['record']) == 'yes') + $smarty->assign("DELETE","permitted"); + + +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$smarty->assign("UPDATEINFO",updateInfo($focus->id)); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); +$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); +$smarty->assign("ID", vtlib_purify($_REQUEST['record'])); + +// 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 + +$smarty->assign("MODULE", $currentModule); +$smarty->assign("SINGLE_MOD", 'Vendor'); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); + +$tabid = getTabid("Vendors"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); +$smarty->assign("EDIT_PERMISSION",isPermitted($currentModule,'EditView',$_REQUEST['record'])); + +$smarty->assign("IS_REL_LIST",isPresentRelatedLists($currentModule)); + +if($singlepane_view == 'true') +{ + $related_array = getRelatedLists($currentModule,$focus); + $smarty->assign("RELATEDLISTS", $related_array); +} + +$smarty->assign("SinglePane_View", $singlepane_view); + +if(PerformancePrefs::getBoolean('DETAILVIEW_RECORD_NAVIGATION', true) && isset($_SESSION[$currentModule.'_listquery'])){ + $recordNavigationInfo = ListViewSession::getListViewNavigation($focus->id); + VT_detailViewNavigation($smarty,$recordNavigationInfo,$focus->id); +} +// Record Change Notification +$focus->markAsViewed($current_user->id); +// END + +$smarty->assign('DETAILVIEW_AJAX_EDIT', PerformancePrefs::getBoolean('DETAILVIEW_AJAX_EDIT', true)); + +$smarty->display("Inventory/InventoryDetailView.tpl"); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/DetailViewAjax.php b/oss/vtiger/trunk/modules/Vendors/DetailViewAjax.php new file mode 100644 index 00000000..5e738f39 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/DetailViewAjax.php @@ -0,0 +1,45 @@ +retrieve_entity_info($crmid,"Vendors"); + $modObj->column_fields[$fieldname] = $fieldvalue; + $modObj->id = $crmid; + $modObj->mode = "edit"; + $modObj->save("Vendors"); + if($modObj->id != "") + { + echo ":#:SUCCESS"; + }else + { + echo ":#:FAILURE"; + } + }else + { + echo ":#:FAILURE"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/EditView.php b/oss/vtiger/trunk/modules/Vendors/EditView.php new file mode 100644 index 00000000..d0a1d8df --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/EditView.php @@ -0,0 +1,127 @@ +assign("SEARCH", $searchurl); +//4600 ends + +if(isset($_REQUEST['record']) && $_REQUEST['record'] != '') +{ + $focus->id = $_REQUEST['record']; + $focus->mode = 'edit'; + $focus->retrieve_entity_info($_REQUEST['record'],"Vendors"); + $focus->name = $focus->column_fields['vendorname']; +} +if(isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') +{ + $focus->id = ""; + $focus->mode = ''; +} +if(empty($_REQUEST['record']) && $focus->mode != 'edit'){ + setObjectValuesFromRequest($focus); +} + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; + +$disp_view = getView($focus->mode); +if($disp_view == 'edit_view') + $smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +else +{ + $bas_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'BAS'); + $adv_block = getBlocks($currentModule,$disp_view,$mode,$focus->column_fields,'ADV'); + + $blocks['basicTab'] = $bas_block; + if(is_array($adv_block )) + $blocks['moreTab'] = $adv_block; + + $smarty->assign("BLOCKS",$blocks); + $smarty->assign("BLOCKS_COUNT",count($blocks)); +} +$smarty->assign("OP_MODE",$disp_view); + +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Vendor'); + +$smarty->assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); + +$smarty->assign("ID", $focus->id); +if(isset($focus->name)) + $smarty->assign("NAME", $focus->name); + +if(isset($cust_fld)) +{ + $smarty->assign("CUSTOMFIELD", $cust_fld); +} + +$smarty->assign("CALENDAR_LANG", $app_strings['LBL_JSCALENDAR_LANG']); +$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT'])); +if($focus->mode == 'edit') +{ + $smarty->assign("UPDATEINFO",updateInfo($focus->id)); + $smarty->assign("MODE", $focus->mode); +} + +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'])); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path);$smarty->assign("PRINT_URL", "phprint.php?jt=".session_id().$GLOBALS['request_string']); + +$tabid = getTabid("Vendors"); +$validationData = getDBValidationData($focus->tab_name,$tabid); +$data = split_validationdataArray($validationData); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); +$smarty->assign("VALIDATION_DATA_FIELDNAME",$data['fieldname']); +$smarty->assign("VALIDATION_DATA_FIELDDATATYPE",$data['datatype']); +$smarty->assign("VALIDATION_DATA_FIELDLABEL",$data['fieldlabel']); + +$check_button = Button_Check($module); +$smarty->assign("CHECK", $check_button); +$smarty->assign("DUPLICATE",vtlib_purify($_REQUEST['isDuplicate'])); + +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 '
    '. getTranslatedString('LBL_DUPLICATE'). ' '. getTranslatedString($mod_seq_field['label']) + .' - '. getTranslatedString('LBL_CLICK') .' '.getTranslatedString('LBL_HERE').' ' + . getTranslatedString('LBL_TO_CONFIGURE'). ' '. getTranslatedString($mod_seq_field['label']) .''; + else + $smarty->assign("MOD_SEQ_ID",$autostr); +} else { + $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]); +} +// END + + +if($focus->mode == 'edit') + $smarty->display('Inventory/InventoryEditView.tpl'); +else + $smarty->display('Inventory/InventoryCreateView.tpl'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/ExportRecords.php b/oss/vtiger/trunk/modules/Vendors/ExportRecords.php new file mode 100644 index 00000000..f2714fa3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/ExportRecords.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/FindDuplicateRecords.php b/oss/vtiger/trunk/modules/Vendors/FindDuplicateRecords.php new file mode 100644 index 00000000..74ad2c8d --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/FindDuplicateRecords.php @@ -0,0 +1,107 @@ +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 "
    "; + echo "
    + + + + + + + + + +
    + $app_strings[LBL_DUP_PERMISSION] $req_module $errormsg
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/Import.php b/oss/vtiger/trunk/modules/Vendors/Import.php new file mode 100644 index 00000000..7a1102d4 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/Import.php @@ -0,0 +1,16 @@ + + diff --git a/oss/vtiger/trunk/modules/Vendors/ListView.php b/oss/vtiger/trunk/modules/Vendors/ListView.php new file mode 100644 index 00000000..3a059b46 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/ListView.php @@ -0,0 +1,237 @@ +assign("MOD", $mod_strings); +$smarty->assign("APP", $app_strings); +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH",$image_path); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("SINGLE_MOD",'Vendor'); +$category = getParentTab(); +$smarty->assign("CATEGORY",$category); + +$focus = new Vendors(); +// Initialize sort by fields +$focus->initSortbyField('Vendors'); +// END +$other_text = Array(); + +if(!$_SESSION['lvs'][$currentModule]) +{ + unset($_SESSION['lvs']); + $modObj = new ListViewSession(); + $modObj->sorder = $sorder; + $modObj->sortby = $order_by; + $_SESSION['lvs'][$currentModule] = get_object_vars($modObj); +} + +if($_REQUEST['errormsg'] != '') +{ + $errormsg = vtlib_purify($_REQUEST['errormsg']); + $smarty->assign("ERROR","The User does not have permission to delete ".$errormsg." ".$currentModule); +}else +{ + $smarty->assign("ERROR",""); +} +if (!isset($where)) $where = ""; + +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> +if($_REQUEST['order_by'] != '') + $order_by = $adb->sql_escape_string($_REQUEST['order_by']); +else + $order_by = (($_SESSION['VENDORS_ORDER_BY'] != '')?($_SESSION['VENDORS_ORDER_BY']):($focus->default_order_by)); + +if($_REQUEST['sorder'] != '') + $sorder = $adb->sql_escape_string($_REQUEST['sorder']); +else + $sorder = (($_SESSION['VENDORS_SORT_ORDER'] != '')?($_SESSION['VENDORS_SORT_ORDER']):($focus->default_sort_order)); + +$_SESSION['VENDORS_ORDER_BY'] = $order_by; +$_SESSION['VENDORS_SORT_ORDER'] = $sorder; +//<<<<<<<<<<<<<<<<<<< sorting - stored in session >>>>>>>>>>>>>>>>>>>> + +if(isset($_REQUEST['query']) && $_REQUEST['query'] != '' && $_REQUEST['query'] == 'true') +{ + list($where, $ustring) = split("#@@#",getWhereCondition($currentModule)); + // we have a query + $url_string .="&query=true".$ustring; + $log->info("Here is the where clause for the list view: $where"); + $smarty->assign("SEARCH_URL",$url_string); + +} + +//<<<>>>>>> +$oCustomView = new CustomView("Vendors"); +$viewid = $oCustomView->getViewId($currentModule); +$customviewcombo_html = $oCustomView->getCustomViewCombo($viewid); +$viewnamedesc = $oCustomView->getCustomViewByCvid($viewid); + +//Added to handle approving or denying status-public by the admin in CustomView +$statusdetails = $oCustomView->isPermittedChangeStatus($viewnamedesc['status']); +$smarty->assign("CUSTOMVIEW_PERMISSION",$statusdetails); + +//To check if a user is able to edit/delete a customview +$edit_permit = $oCustomView->isPermittedCustomView($viewid,'EditView',$currentModule); +$delete_permit = $oCustomView->isPermittedCustomView($viewid,'Delete',$currentModule); +$smarty->assign("CV_EDIT_PERMIT",$edit_permit); +$smarty->assign("CV_DELETE_PERMIT",$delete_permit); + +//<<<<>>>> + +// Buttons and View options +if(isPermitted('Vendors','DeleteVendor','') == 'yes') +{ + $other_text['del'] = $app_strings[LBL_MASS_DELETE]; +} +if(isPermitted('Vendors','EditView','') == 'yes') + $other_text['mass_edit'] = $app_strings[LBL_MASS_EDIT]; + +if($viewnamedesc['viewname'] == 'All') +{ + $smarty->assign("ALL", 'All'); +} +if($viewid ==0) +{ + echo "
    "; + echo "
    + + + + + + + + + +
    $app_strings[LBL_PERMISSION]
    + $app_strings[LBL_GO_BACK]
    +
    +
    "; + echo "
    "; + exit; +} + + +//Retreive the list from Database +//<<<<<<<<>>>>>>>> +if($viewid != "0") +{ + $listquery = getListQuery("Vendors"); + $list_query = $oCustomView->getModifiedCvListQuery($viewid,$listquery,"Vendors"); +}else +{ + $list_query = getListQuery("Vendors"); +} +//<<<<<<<>>>>>>>> + +if(isset($where) && $where != '') +{ + $list_query .= ' and '.$where; + $_SESSION['export_where'] = $where; +} +else + unset($_SESSION['export_where']); + + +if(isset($order_by) && $order_by != '') +{ + $tablename = getTableNameForField('Vendors',$order_by); + $tablename = (($tablename != '')?($tablename."."):''); + + if( $adb->dbType == "pgsql") + $list_query .= ' GROUP BY '.$tablename.$order_by; + + $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); + +//Retreive the List View Table Header +if($viewid !='') +$url_string .="&viewname=".$viewid; + +$listview_header = getListViewHeader($focus,"Vendors",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("LISTHEADER", $listview_header); + +$listview_header_search = getSearchListHeaderValues($focus,"Vendors",$url_string,$sorder,$order_by,"",$oCustomView); +$smarty->assign("SEARCHLISTHEADER",$listview_header_search); + +$listview_entries = getListViewEntries($focus,"Vendors",$list_result,$navigation_array,'','&return_module=Vendors&return_action=index','EditView','Delete',$oCustomView); +$smarty->assign("LISTENTITY", $listview_entries); + +$smarty->assign("AVALABLE_FIELDS", getMergeFields($currentModule,"available_fields")); +$smarty->assign("FIELDS_TO_MERGE", getMergeFields($currentModule,"fileds_to_merge")); + +//Added to select Multiple records in multiple pages +$smarty->assign("SELECTEDIDS", vtlib_purify($_REQUEST['selobjs'])); +$smarty->assign("ALLSELECTEDIDS", vtlib_purify($_REQUEST['allselobjs'])); +$smarty->assign("CURRENT_PAGE_BOXES", implode(array_keys($listview_entries),";")); + +$smarty->assign("CUSTOMVIEW_OPTION",$customviewcombo_html); +$smarty->assign("VIEWID", $viewid); +$navigationOutput = getTableHeaderSimpleNavigation($navigation_array, $url_string,"Vendors","index",$viewid); +$alphabetical = AlphabeticalSearch($currentModule,'index','vendorname','true','basic',"","","","",$viewid); +$fieldnames = getAdvSearchfields($currentModule); +$criteria = getcriteria_options(); +$smarty->assign("CRITERIA", $criteria); +$smarty->assign("FIELDNAMES", $fieldnames); +$smarty->assign("ALPHABETICAL", $alphabetical); +$smarty->assign("NAVIGATION", $navigationOutput); +$smarty->assign("RECORD_COUNTS", $record_string); +$smarty->assign("BUTTONS", $other_text); + +$check_button = Button_Check($currentModule); +$smarty->assign("CHECK", $check_button); + +$_SESSION[$currentModule.'_listquery'] = $list_query; + +if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] != '') + $smarty->display("ListViewEntries.tpl"); +else + $smarty->display("ListView.tpl"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/ListViewPagging.php b/oss/vtiger/trunk/modules/Vendors/ListViewPagging.php new file mode 100644 index 00000000..333f1768 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/ListViewPagging.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/MassEdit.php b/oss/vtiger/trunk/modules/Vendors/MassEdit.php new file mode 100644 index 00000000..348dab37 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/MassEdit.php @@ -0,0 +1,45 @@ +mode = ''; +$mode = 'mass_edit'; +$disp_view = getView($focus->mode); + +$smarty = new vtigerCRM_Smarty; +$smarty->assign("BLOCKS",getBlocks($currentModule,$disp_view,$mode,$focus->column_fields)); +$smarty->assign("IDS",$_REQUEST['idstring']); +$smarty->assign("MASS_EDIT","1"); +$smarty->assign("MODULE",$currentModule); +$smarty->assign("APP",$app_strings); +$smarty->assign("CATEGORY",getParentTab()); + +$theme_path="themes/".$theme."/"; +$image_path=$theme_path."images/"; +$smarty->assign("THEME", $theme); +$smarty->assign("IMAGE_PATH", $image_path); + +// 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'); + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/MassEditSave.php b/oss/vtiger/trunk/modules/Vendors/MassEditSave.php new file mode 100644 index 00000000..c587e5fc --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/MassEditSave.php @@ -0,0 +1,68 @@ +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"); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/Popup.php b/oss/vtiger/trunk/modules/Vendors/Popup.php new file mode 100644 index 00000000..39b573a1 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/Popup.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/ProcessDuplicates.php b/oss/vtiger/trunk/modules/Vendors/ProcessDuplicates.php new file mode 100644 index 00000000..bb5047fa --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/ProcessDuplicates.php @@ -0,0 +1,134 @@ +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,""); + } + } + + ?> + +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"); +} + +?> diff --git a/oss/vtiger/trunk/modules/Vendors/QuickCreate.php b/oss/vtiger/trunk/modules/Vendors/QuickCreate.php new file mode 100644 index 00000000..8d5998b8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/QuickCreate.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/Save.php b/oss/vtiger/trunk/modules/Vendors/Save.php new file mode 100644 index 00000000..694801b3 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/Save.php @@ -0,0 +1,53 @@ +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("Vendors"); +$return_id = $focus->id; + +if(isset($_REQUEST['return_module']) && $_REQUEST['return_module'] != "") $return_module = vtlib_purify($_REQUEST['return_module']); +else $return_module = "Vendors"; +if(isset($_REQUEST['return_action']) && $_REQUEST['return_action'] != "") $return_action = vtlib_purify($_REQUEST['return_action']); +else $return_action = "DetailView"; +if(isset($_REQUEST['return_id']) && $_REQUEST['return_id'] != "") $return_id = vtlib_purify($_REQUEST['return_id']); + +//code added for returning back to the current view after edit from list view +if($_REQUEST['return_viewname'] == '') $return_viewname='0'; +if($_REQUEST['return_viewname'] != '')$return_viewname=vtlib_purify($_REQUEST['return_viewname']); + +header("Location: index.php?action=$return_action&module=$return_module&record=$return_id&viewname=$return_viewname&smodule=VENDOR&start=".vtlib_purify($_REQUEST['pagenumber']).$search); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/Settings.php b/oss/vtiger/trunk/modules/Vendors/Settings.php new file mode 100644 index 00000000..980dd078 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/Settings.php @@ -0,0 +1,13 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/TagCloud.php b/oss/vtiger/trunk/modules/Vendors/TagCloud.php new file mode 100644 index 00000000..859b11ff --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/TagCloud.php @@ -0,0 +1,12 @@ + diff --git a/oss/vtiger/trunk/modules/Vendors/UnifiedSearch.php b/oss/vtiger/trunk/modules/Vendors/UnifiedSearch.php new file mode 100644 index 00000000..9a37320c --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/UnifiedSearch.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/Vendors/Vendors.js b/oss/vtiger/trunk/modules/Vendors/Vendors.js new file mode 100644 index 00000000..be3122d8 --- /dev/null +++ b/oss/vtiger/trunk/modules/Vendors/Vendors.js @@ -0,0 +1,72 @@ +/********************************************************************************* +** 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. + * + ********************************************************************************/ +document.write(" + + is_admin)==='on'; + } + +/* function to check if the module has workflow + * @params :: $modulename - name of the module + */ + function checkModuleWorkflow($modulename){ + global $adb; + $tabid = getTabid($modulename); + $modules_not_supported = array('Documents','Calendar','Emails','Faq','Events','PBXManager','Users'); + $query = "SELECT name FROM vtiger_tab WHERE name not in (".generateQuestionMarks($modules_not_supported).") AND isentitytype=1 AND presence = 0 AND tabid = ?"; + $result = $adb->pquery($query,array($modules_not_supported,$tabid)); + $rows = $adb->num_rows($result); + if($rows > 0){ + return true; + }else{ + return false; + } + } +} + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/com_vtiger_workflowAjax.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/com_vtiger_workflowAjax.php new file mode 100644 index 00000000..067b69bf --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/com_vtiger_workflowAjax.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/deletetask.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/deletetask.php new file mode 100644 index 00000000..f8f29ecc --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/deletetask.php @@ -0,0 +1,45 @@ +name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $wm = new VTTaskManager($adb); + $wm->deleteTask($request['task_id']); + + if(isset($request["return_url"])){ + $returnUrl=$request["return_url"]; + }else{ + $returnUrl=$module->editWorkflowUrl($wf->id); + } + + ?> + + Return + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/deleteworkflow.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/deleteworkflow.php new file mode 100644 index 00000000..0e2770ef --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/deleteworkflow.php @@ -0,0 +1,44 @@ +name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $wm = new VTWorkflowManager($adb); + $wm->delete($request['workflow_id']); + + if(isset($request["return_url"])){ + $returnUrl=$request["return_url"]; + }else{ + $returnUrl=$module->listViewUrl($wf->id); + } + + ?> + + Return + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/edittask.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/edittask.php new file mode 100644 index 00000000..754b310f --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/edittask.php @@ -0,0 +1,115 @@ +name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $smarty = new vtigerCRM_Smarty(); + $tm = new VTTaskManager($adb); + $smarty->assign('edit',isset($request["task_id"])); + if(isset($request["task_id"])){ + $task = $tm->retrieveTask($request["task_id"]); + $workflowId=$task->workflowId; + }else{ + $workflowId = $request["workflow_id"]; + $taskClass = $request["task_type"]; + $task = $tm->createTask($taskClass, $workflowId); + } + + if($task==null){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NO_TASK']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NO_TASK']); + return; + } + + $wm = new VTWorkflowManager($adb); + $workflow = $wm->retrieve($workflowId); + if($workflow==null){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NO_WORKFLOW']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NO_WORKFLOW']); + return; + } + + + $smarty->assign("workflow", $workflow); + $smarty->assign("returnUrl", $request["return_url"]); + $smarty->assign("task", $task); + $smarty->assign("taskType", $taskClass); + $smarty->assign("saveType", $request['save_type']); + $taskClass = get_class($task); + $smarty->assign("taskTemplate", "{$module->name}/taskforms/$taskClass.tpl"); + $et = VTWSEntityType::usingGlobalCurrentUser($workflow->moduleName); + $smarty->assign("entityType", $et); + $smarty->assign('entityName', $workflow->moduleName); + $smarty->assign("fieldNames", $et->getFieldNames()); + + $dateFields = array(); + $fieldTypes = $et->getFieldTypes(); + $fieldLabels = $et->getFieldLabels(); + foreach($fieldTypes as $name => $type){ + if($type->type=='Date' || $type->type=='DateTime'){ + $dateFields[$name] = $fieldLabels[$name]; + } + } + + $smarty->assign('dateFields', $dateFields); + + + if($task->trigger!=null){ + $trigger = $task->trigger; + $days = $trigger['days']; + if ($days < 0){ + $days*=-1; + $direction = 'before'; + }else{ + $direction = 'after'; + } + $smarty->assign('trigger', array('days'=>$days, 'direction'=>$direction, + 'field'=>$trigger['field'])); + } + + + $smarty->assign("MOD", array_merge( + return_module_language($current_language,'Settings'), + return_module_language($current_language, $module->name))); + $smarty->assign("APP", $app_strings); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("THEME", $theme); + $smarty->assign("MODULE_NAME", $module->label); + $smarty->assign("PAGE_NAME", $mod['LBL_EDIT_TASK']); + $smarty->assign("PAGE_TITLE", $mod['LBL_EDIT_TASK_TITLE']); + + $smarty->assign("module", $module); + + $smarty->display("{$module->name}/EditTask.tpl"); + } + vtTaskEdit($adb, $_REQUEST, $current_language, $app_strings); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/editworkflow.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/editworkflow.php new file mode 100644 index 00000000..639a0098 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/editworkflow.php @@ -0,0 +1,86 @@ +name); + + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + + $smarty = new vtigerCRM_Smarty(); + if($request['source']=='from_template'){ + $tm = new VTWorkflowTemplateManager($adb); + $template = $tm->retrieveTemplate($request['template_id']); + $workflow = $tm->createWorkflow($template); + }else{ + $wfs = new VTWorkflowManager($adb); + if(isset($request["workflow_id"])){ + $workflow = $wfs->retrieve($request["workflow_id"]); + }else{ + $moduleName=$request["module_name"]; + $workflow = $wfs->newWorkflow($moduleName); + } + } + + if($workflow==null){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NO_WORKFLOW']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NO_WORKFLOW']); + return; + } + $tm = new VTTaskManager($adb); + $tasks = $tm->getTasksForWorkflow($workflow->id); + $smarty->assign("tasks", $tasks); + $smarty->assign("taskTypes", $tm->getTaskTypes()); + $smarty->assign("newTaskReturnUrl", $requestUrl); + + $smarty->assign("returnUrl", $request["return_url"]); + $smarty->assign("APP", $app_strings); + $smarty->assign("MOD", array_merge( + return_module_language($current_language,'Settings'), + return_module_language($current_language, $module->name))); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH", $image_path); + $smarty->assign("MODULE_NAME", $module->label); + $smarty->assign("PAGE_NAME", $mod['LBL_EDIT_WORKFLOW']); + $smarty->assign("PAGE_TITLE", $mod['LBL_EDIT_WORKFLOW_TITLE']); + + $smarty->assign("workflow", $workflow); + $smarty->assign("saveType", isset($workflow->id)?"edit":"new"); + $smarty->assign("module", $module); + + $smarty->display("{$module->name}/EditWorkflow.tpl"); +} +vtWorkflowEdit($adb, $_REQUEST, $_SERVER["REQUEST_URI"], $current_language, $app_strings); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/entitymethodjson.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/entitymethodjson.php new file mode 100644 index 00000000..37f71729 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/entitymethodjson.php @@ -0,0 +1,21 @@ +methodsForModule($moduleName); + echo Zend_Json::encode($methodNames); +} + +vtEntityMethodJson($adb, $_REQUEST); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/errormessage.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/errormessage.php new file mode 100644 index 00000000..9459f0b3 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/errormessage.php @@ -0,0 +1,12 @@ + +

    Error

    + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/errorpage.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/errorpage.php new file mode 100644 index 00000000..10d1b854 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/errorpage.php @@ -0,0 +1,18 @@ + +

    Workflow engine error

    + + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/include.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/include.inc new file mode 100644 index 00000000..0c8ec5d2 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/include.inc @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/include_webservices.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/include_webservices.php new file mode 100644 index 00000000..78913350 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/include_webservices.php @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/language/en_us.lang.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/language/en_us.lang.php new file mode 100644 index 00000000..9eeb1bc6 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/language/en_us.lang.php @@ -0,0 +1,42 @@ + 'Send Email', +'VTEntityMethodTask' => 'Invoke Custom Function', +'VTCreateTodoTask' => 'Create Todo', +'VTCreateEventTask' => 'Create Event', +'LBL_EDIT_TASK'=>'Edit Task', +'LBL_EDIT_TASK_TITLE'=>'Edit an existing task or create a new one', +'LBL_EDIT_WORKFLOW'=>'Edit Workflow', +'LBL_EDIT_WORKFLOW_TITLE'=>'Edit an existing workflow or create a one', +'LBL_FROM_TEMPLATE'=>'From Template', +'LBL_NEW_WORKFLOW'=>'New Workflow', +'LBL_NEW_TEMPLATE'=>'Save as Template', +'LBL_CREATE_WORKFLOW_FOR'=>'Create a workflow for', +'LBL_FOR_MODULE'=>'For Module', +'LBL_FROM_TEMPLATE'=>'From Template', +'LBL_CHOOSE_A_TEMPLATE'=>'Choose a template', +'LBL_VALIDATION_MISSING_MANDATORY_FIELDS'=>'There are empty mandatory fields.', +'LBL_VALIDATION_INVALID_DATE_RANGE'=>'Start date/time is greater than the end date/time', +'LBL_ERROR_NO_WORKFLOW'=>'The workflow you requested does not exist', +'LBL_ERROR_NO_TASK'=>'The task you requested does not exist', +'LBL_ERROR_NOT_ADMIN'=>'You do not have access to this module as you are not an admin user', +'LBL_CREATE_WORKFLOW'=>'Create workflow', +'LBL_WORKFLOW_LIST'=>'Workflow List', +'LBL_AVAILABLE_WORKLIST_LIST'=>'Available Workflows', +'LBL_LOADING'=>'Loading...', +'LBL_VALIDATION_ERROR'=>'Validation Error', +'LBL_SELECT_OPTION_DOTDOTDOT'=>'Select Option...', +'LBL_WORKFLOW_NOTE_CRON_CONFIG'=>'NOTE: You should have Workflow cron script configured.', +'LBL_NO_TEMPLATES'=>'No Templates', +); + + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/language/zh_cn.lang.php new file mode 100644 index 00000000..60901316 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/language/zh_cn.lang.php @@ -0,0 +1,34 @@ + '发送邮件', +'VTEntityMethodTask' => '自定义函数', +'VTCreateTodoTask' => '创建待办事项', +'VTCreateEventTask' => '创建活动', +'LBL_EDIT_TASK'=>'编辑任务', +'LBL_EDIT_TASK_TITLE'=>'编辑现有的任务或者创建新任务', +'LBL_EDIT_WORKFLOW'=>'编辑工作流程', +'LBL_EDIT_WORKFLOW_TITLE'=>'编辑现有的工作流程或者创建新流程', +'LBL_FROM_TEMPLATE'=>'从模板', +'LBL_NEW_WORKFLOW'=>'新流程', +'LBL_NEW_TEMPLATE'=>'保存为模板', +'LBL_CREATE_WORKFLOW_FOR'=>'新的工作流程', +'LBL_FOR_MODULE'=>'的模块', +'LBL_FROM_TEMPLATE'=>'从模板', +'LBL_CHOOSE_A_TEMPLATE'=>'选择模板', +'LBL_VALIDATION_MISSING_MANDATORY_FIELDS'=>'有空必填。', +'LBL_VALIDATION_INVALID_DATE_RANGE'=>'开始的日期/时间大于结束日期/时间。', +'LBL_ERROR_NO_WORKFLOW'=>'你请求的工作流程不存在。 ', +'LBL_ERROR_NO_TASK'=>'你请求的任务不存在。', +'LBL_ERROR_NOT_ADMIN'=>'您没有访问此模块的权限。', +'LBL_CREATE_WORKFLOW'=>'创建工作流', +'LBL_WORKFLOW_LIST'=>'工作流列表', +'LBL_AVAILABLE_WORKLIST_LIST'=>'有效的工作流', +'LBL_LOADING'=>'下载...', +'LBL_VALIDATION_ERROR'=>'Validation Error', +'LBL_SELECT_OPTION_DOTDOTDOT'=>'选择项...', +'LBL_WORKFLOW_NOTE_CRON_CONFIG'=>'NOTE: You should have Workflow cron script configured.', +'LBL_NO_TEMPLATES'=>'没有模板', +); + + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/loadtemplates.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/loadtemplates.php new file mode 100644 index 00000000..3f258573 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/loadtemplates.php @@ -0,0 +1,26 @@ +loadTemplates($str); +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/modulefieldsjson.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/modulefieldsjson.php new file mode 100644 index 00000000..4fdd057d --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/modulefieldsjson.php @@ -0,0 +1,19 @@ +getFieldLabels()); + } + vtModuleTypeInfoJson($adb, $_REQUEST); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/add.png b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/add.png new file mode 100644 index 00000000..f13429ee Binary files /dev/null and b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/add.png differ diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/createeventtaskscript.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/createeventtaskscript.js new file mode 100644 index 00000000..4eee1088 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/createeventtaskscript.js @@ -0,0 +1,106 @@ +function VTCreateTodoTask($){ + + var map = fn.map; + var dict = fn.dict; + var filter = fn.filter; + var reduceR = fn.reduceR; + var parallelExecuter = fn.parallelExecuter; + var contains = fn.contains; + var concat = fn.concat; + + + function parse12HoursTime(timeStr){ + var hours; + + var match = timeStr.match(/(\d\d):(\d\d)(am|pm)/); + if(match[3]=='am'){ + hours = parseInt(match[1], 10) % 12; + }else{ + hours = parseInt(match[1], 10) % 12 + 12; + } + return hours*60+parseInt(match[2], 10); + } + + function errorDialog(message){ + alert(message); + } + + function index(arr, field){ + return dict(map(function(e){return [e[field], e];}, arr)); + } + + function handleError(fn){ + return function(status, result){ + if(status){ + fn(result); + }else{ + errorDialog('Failure:'+result); + } + }; + } + + function fillPicklist(picklistId, fieldInfo, defaultValue){ + var values = fieldInfo['type']['picklistValues']; + var select = $('#'+picklistId); + $.each(values, function(i, v){ + select.append(''); + }); + select.attr('value', defaultValue); + } + + var validateDateRange = { + init: function(){ + + }, + validator: function(){ + var result; + var successResult = [true]; + var failureResult = [false, 'invalid_date_range_message', []]; + if(this.fieldValue('startDatefield') == this.fieldValue('endDatefield')){ + var startTime = this.fieldValue('startTime'); + var endTime = this.fieldValue('endTime'); + var startDays = parseInt(this.fieldValue('startDays'), 10); + var endDays = parseInt(this.fieldValue('endDays'), 10); + var startDirection = this.fieldValue('startDirection')=="After"?1:-1; + var endDirection = this.fieldValue('endDirection')=="After"?1:-1; + var dd = endDays*endDirection - startDays*startDirection; + if(dd<0){ + result = failureResult; + }else if(dd==0){ + if(parse12HoursTime(startTime)>=parse12HoursTime(startTime)){ + result = failureResult; + }else{ + result = successResult; + } + }else{ + result = successResult; + } + }else{ + result = successResult; + } + return result; + } + }; + + var vtinst = new VtigerWebservices("webservice.php"); + vtinst.extendSession(handleError(function(result){ + $(document).ready(function(){ + //Setup the validator + validator.addValidator('validateDateRange', validateDateRange); + validator.mandatoryFields.push('eventName'); + + vtinst.describeObject('Events', handleError(function(result){ + var fields = result['fields']; + var fieldsMap = index(fields, 'name'); + fillPicklist('event_status', fieldsMap['eventstatus'], eventStatus); + $('#event_status_busyicon').hide(); + $('#event_status').show(); + + fillPicklist('event_type', fieldsMap['activitytype'], eventType); + $('#event_type_busyicon').hide(); + $('#event_type').show(); + })); + }); + })); +} +VTCreateTodoTask(jQuery); \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/createtodotaskscript.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/createtodotaskscript.js new file mode 100644 index 00000000..5bd2af01 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/createtodotaskscript.js @@ -0,0 +1,63 @@ +function VTCreateTodoTask($){ + + var map = fn.map; + var dict = fn.dict; + var filter = fn.filter; + var reduceR = fn.reduceR; + var parallelExecuter = fn.parallelExecuter; + var contains = fn.contains; + var concat = fn.concat; + + function errorDialog(message){ + alert(message); + } + + function index(arr, field){ + return dict(map(function(e){return [e[field], e];}, arr)); + } + + function handleError(fn){ + return function(status, result){ + if(status){ + fn(result); + }else{ + errorDialog('Failure:'+result); + } + } + } + + var vtinst = new VtigerWebservices("webservice.php"); + vtinst.extendSession(handleError(function(result){ + $(document).ready(function(){ + //Setup the validator + validator.mandatoryFields.push('todo'); + + vtinst.describeObject('Calendar', handleError(function(result){ + var fields = result['fields']; + var fieldsMap = index(fields, 'name'); + var eventStatusType = fieldsMap['taskstatus']; + var eventStatusValues = eventStatusType['type']['picklistValues']; + + var taskPriorityType = fieldsMap['taskpriority']; + var taskPriorityValues = taskPriorityType['type']['picklistValues']; + + var status = $('#task_status'); + $.each(eventStatusValues, function(i, v){ + status.append(''); + }); + status.attr('value', taskStatus); + $('#task_status_busyicon').hide(); + $('#task_status').show(); + + var priority = $('#task_priority'); + $.each(taskPriorityValues, function(i, v){ + priority.append(''); + }); + priority.attr('value', taskPriority); + $('#task_priority_busyicon').hide(); + $('#task_priority').show(); + })); + }); + })); +} +VTCreateTodoTask(jQuery); \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/edittaskscript.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/edittaskscript.js new file mode 100644 index 00000000..e41c15a0 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/edittaskscript.js @@ -0,0 +1,51 @@ +function edittaskscript($){ + + function NumberBox(element){ + var elementId = element.attr("id"); + var boxId = '#'+elementId+'-number-box'; + var str = ""; + for(var i = 1; i <= 30; i++){ + str += ''+(i < 10? ("0"+i) : i)+' '; + if(!(i % 5)){ + str+="
    "; + } + } + element.after(''); + element.focus(function(){ + var pos = element.position(); + $(boxId).css('display', 'block'); + $(boxId).css({ + position: 'absolute', + top: (pos.top+25)+'px' + }); + }); + + element.blur(function(){ + setTimeout(function(){$(boxId).css('display', 'none');},500); + }); + + $('.box_cel').click(function(){ + element.attr('value', parseInt($(this).text())); + }); + } + + + + $(document).ready(function(){ + validator = new VTFieldValidator($('#new_task_form')); + validator.mandatoryFields = ['summary']; + $('.time_field').timepicker(); + NumberBox($('#select_date_days')); + //UI to set the date for executing the task. + $('#check_select_date').click(function(){ + if($(this).attr('checked')){ + $('#select_date').css('display', 'block'); + }else{ + $('#select_date').css('display', 'none'); + } + }); + $('#edittask_cancel_button').click(function(){ + window.location=returnUrl; + }); + }); +} \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/editworkflowscript.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/editworkflowscript.js new file mode 100644 index 00000000..70b2e778 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/editworkflowscript.js @@ -0,0 +1,499 @@ +/*+******************************************************************************** + * 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. + ********************************************************************************/ + +function editworkflowscript($, conditions){ + var vtinst = new VtigerWebservices("webservice.php"); + var fieldValidator; + var desc = null; + + function id(v){ + return v; + } + + function map(fn, list){ + var out = []; + $.each(list, function(i, v){ + out[out.length]=fn(v); + }); + return out; + } + + function field(name){ + return function(object){ + if(typeof(object) != 'undefined') { + return object[name]; + } + }; + } + + function zip(){ + var out = []; + + var lengths = map(field('length'), arguments); + var min = reduceR(function(a,b){return a'+e.label+'';}, + opType['picklistValues']) + ); + value.replaceWith(''); + } + + function forInteger(opType, condno){ + var value = $(format("#save_condition_%s_value", condno)); + value.replaceWith(format('', condno)); + } + var functions = { + string:function(opType, condno){ + var value = $(format("#save_condition_%s_value", condno)); + value.replaceWith(format('', condno)); + }, + 'boolean': function(opType, condno){ + var value = $("#save_condition_"+condno+"_value"); + value.replaceWith( + ''); + }, + integer: forInteger, + picklist:forPicklist, + multipicklist:forPicklist + }; + var ret = functions[fieldType]; + if(ret==null){ + ret = functions['string']; + } + return ret; + } + + var format = fn.format; + + + function fillOptions(el,options){ + el.empty(); + $.each(options, function(k, v){ + el.append(''); + }); + } + + function resetFields(opType, condno){ + var ops = $("#save_condition_"+condno+"_operation"); + var selectedOperations = operations[opType.name]; + var l = dict(zip(selectedOperations, selectedOperations)); + fillOptions(ops, l); + defaultValue(opType.name)(opType, condno); + } + + + function removeCondition(condno){ + $(format("#save_condition_%s", condno)).remove(); + } + + //Convert user type into reference for consistency in describe objects + //This is done inplace + function referencify(desc){ + var fields = desc['fields']; + for(var i=0; i \ + \ + \ + \ + \ + \ + ' + ); + var fe = $("#save_condition_"+condno+"_fieldname"); + var i = 1; + fillOptions(fe, fieldLabels); + + + var fullFieldName = fe.attr("value"); + + resetFields(getFieldType(fullFieldName), condno); + + var re = $("#save_condition_"+condno+"_remove"); + re.bind("click", function(){ + removeCondition(condno); + }); + + fe.bind("change", function(){ + var select = $(this); + var condNo = select.attr("id").match(/save_condition_(\d+)_fieldname/)[1]; + var fullFieldName = $(this).attr('value'); + resetFields(getFieldType(fullFieldName), condNo); + }); + } + + var newTaskPopup = NewTaskPopup(); + $("#new_task").click(function(){ + newTaskPopup.show(); + }); + + var newTemplatePopup = NewTemplatePopup(); + $("#new_template").click(function(){ + newTemplatePopup.show(); + }); + + var condno=0; + if(conditions){ + $.each(conditions, function(i, condition){ + var fieldname = condition["fieldname"]; + addCondition(condno); + $(format("#save_condition_%s_fieldname", condno)).attr("value", fieldname); + resetFields(getFieldType(fieldname), condno); + $(format("#save_condition_%s_operation", condno)).attr("value", condition["operation"]); + $('#dump').html(condition["value"]); + var text = $('#dump').text(); + $(format("#save_condition_%s_value", condno)).attr("value", text); + condno+=1; + }); + } + + $("#save_conditions_add").bind("click", function(){ + addCondition(condno++); + }); + + $("#save_submit").bind("click", function(){ + var conditions = []; + $("#save_conditions").children().each(function(i){ + var fieldname = $(this).children(".fieldname").attr("value"); + var operation = $(this).children(".operation").attr("value"); + var value = $(this).children(".value").attr("value"); + var condition = {fieldname:fieldname, operation:operation, value:value}; + conditions[i]=condition; + }); + if(conditions.length==0){ + var out = ""; + }else{ + var out = JSON.stringify(conditions); + } + $("#save_conditions_json").attr("value", out); + }); + pageLoadingPopup.close(); + $('#save_conditions_add').show(); + })); + })); + })); + }); + +} \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/emailtaskscript.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/emailtaskscript.js new file mode 100644 index 00000000..d16ee655 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/emailtaskscript.js @@ -0,0 +1,240 @@ +/*+******************************************************************************** + * 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. + ********************************************************************************/ + +function VTEmailTask($){ + var vtinst = new VtigerWebservices("webservice.php"); + var desc = null; + var accessibleModulesInfo = null; + + var map = fn.map; + var dict = fn.dict; + var filter = fn.filter; + var reduceR = fn.reduceR; + var parallelExecuter = fn.parallelExecuter; + var contains = fn.contains; + var concat = fn.concat; + + function diff(reflist, list) { + var out = []; + $.each(list, function(i, v) { + if(contains(reflist, v)) { + out.push(v); + } + }); + return out; + } + + //Display an error message. + function errorDialog(message){ + alert(message); + } + + //This is a wrapper to handle webservice errors. + function handleError(fn){ + return function(status, result){ + if(status){ + fn(result); + }else{ + errorDialog('Failure:'+result); + } + }; + } + + //Insert text at the cursor + function insertAtCursor(element, value){ + //http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript + if (document.selection) { + element.focus(); + var sel = document.selection.createRange(); + sel.text = value; + element.focus(); + }else if (element.selectionStart || element.selectionStart == '0') { + var startPos = element.selectionStart; + var endPos = element.selectionEnd; + var scrollTop = element.scrollTop; + element.value = element.value.substring(0, startPos) + + value + + element.value.substring(endPos, + element.value.length); + element.focus(); + element.selectionStart = startPos + value.length; + element.selectionEnd = startPos + value.length; + element.scrollTop = scrollTop; + } else { + element.value += value; + element.focus(); + } + } + + //Convert user type into reference for consistency in describe objects + //This is done inplace + function referencify(desc){ + var fields = desc['fields']; + for(var i=0; i' + v + ''); + }); + + } + + $(document).ready(function(){ + vtinst.extendSession(handleError(function(result){ + vtinst.listTypes(handleError(function(accessibleModules) { + accessibleModulesInfo = accessibleModules; + + getDescribeObjects(accessibleModules, moduleName, handleError(function(modules){ + fillSelectBox('task-fieldnames', modules, moduleName); + $('#task-fieldnames-busyicon').hide(); + $('#task-fieldnames').show(); + $('#task-fieldnames').change(function(){ + var textarea = $('#save_content').get(0); + var value = '$'+$(this).attr('value'); + insertAtCursor(textarea, value); + }); + + fillSelectBox('task-emailfields', modules, moduleName, + function(e){return e['type']['name']=='email';}); + $('#task-emailfields-busyicon').hide(); + $('#task-emailfields').show(); + $('#task-emailfields').change(function(){ + var input = $($('#save_recepient').get()); + var value = '$'+$(this).attr('value'); + input.attr("value", input.attr("value")+','+value); + }); + })); + + })); + + })); + //Setup the validator + validator.mandatoryFields.push('recepient'); + validator.mandatoryFields.push('subject'); + }); +} +vtEmailTask = VTEmailTask(jQuery); diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/fieldvalidator.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/fieldvalidator.js new file mode 100644 index 00000000..17768d10 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/fieldvalidator.js @@ -0,0 +1,88 @@ +function MessageBoxPopup(){ + function center(el){ + el.css({position: 'absolute'}); + el.width("400px"); + el.height("110px"); + placeAtCenter(el.get(0)); + } + + function close(){ + jQuery('#error_message_box').css('display', 'none'); + } + + function show(module){ + if(typeof('VtigerJS_DialogBox') != 'undefined') VtigerJS_DialogBox.unblock(); + jQuery('#error_message_box').css('display', 'block'); + center(jQuery('#error_message_box')); + } + + jQuery('#error_message_box_close').click(close); + jQuery('#error_message_box_cancel').click(close); + return { + close:close,show:show + }; +} + + +var validateMandatoryFields = { + init: function(){ + this.mandatoryFields = []; + }, + validator: function (){ + var emptyFields = []; + var result; + var mandatoryFields = this.mandatoryFields; + for(var i = 0; i < mandatoryFields.length; i++){ + var fieldName = mandatoryFields[i]; + if(this.fieldValue(fieldName)==""){ + emptyFields.push(fieldName); + } + } + if(emptyFields.length!=0){ + result = [false, 'empty_fields_message', emptyFields]; + }else{ + result = [true]; + } + return result; + } +}; + +var VTFieldValidatorPrototype = { + validate: function(){ + var isValid = true; + var validators = this.validators; + for(var i = 0; i < validators.length; i++){ + var validator = validators[i]; + var result = validator.call(this); + if(result[0]==false){ + jQuery('#'+result[1]).css('display', 'block'); + isValid = false; + } + } + if(!isValid){ + this.messageBoxPopup.show(); + } + return isValid; + }, + addValidator: function(name, validator){ + validator.init.call(this); + this.validators.push(validator.validator); + }, + fieldValue: function(fieldName){ + return this.form.find('[name='+fieldName+']').val(); + } +}; + +function VTFieldValidator(form){ + var _this = this; + _this.form = form; + _this.messageBoxPopup = MessageBoxPopup(); + form.submit(function(){ + return _this.validate(); + }); + _this.validators = []; + _this.addValidator('mandatoryFields', validateMandatoryFields); +} + +VTFieldValidator.prototype = VTFieldValidatorPrototype; + diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/functional.js b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/functional.js new file mode 100644 index 00000000..a5473a2b --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/resources/functional.js @@ -0,0 +1,162 @@ +function functional($){ + return { + + /** + * Test: + * fn.format("Hello %s", "world") == "Hello world" + */ + format: function(){ + var i=1; + var fmtStr = arguments[0]; + var args = arguments; + return fmtStr.replace(/%s/g,function(){return args[i++];}) + }, + + addStylesheet: function(url){ + /*From: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS*/ + var headID = document.getElementsByTagName("head")[0]; + var cssNode = document.createElement('link'); + cssNode.type = 'text/css'; + cssNode.rel = 'stylesheet'; + cssNode.href = url; + cssNode.media = 'screen'; + headID.appendChild(cssNode); + }, + + id: function(v){ + return v; + }, + + map: function(fn, list){ + var out = []; + $.each(list, function(i, v){ + out[out.length]=fn(v); + }); + return out; + }, + + field: function(name){ + return function(object){ + return object[name]; + } + }, + + zip: function(){ + var out = []; + + var lengths = map(field('length'), arguments); + var min = reduceR(function(a,b){return aarguments.length){ + nparams = arguments.length; + } + + var args = []; + for(var i=0;i)[^>]*$|^#(\w+)$/, + +// Is it a simple selector + isSimple = /^.[^:#\[\.]*$/, + +// Will speed up references to undefined, and allows munging its name. + undefined; + +jQuery.fn = jQuery.prototype = { + init: function( selector, context ) { + // Make sure that a selection was provided + selector = selector || document; + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this[0] = selector; + this.length = 1; + return this; + } + // Handle HTML strings + if ( typeof selector == "string" ) { + // Are we dealing with HTML string or an ID? + var match = quickExpr.exec( selector ); + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) + selector = jQuery.clean( [ match[1] ], context ); + + // HANDLE: $("#id") + else { + var elem = document.getElementById( match[3] ); + + // Make sure an element was located + if ( elem ){ + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id != match[3] ) + return jQuery().find( selector ); + + // Otherwise, we inject the element directly into the jQuery object + return jQuery( elem ); + } + selector = []; + } + + // HANDLE: $(expr, [context]) + // (which is just equivalent to: $(content).find(expr) + } else + return jQuery( context ).find( selector ); + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) + return jQuery( document )[ jQuery.fn.ready ? "ready" : "load" ]( selector ); + + return this.setArray(jQuery.makeArray(selector)); + }, + + // The current version of jQuery being used + jquery: "1.2.6", + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + // The number of elements contained in the matched element set + length: 0, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == undefined ? + + // Return a 'clean' array + jQuery.makeArray( this ) : + + // Return just the object + this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + // Build a new jQuery matched element set + var ret = jQuery( elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Force the current matched set of elements to become + // the specified array of elements (destroying the stack in the process) + // You should use pushStack() in order to do this, but maintain the stack + setArray: function( elems ) { + // Resetting the length to 0, then using the native Array push + // is a super-fast way to populate an object with array-like properties + this.length = 0; + Array.prototype.push.apply( this, elems ); + + return this; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + var ret = -1; + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem && elem.jquery ? elem[0] : elem + , this ); + }, + + attr: function( name, value, type ) { + var options = name; + + // Look for the case where we're accessing a style value + if ( name.constructor == String ) + if ( value === undefined ) + return this[0] && jQuery[ type || "attr" ]( this[0], name ); + + else { + options = {}; + options[ name ] = value; + } + + // Check to see if we're setting style values + return this.each(function(i){ + // Set all the styles + for ( name in options ) + jQuery.attr( + type ? + this.style : + this, + name, jQuery.prop( this, options[ name ], type, i, name ) + ); + }); + }, + + css: function( key, value ) { + // ignore negative width and height values + if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 ) + value = undefined; + return this.attr( key, value, "curCSS" ); + }, + + text: function( text ) { + if ( typeof text != "object" && text != null ) + return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); + + var ret = ""; + + jQuery.each( text || this, function(){ + jQuery.each( this.childNodes, function(){ + if ( this.nodeType != 8 ) + ret += this.nodeType != 1 ? + this.nodeValue : + jQuery.fn.text( [ this ] ); + }); + }); + + return ret; + }, + + wrapAll: function( html ) { + if ( this[0] ) + // The elements to wrap the target around + jQuery( html, this[0].ownerDocument ) + .clone() + .insertBefore( this[0] ) + .map(function(){ + var elem = this; + + while ( elem.firstChild ) + elem = elem.firstChild; + + return elem; + }) + .append(this); + + return this; + }, + + wrapInner: function( html ) { + return this.each(function(){ + jQuery( this ).contents().wrapAll( html ); + }); + }, + + wrap: function( html ) { + return this.each(function(){ + jQuery( this ).wrapAll( html ); + }); + }, + + append: function() { + return this.domManip(arguments, true, false, function(elem){ + if (this.nodeType == 1) + this.appendChild( elem ); + }); + }, + + prepend: function() { + return this.domManip(arguments, true, true, function(elem){ + if (this.nodeType == 1) + this.insertBefore( elem, this.firstChild ); + }); + }, + + before: function() { + return this.domManip(arguments, false, false, function(elem){ + this.parentNode.insertBefore( elem, this ); + }); + }, + + after: function() { + return this.domManip(arguments, false, true, function(elem){ + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + }, + + end: function() { + return this.prevObject || jQuery( [] ); + }, + + find: function( selector ) { + var elems = jQuery.map(this, function(elem){ + return jQuery.find( selector, elem ); + }); + + return this.pushStack( /[^+>] [^+>]/.test( selector ) || selector.indexOf("..") > -1 ? + jQuery.unique( elems ) : + elems ); + }, + + clone: function( events ) { + // Do the clone + var ret = this.map(function(){ + if ( jQuery.browser.msie && !jQuery.isXMLDoc(this) ) { + // IE copies events bound via attachEvent when + // using cloneNode. Calling detachEvent on the + // clone will also remove the events from the orignal + // In order to get around this, we use innerHTML. + // Unfortunately, this means some modifications to + // attributes in IE that are actually only stored + // as properties will not be copied (such as the + // the name attribute on an input). + var clone = this.cloneNode(true), + container = document.createElement("div"); + container.appendChild(clone); + return jQuery.clean([container.innerHTML])[0]; + } else + return this.cloneNode(true); + }); + + // Need to set the expando to null on the cloned set if it exists + // removeData doesn't work here, IE removes it from the original as well + // this is primarily for IE but the data expando shouldn't be copied over in any browser + var clone = ret.find("*").andSelf().each(function(){ + if ( this[ expando ] != undefined ) + this[ expando ] = null; + }); + + // Copy the events from the original to the clone + if ( events === true ) + this.find("*").andSelf().each(function(i){ + if (this.nodeType == 3) + return; + var events = jQuery.data( this, "events" ); + + for ( var type in events ) + for ( var handler in events[ type ] ) + jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data ); + }); + + // Return the cloned set + return ret; + }, + + filter: function( selector ) { + return this.pushStack( + jQuery.isFunction( selector ) && + jQuery.grep(this, function(elem, i){ + return selector.call( elem, i ); + }) || + + jQuery.multiFilter( selector, this ) ); + }, + + not: function( selector ) { + if ( selector.constructor == String ) + // test special case where just one selector is passed in + if ( isSimple.test( selector ) ) + return this.pushStack( jQuery.multiFilter( selector, this, true ) ); + else + selector = jQuery.multiFilter( selector, this ); + + var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType; + return this.filter(function() { + return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector; + }); + }, + + add: function( selector ) { + return this.pushStack( jQuery.unique( jQuery.merge( + this.get(), + typeof selector == 'string' ? + jQuery( selector ) : + jQuery.makeArray( selector ) + ))); + }, + + is: function( selector ) { + return !!selector && jQuery.multiFilter( selector, this ).length > 0; + }, + + hasClass: function( selector ) { + return this.is( "." + selector ); + }, + + val: function( value ) { + if ( value == undefined ) { + + if ( this.length ) { + var elem = this[0]; + + // We need to handle select boxes special + if ( jQuery.nodeName( elem, "select" ) ) { + var index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type == "select-one"; + + // Nothing was selected + if ( index < 0 ) + return null; + + // Loop through all the selected options + for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { + var option = options[ i ]; + + if ( option.selected ) { + // Get the specifc value for the option + value = jQuery.browser.msie && !option.attributes.value.specified ? option.text : option.value; + + // We don't need an array for one selects + if ( one ) + return value; + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + + // Everything else, we just grab the value + } else + return (this[0].value || "").replace(/\r/g, ""); + + } + + return undefined; + } + + if( value.constructor == Number ) + value += ''; + + return this.each(function(){ + if ( this.nodeType != 1 ) + return; + + if ( value.constructor == Array && /radio|checkbox/.test( this.type ) ) + this.checked = (jQuery.inArray(this.value, value) >= 0 || + jQuery.inArray(this.name, value) >= 0); + + else if ( jQuery.nodeName( this, "select" ) ) { + var values = jQuery.makeArray(value); + + jQuery( "option", this ).each(function(){ + this.selected = (jQuery.inArray( this.value, values ) >= 0 || + jQuery.inArray( this.text, values ) >= 0); + }); + + if ( !values.length ) + this.selectedIndex = -1; + + } else + this.value = value; + }); + }, + + html: function( value ) { + return value == undefined ? + (this[0] ? + this[0].innerHTML : + null) : + this.empty().append( value ); + }, + + replaceWith: function( value ) { + return this.after( value ).remove(); + }, + + eq: function( i ) { + return this.slice( i, i + 1 ); + }, + + slice: function() { + return this.pushStack( Array.prototype.slice.apply( this, arguments ) ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function(elem, i){ + return callback.call( elem, i, elem ); + })); + }, + + andSelf: function() { + return this.add( this.prevObject ); + }, + + data: function( key, value ){ + var parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + if ( data === undefined && this.length ) + data = jQuery.data( this[0], key ); + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } else + return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){ + jQuery.data( this, key, value ); + }); + }, + + removeData: function( key ){ + return this.each(function(){ + jQuery.removeData( this, key ); + }); + }, + + domManip: function( args, table, reverse, callback ) { + var clone = this.length > 1, elems; + + return this.each(function(){ + if ( !elems ) { + elems = jQuery.clean( args, this.ownerDocument ); + + if ( reverse ) + elems.reverse(); + } + + var obj = this; + + if ( table && jQuery.nodeName( this, "table" ) && jQuery.nodeName( elems[0], "tr" ) ) + obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") ); + + var scripts = jQuery( [] ); + + jQuery.each(elems, function(){ + var elem = clone ? + jQuery( this ).clone( true )[0] : + this; + + // execute all scripts after the elements have been injected + if ( jQuery.nodeName( elem, "script" ) ) + scripts = scripts.add( elem ); + else { + // Remove any inner scripts for later evaluation + if ( elem.nodeType == 1 ) + scripts = scripts.add( jQuery( "script", elem ).remove() ); + + // Inject the elements into the document + callback.call( obj, elem ); + } + }); + + scripts.each( evalScript ); + }); + } +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +function evalScript( i, elem ) { + if ( elem.src ) + jQuery.ajax({ + url: elem.src, + async: false, + dataType: "script" + }); + + else + jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); + + if ( elem.parentNode ) + elem.parentNode.removeChild( elem ); +} + +function now(){ + return +new Date; +} + +jQuery.extend = jQuery.fn.extend = function() { + // copy reference to target object + var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options; + + // Handle a deep copy situation + if ( target.constructor == Boolean ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target != "object" && typeof target != "function" ) + target = {}; + + // extend jQuery itself if only one argument is passed + if ( length == i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) + // Extend the base object + for ( var name in options ) { + var src = target[ name ], copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) + continue; + + // Recurse if we're merging object values + if ( deep && copy && typeof copy == "object" && !copy.nodeType ) + target[ name ] = jQuery.extend( deep, + // Never move original objects, clone them + src || ( copy.length != null ? [ ] : { } ) + , copy ); + + // Don't bring in undefined values + else if ( copy !== undefined ) + target[ name ] = copy; + + } + + // Return the modified object + return target; +}; + +var expando = "jQuery" + now(), uuid = 0, windowData = {}, + // exclude the following css properties to add px + exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, + // cache defaultView + defaultView = document.defaultView || {}; + +jQuery.extend({ + noConflict: function( deep ) { + window.$ = _$; + + if ( deep ) + window.jQuery = _jQuery; + + return jQuery; + }, + + // See test/unit/core.js for details concerning this function. + isFunction: function( fn ) { + return !!fn && typeof fn != "string" && !fn.nodeName && + fn.constructor != Array && /^[\s[]?function/.test( fn + "" ); + }, + + // check if an element is in a (or is an) XML document + isXMLDoc: function( elem ) { + return elem.documentElement && !elem.body || + elem.tagName && elem.ownerDocument && !elem.ownerDocument.body; + }, + + // Evalulates a script in a global context + globalEval: function( data ) { + data = jQuery.trim( data ); + + if ( data ) { + // Inspired by code by Andrea Giammarchi + // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html + var head = document.getElementsByTagName("head")[0] || document.documentElement, + script = document.createElement("script"); + + script.type = "text/javascript"; + if ( jQuery.browser.msie ) + script.text = data; + else + script.appendChild( document.createTextNode( data ) ); + + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709). + head.insertBefore( script, head.firstChild ); + head.removeChild( script ); + } + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase(); + }, + + cache: {}, + + data: function( elem, name, data ) { + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ]; + + // Compute a unique ID for the element + if ( !id ) + id = elem[ expando ] = ++uuid; + + // Only generate the data cache if we're + // trying to access or manipulate it + if ( name && !jQuery.cache[ id ] ) + jQuery.cache[ id ] = {}; + + // Prevent overriding the named cache with undefined values + if ( data !== undefined ) + jQuery.cache[ id ][ name ] = data; + + // Return the named cache data, or the ID for the element + return name ? + jQuery.cache[ id ][ name ] : + id; + }, + + removeData: function( elem, name ) { + elem = elem == window ? + windowData : + elem; + + var id = elem[ expando ]; + + // If we want to remove a specific section of the element's data + if ( name ) { + if ( jQuery.cache[ id ] ) { + // Remove the section of cache data + delete jQuery.cache[ id ][ name ]; + + // If we've removed all the data, remove the element's cache + name = ""; + + for ( name in jQuery.cache[ id ] ) + break; + + if ( !name ) + jQuery.removeData( elem ); + } + + // Otherwise, we want to remove all of the element's data + } else { + // Clean up the element expando + try { + delete elem[ expando ]; + } catch(e){ + // IE has trouble directly removing the expando + // but it's ok with using removeAttribute + if ( elem.removeAttribute ) + elem.removeAttribute( expando ); + } + + // Completely remove the data cache + delete jQuery.cache[ id ]; + } + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, length = object.length; + + if ( args ) { + if ( length == undefined ) { + for ( name in object ) + if ( callback.apply( object[ name ], args ) === false ) + break; + } else + for ( ; i < length; ) + if ( callback.apply( object[ i++ ], args ) === false ) + break; + + // A special, fast, case for the most common use of each + } else { + if ( length == undefined ) { + for ( name in object ) + if ( callback.call( object[ name ], name, object[ name ] ) === false ) + break; + } else + for ( var value = object[0]; + i < length && callback.call( value, i, value ) !== false; value = object[++i] ){} + } + + return object; + }, + + prop: function( elem, value, type, i, name ) { + // Handle executable functions + if ( jQuery.isFunction( value ) ) + value = value.call( elem, i ); + + // Handle passing in a number to a CSS property + return value && value.constructor == Number && type == "curCSS" && !exclude.test( name ) ? + value + "px" : + value; + }, + + className: { + // internal only, use addClass("class") + add: function( elem, classNames ) { + jQuery.each((classNames || "").split(/\s+/), function(i, className){ + if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) ) + elem.className += (elem.className ? " " : "") + className; + }); + }, + + // internal only, use removeClass("class") + remove: function( elem, classNames ) { + if (elem.nodeType == 1) + elem.className = classNames != undefined ? + jQuery.grep(elem.className.split(/\s+/), function(className){ + return !jQuery.className.has( classNames, className ); + }).join(" ") : + ""; + }, + + // internal only, use hasClass("class") + has: function( elem, className ) { + return jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1; + } + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var old = {}; + // Remember the old values, and insert the new ones + for ( var name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + callback.call( elem ); + + // Revert the old values + for ( var name in options ) + elem.style[ name ] = old[ name ]; + }, + + css: function( elem, name, force ) { + if ( name == "width" || name == "height" ) { + var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ]; + + function getWH() { + val = name == "width" ? elem.offsetWidth : elem.offsetHeight; + var padding = 0, border = 0; + jQuery.each( which, function() { + padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; + border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; + }); + val -= Math.round(padding + border); + } + + if ( jQuery(elem).is(":visible") ) + getWH(); + else + jQuery.swap( elem, props, getWH ); + + return Math.max(0, val); + } + + return jQuery.curCSS( elem, name, force ); + }, + + curCSS: function( elem, name, force ) { + var ret, style = elem.style; + + // A helper method for determining if an element's values are broken + function color( elem ) { + if ( !jQuery.browser.safari ) + return false; + + // defaultView is cached + var ret = defaultView.getComputedStyle( elem, null ); + return !ret || ret.getPropertyValue("color") == ""; + } + + // We need to handle opacity special in IE + if ( name == "opacity" && jQuery.browser.msie ) { + ret = jQuery.attr( style, "opacity" ); + + return ret == "" ? + "1" : + ret; + } + // Opera sometimes will give the wrong display answer, this fixes it, see #2037 + if ( jQuery.browser.opera && name == "display" ) { + var save = style.outline; + style.outline = "0 solid black"; + style.outline = save; + } + + // Make sure we're using the right name for getting the float value + if ( name.match( /float/i ) ) + name = styleFloat; + + if ( !force && style && style[ name ] ) + ret = style[ name ]; + + else if ( defaultView.getComputedStyle ) { + + // Only "float" is needed here + if ( name.match( /float/i ) ) + name = "float"; + + name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase(); + + var computedStyle = defaultView.getComputedStyle( elem, null ); + + if ( computedStyle && !color( elem ) ) + ret = computedStyle.getPropertyValue( name ); + + // If the element isn't reporting its values properly in Safari + // then some display: none elements are involved + else { + var swap = [], stack = [], a = elem, i = 0; + + // Locate all of the parent display: none elements + for ( ; a && color(a); a = a.parentNode ) + stack.unshift(a); + + // Go through and make them visible, but in reverse + // (It would be better if we knew the exact display type that they had) + for ( ; i < stack.length; i++ ) + if ( color( stack[ i ] ) ) { + swap[ i ] = stack[ i ].style.display; + stack[ i ].style.display = "block"; + } + + // Since we flip the display style, we have to handle that + // one special, otherwise get the value + ret = name == "display" && swap[ stack.length - 1 ] != null ? + "none" : + ( computedStyle && computedStyle.getPropertyValue( name ) ) || ""; + + // Finally, revert the display styles back + for ( i = 0; i < swap.length; i++ ) + if ( swap[ i ] != null ) + stack[ i ].style.display = swap[ i ]; + } + + // We should always get a number back from opacity + if ( name == "opacity" && ret == "" ) + ret = "1"; + + } else if ( elem.currentStyle ) { + var camelCase = name.replace(/\-(\w)/g, function(all, letter){ + return letter.toUpperCase(); + }); + + ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) { + // Remember the original values + var left = style.left, rsLeft = elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + elem.runtimeStyle.left = elem.currentStyle.left; + style.left = ret || 0; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + elem.runtimeStyle.left = rsLeft; + } + } + + return ret; + }, + + clean: function( elems, context ) { + var ret = []; + context = context || document; + // !context.createElement fails in IE with an error but returns typeof 'object' + if (typeof context.createElement == 'undefined') + context = context.ownerDocument || context[0] && context[0].ownerDocument || document; + + jQuery.each(elems, function(i, elem){ + if ( !elem ) + return; + + if ( elem.constructor == Number ) + elem += ''; + + // Convert html string into DOM nodes + if ( typeof elem == "string" ) { + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ + return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? + all : + front + ">"; + }); + + // Trim whitespace, otherwise indexOf won't work as expected + var tags = jQuery.trim( elem ).toLowerCase(), div = context.createElement("div"); + + var wrap = + // option or optgroup + !tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + tags.match(/^<(thead|tbody|tfoot|colg|cap)/) && + [ 1, "", "
    " ] || + + !tags.indexOf("", "" ] || + + // matched above + (!tags.indexOf("", "" ] || + + !tags.indexOf("", "" ] || + + // IE can't serialize and + Return + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/savetemplate.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/savetemplate.php new file mode 100644 index 00000000..4b5c489c --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/savetemplate.php @@ -0,0 +1,46 @@ +name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $title = $request['title']; + $workflowId = $request['workflow_id']; + $wfs = new VTworkflowManager($adb); + $workflow = $wfs->retrieve($workflowId); + $tm = new VTWorkflowTemplateManager($adb); + $tpl = $tm->newTemplate($title, $workflow); + $tm->saveTemplate($tpl); + $returnUrl = $request['return_url']; + ?> + + Return + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/saveworkflow.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/saveworkflow.php new file mode 100644 index 00000000..a4d49b4c --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/saveworkflow.php @@ -0,0 +1,68 @@ +name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $description = $request["description"]; + $moduleName = $request["module_name"]; + $conditions = $request["conditions"]; + $taskId = $request["task_id"]; + $saveType=$request["save_type"]; + $executionCondition = $request['execution_condition']; + $wm = new VTWorkflowManager($adb); + if($saveType=='new'){ + $wf = $wm->newWorkflow($moduleName); + $wf->description = $description; + $wf->test = $conditions; + $wf->taskId = $taskId; + $wf->executionConditionAsLabel($executionCondition); + $wm->save($wf); + }else if($saveType=='edit'){ + $wf = $wm->retrieve($request["workflow_id"]); + $wf->description = $description; + $wf->test = $conditions; + $wf->taskId = $taskId; + $wf->executionConditionAsLabel($executionCondition); + $wm->save($wf); + }else{ + throw new Exception(); + } + if(isset($request["return_url"])){ + $returnUrl=$request["return_url"]; + }else{ + $returnUrl=$module->editWorkflowUrl($wf->id); + } + ?> + + Return + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/sortfieldsjson.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/sortfieldsjson.php new file mode 100644 index 00000000..55e83270 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/sortfieldsjson.php @@ -0,0 +1,17 @@ +sortby_fields); + } + vtSortFieldsJson($_REQUEST); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasklist.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasklist.php new file mode 100644 index 00000000..de7ea0f2 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasklist.php @@ -0,0 +1,51 @@ +name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $smarty = new vtigerCRM_Smarty(); + $tm = new VTTaskManager($adb); + $smarty->assign("tasks", $tm->getTasks()); + $smarty->assign("moduleNames", array("Contacts", "Applications")); + $smarty->assign("taskTypes", array("VTEmailTask", "VTDummyTask")); + $smarty->assign("returnUrl", $requestUrl); + + $smarty->assign("MOD", return_module_language($current_language,'Settings')); + $smarty->assign("APP", $app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE_NAME", $module->label); + $smarty->assign("PAGE_NAME", 'Task List'); + $smarty->assign("PAGE_TITLE", 'List available tasks'); + $smarty->assign("moduleName", $moduleName); + $smarty->display("{$module->name}/ListTasks.tpl"); + } + vtDisplayTaskList($adb, $_SERVER["REQUEST_URI"], $current_language); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateEntityTask.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateEntityTask.inc new file mode 100644 index 00000000..d12c03cc --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateEntityTask.inc @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateEventTask.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateEventTask.inc new file mode 100644 index 00000000..0e01a70c --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateEventTask.inc @@ -0,0 +1,116 @@ +retrieveCurrentUserInfoFromFile(1); + global $current_user; + $this->originalUser = $current_user; + $current_user = $user; + return $user; + } + + public function doTask($entityData){ + global $adb, $current_user; + $userId = $entityData->get('assigned_user_id'); + if($userId===null){ + $userId = vtws_getWebserviceEntityId('Users', 1);; + } + + $startDate = $this->calculateDate($entityData, $this->startDays, + $this->startDirection, $this->startDatefield); + $endDate = $this->calculateDate($entityData, $this->endDays, + $this->endDirection, $this->endDatefield); + + $fields = array( + 'activitytype'=>$this->eventType, + 'description'=>$this->description, + 'subject'=>$this->eventName, + 'taskpriority'=>$this->priority, + 'eventstatus'=>$this->status, + 'assigned_user_id'=>$userId, + 'time_start'=>self::conv12to24hour($this->startTime), + 'date_start'=>$startDate, + 'time_end'=>self::conv12to24hour($this->endTime), + 'due_date'=>$endDate, + 'visibility'=>'all', + 'taskstatus'=>'', + 'duration_hours'=>'' + ); + + $moduleName = $entityData->getModuleName(); + $adminUser = $this->getAdmin(); + $id = $entityData->getId(); + if($moduleName=='Contacts'){ + $fields['contact_id'] = $id; + }else{ + $data = vtws_describe('Calendar', $adminUser); + $fieldInfo = $data['fields']; + foreach($fieldInfo as $field){ + if($field['name']=='parent_id'){ + $parentIdField = $field; + } + } + $refersTo = $parentIdField['type']['refersTo']; + + if(in_array($moduleName, $refersTo)){ + $fields['parent_id'] = $id; + } + } + + vtws_create('Events', $fields, $adminUser); + global $current_user; + $current_user = $this->originalUser; + } + + private function calculateDate($entityData, $days, $direction, $datefield){ + $baseDate = $entityData->get($datefield); + preg_match('/\d\d\d\d-\d\d-\d\d/', $baseDate, $match); + $baseDate = strtotime($match[0]); + $date = strftime('%Y-%m-%d', $baseDate+$days*24*60*60* + ($direction=='Before'?-1:1)); + return $date; + } + + static function conv12to24hour($timeStr){ + $arr = array(); + preg_match('/(\d{1,2}):(\d{1,2})(am|pm)/', $timeStr, $arr); + if($arr[3]=='am'){ + $hours = ((int)$arr[1]) % 12; + }else{ + $hours = ((int)$arr[1]) % 12 + 12; + } + return str_pad($hours, 2, '0', STR_PAD_LEFT).':'.str_pad($arr[2], 2, '0', STR_PAD_LEFT); + } +} +?> diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc new file mode 100644 index 00000000..e52fbadc --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTCreateTodoTask.inc @@ -0,0 +1,99 @@ +retrieveCurrentUserInfoFromFile(1); + global $current_user; + $this->originalUser = $current_user; + $current_user = $user; + return $user; + } + + public function doTask($entityData){ + global $adb, $current_user; + $userId = $entityData->get('assigned_user_id'); + if($userId===null){ + $userId = vtws_getWebserviceEntityId('Users', 1);; + } + + $baseDate = $entityData->get($this->datefield); + preg_match('/\d\d\d\d-\d\d-\d\d/', $baseDate, $match); + $baseDate = strtotime($match[0]); + $date = strftime('%Y-%m-%d', $baseDate+$this->days*24*60*60*($this->directions=='Before'?-1:1)); + $fields = array( + 'activitytype'=>'Task', + 'description'=>$this->description, + 'subject'=>$this->todo, + 'taskpriority'=>$this->priority, + 'taskstatus'=>$this->status, + 'assigned_user_id'=>$userId, + 'time_start'=>self::conv12to24hour($this->time), + 'sendnotification'=>$this->sendNotification!=''?1:0, + 'date_start'=>$date, + 'due_date'=>$date, + 'visibility'=>'all', + 'eventstatus'=>'' + ); + $moduleName = $entityData->getModuleName(); + $adminUser = $this->getAdmin(); + $id = $entityData->getId(); + if($moduleName=='Contacts'){ + $fields['contact_id'] = $id; + }else{ + $data = vtws_describe('Calendar', $adminUser); + $fieldInfo = $data['fields']; + foreach($fieldInfo as $field){ + if($field['name']=='parent_id'){ + $parentIdField = $field; + } + } + $refersTo = $parentIdField['type']['refersTo']; + + if(in_array($moduleName, $refersTo)){ + $fields['parent_id'] = $id; + } + } + + vtws_create('Calendar', $fields, $adminUser); + global $current_user; + $current_user = $this->originalUser; + } + + static function conv12to24hour($timeStr){ + $arr = array(); + preg_match('/(\d{1,2}):(\d{1,2})(am|pm)/', $timeStr, $arr); + if($arr[3]=='am'){ + $hours = ((int)$arr[1]) % 12; + }else{ + $hours = ((int)$arr[1]) % 12 + 12; + } + return str_pad($hours, 2, '0', STR_PAD_LEFT).':'.str_pad($arr[2], 2, '0', STR_PAD_LEFT); + } +} +?> diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTDummyTask.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTDummyTask.inc new file mode 100644 index 00000000..b936cd74 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTDummyTask.inc @@ -0,0 +1,19 @@ +statement; + echo "This is a dummy workflow task with $statement"; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTEmailTask.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTEmailTask.inc new file mode 100644 index 00000000..a47e13e0 --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTEmailTask.inc @@ -0,0 +1,46 @@ +query("select user_name, email1, email2 from vtiger_users where id=1"); + $from_email = $adb->query_result($result,0,'email1'); + $from_name = $adb->query_result($result,0,'user_name'); + + $admin = $util->adminUser(); + $module = $entity->getModuleName(); + + $entityCache = new VTEntityCache($admin); + + $et = new VTSimpleTemplate($this->recepient); + $to_email = $et->render($entityCache, $entity->getId()); + + $st = new VTSimpleTemplate($this->subject); + $subject = $st->render($entityCache, $entity->getId()); + $ct = new VTSimpleTemplate($this->content); + $content = $ct->render($entityCache, $entity->getId()); + send_mail($module,$to_email,$from_name,$from_email,$subject,$content); + + $util->revertUser(); + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTEntityMethodTask.inc b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTEntityMethodTask.inc new file mode 100644 index 00000000..ad4d4fbd --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/tasks/VTEntityMethodTask.inc @@ -0,0 +1,22 @@ +executeMethod($entityData, $this->methodName); + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/templatesformodulejson.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/templatesformodulejson.php new file mode 100644 index 00000000..4bcbbf7d --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/templatesformodulejson.php @@ -0,0 +1,23 @@ +getTemplatesForModule($moduleName); + $arr = array(); + foreach($templates as $template){ + $arr[] = array("title"=>$template->title, 'id'=>$template->id); + } + echo Zend_Json::encode($arr); +} +vtTemplatesForModuleJson($adb, $_REQUEST); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/com_vtiger_workflow/workflowlist.php b/oss/vtiger/trunk/modules/com_vtiger_workflow/workflowlist.php new file mode 100644 index 00000000..9dd4e99b --- /dev/null +++ b/oss/vtiger/trunk/modules/com_vtiger_workflow/workflowlist.php @@ -0,0 +1,74 @@ +pquery($sql,array($modules_not_supported))); + $modules = array(); + foreach($it as $row){ + $modules[] = $row->name; + } + return $modules; +} + +function vtDisplayWorkflowList($adb, $request, $requestUrl, $app_strings, $current_language){ + global $theme; + $image_path = "themes/$theme/images/"; + + $module = new VTWorkflowApplication("workflowlist"); + $util = new VTWorkflowUtils(); + $mod = return_module_language($current_language, $module->name); + + if(!$util->checkAdminAccess()){ + $errorUrl = $module->errorPageUrl($mod['LBL_ERROR_NOT_ADMIN']); + $util->redirectTo($errorUrl, $mod['LBL_ERROR_NOT_ADMIN']); + return; + } + + $smarty = new vtigerCRM_Smarty(); + $wfs = new VTWorkflowManager($adb); + $smarty->assign("moduleNames", vtGetModules($adb)); + $smarty->assign("returnUrl", $requestUrl); + + $listModule = $request["list_module"]; + $smarty->assign("listModule", $listModule); + if($listModule==null || strtolower($listModule)=="all"){ + $smarty->assign("workflows", $wfs->getWorkflows()); + }else{ + $smarty->assign("workflows", $wfs->getWorkflowsForModule($listModule)); + } + + $smarty->assign("MOD",array_merge( + return_module_language($current_language,'Settings'), + return_module_language($current_language, $module->name))); + $smarty->assign("APP", $app_strings); + $smarty->assign("THEME", $theme); + $smarty->assign("IMAGE_PATH",$image_path); + $smarty->assign("MODULE_NAME", $module->label); + $smarty->assign("PAGE_NAME", $mod['LBL_WORKFLOW_LIST']); + $smarty->assign("PAGE_TITLE", $mod['LBL_AVAILABLE_WORKLIST_LIST']); + $smarty->assign("module", $module); + $smarty->display("{$module->name}/ListWorkflows.tpl"); +} +vtDisplayWorkflowList($adb, $_REQUEST, $_SERVER["REQUEST_URI"], $app_strings, $current_language); +?> diff --git a/oss/vtiger/trunk/modules/squirrelmail-1.4.4/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/squirrelmail-1.4.4/language/zh_cn.lang.php new file mode 100644 index 00000000..be181109 --- /dev/null +++ b/oss/vtiger/trunk/modules/squirrelmail-1.4.4/language/zh_cn.lang.php @@ -0,0 +1,49 @@ + 'WebMails', + 'LBL_EMAILS_TITLE' => 'Emails', + 'LBL_MODULE_TITLE' => 'WebMails:Home', + 'LNK_SELECT_ALL' => '全选', + 'LNK_UNSELECT_ALL' => '取消全选', + 'LNK_OPTIONS' => '选项', + 'LBL_VIEWING_MESSAGES' => '浏览信件', + 'LBL_TOTAL' => '总计', + 'LBL_WEBMAILS_LIST' => 'WebMails列表', + 'LBL_FETCH_MY_MAILS' => '接收外部信件', + 'LBL_ADD_TO_VTIGER_CRM' => '新增到CRM系统', + 'LBL_READ' => '已读', + 'LBL_UNREAD' => '未读', + 'LBL_DELETE' => '删除', + 'LBL_SUBJECT' => '主题', + 'LBL_DATE' => '日期', + 'LBL_FROM' => '发件人', + 'LNK_MESSAGE_LIST' => '信件列表', + 'LNK_DELETE' => '删除', + 'LNK_PREVIOUS' => '上一封', + 'LNK_NEXT' => '下一封', + 'LNK_REPLY' => '回复', + 'LNK_REPLY_ALL' => '回复所有', + 'LNK_VIEW_PRINTABLE_VERSION' => '查看打印版本', + 'LBL_ATTACHMENTS' => '附件', + 'LBL_TO' => '收件人', + 'LBL_CC' => '抄送', + 'LBL_BCC' => '密送', + 'LBL_TO_OR_CC' => '收件人或者抄送', + 'LBL_PRIORITY' => '优先级', + 'LNK_NEW' => '撰写', + 'LNK_DONE' => '完成', + 'LBL_OPTIONS' => '选项', + 'LBL_MESSAGE_HIGHLIGHTING' => '已选信件', + 'LBL_NO_HIGHLIGHTING_IS_DEFINED' => '没有选择信件', + 'LBL_IDENTIFYING_NAME' => '识别名称', + 'LBL_COLOR' => '颜色', + 'LBL_OTHER' => '其它', + 'LBL_MATCHES' => '匹配项目', + 'LBL_SUBMIT' => '提交', + 'LBL_EDIT' => '编辑', + 'LBL_UP' => '上', + 'LBL_DOWN' => '下', + 'LBL_MESSAGE_HIGHLIGHTING_INFO' => '基于上面条件,收到的信件在邮件列表中会使用不同的背景颜色。这有助于区分邮件发件人,特别是邮件列表。', + +); +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/uploads/add2db.php b/oss/vtiger/trunk/modules/uploads/add2db.php new file mode 100644 index 00000000..686938e0 --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/add2db.php @@ -0,0 +1,149 @@ +debug("DEBUG In add2db.php"); + + if(isset($_REQUEST['filename_hidden'])) { + $file = $_REQUEST['filename_hidden']; + } else { + $file = $_FILES['filename']['name']; + } + $binFile = sanitizeUploadFileName($file, $upload_badext); + $_FILES["filename"]["name"] = $binFile; + + //decide the file path where we should upload the file in the server + $upload_filepath = decideFilePath(); + + $current_id = $adb->getUniqueID("vtiger_crmentity"); + + if(move_uploaded_file($_FILES["filename"]["tmp_name"],$upload_filepath.$current_id."_".$_FILES["filename"]["name"])) + { + $filename = ltrim(basename(" ".$binFile)); //allowed filename like UTF-8 characters + $filetype= $_FILES['filename']['type']; + $filesize = $_FILES['filename']['size']; + + if($filesize != 0) + { + $desc = $_REQUEST['txtDescription']; + $subject = $_REQUEST['uploadsubject']; + $date_var = $adb->formatDate(date('Y-m-d H:i:s'), true); + $current_date = getdate(); + $current_date = $adb->formatDate(date('Y-m-d H:i:s'), true); + $query = "insert into vtiger_crmentity (crmid,smcreatorid,smownerid,setype,description,createdtime,modifiedtime) values(?,?,?,?,?,?,?)"; + $params = array($current_id, $current_user->id, $current_user->id, $_REQUEST['return_module'].' Attachment', $desc, $date_var, $current_date); + $result = $adb->pquery($query, $params); + + # Added by DG 26 Oct 2005 + # Attachments added to contacts are also added to their accounts + $log->debug("DEBUG return_module: ".$_REQUEST['return_module']); + if ($_REQUEST['return_module'] == 'Contacts') + { + $crmid = $_REQUEST['return_id']; + $query = 'select accountid from vtiger_contactdetails where contactid=?'; + $result = $adb->pquery($query, array($crmid)); + if($adb->num_rows($result) != 0) + { + $log->debug("DEBUG Returned a row"); + $associated_account = $adb->query_result($result,0,"accountid"); + # Now make sure that we haven't already got this attachment associated to this account + # Hmmm... if this works, should we NOT upload the attachment again, and just set the relation for the contact too? + $log->debug("DEBUG Associated Account: ".$associated_account); + $query = "select attachmentsid, name, path from vtiger_attachments where name=?"; + $result = $adb->pquery($query, array($filename)); + if($adb->num_rows($result) != 0) + { + $log->debug("DEBUG Matched a row"); + # Whoops! We matched the name. Is it the same size? + $fname = $adb->query_result($result,0,"name"); + $fpath = $adb->query_result($result,0,"path"); + $fid = $adb->query_result($result,0,"attachmentsid"); + $dg_size = filesize($fpath . "/".$fid."_". $fname); + //$dg_size = $adb->query_result($result,0,"attachmentsize"); + $log->debug("DEBUG: These should be the same size: ".$dg_size." ".$filesize); + if ($dg_size == $filesize) + { + # Yup, it is probably the same file + $associated_account = ''; + } + } + } + else + { + $associated_account = ''; + } + } + + $sql = "insert into vtiger_attachments(attachmentsid, name, description, type,path,subject) values(?,?,?,?,?,?)"; + $params = array($current_id, $filename, $desc, $filetype, $upload_filepath, $subject); + $result = $adb->pquery($sql, $params); + + + $sql1 = "insert into vtiger_seattachmentsrel values(?,?)"; + $params1 = array($crmid, $current_id); + $result = $adb->pquery($sql1, $params1); + + # Attachments added to contacts are also added to their accounts + if ($associated_account) + { + $log->debug("DEBUG: inserting into vtiger_seattachmentsrel from add2db 2"); + $sql1 = "insert into vtiger_seattachmentsrel values(?,?)"; + $params1 = array($associated_account, $current_id); + $result = $adb->pquery($sql1, $params1); + } + + echo ''; + } + else + { + $errormessage = "Error Message
      +
    • Invalid file OR +
    • File has no data +

    " ; + header("Location: index.php?module=uploads&action=uploadsAjax&msg=true&file=upload&errormessage=".$errormessage); + } + } + else + { + $errorCode = $_FILES['binFile']['error']; + $errormessage = ""; + + if($errorCode == 4) + { + $errormessage = "Kindly give a valid file for upload!
    " ; + } + else if($errorCode == 2) + { + $errormessage = "Sorry, the uploaded file exceeds the maximum filesize limit. Please try a file smaller than $upload_maxsize bytes
    "; + } + else if($errorCode == 6) + { + $errormessage = "Please configure upload_tmp_dir variable in php.ini file.
    " ; + } + else if($errorCode == 3 || $errorcode == '') + { + $errormessage = "Problems in file upload. Please try again!
    "; + } + + if($errormessage != '') + { + echo $errormessage; + include("upload.php"); + } + } + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/uploads/deleteattachments.php b/oss/vtiger/trunk/modules/uploads/deleteattachments.php new file mode 100644 index 00000000..df854041 --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/deleteattachments.php @@ -0,0 +1,23 @@ +pquery($sql, array($id)); + +$sql = "delete from vtiger_attachments where attachmentsid =?"; +$adb->pquery($sql, array($id)); + +header("Location:index.php?module=".vtlib_purify($_REQUEST['return_module'])."&action=".vtlib_purify($_REQUEST['return_action'])."&record=".vtlib_purify($_REQUEST['return_id'])."&parenttab=".getParentTab()); + + +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/uploads/downloadfile.php b/oss/vtiger/trunk/modules/uploads/downloadfile.php new file mode 100644 index 00000000..a65347d8 --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/downloadfile.php @@ -0,0 +1,57 @@ +pquery("SELECT deleted FROM vtiger_crmentity WHERE crmid=?", array($entityid)); +if(!empty($deletecheck) && $adb->query_result($deletecheck, 0, 'deleted') == 1) { + + echo $app_strings['LBL_RECORD_DELETE']; + +} else { + + $dbQuery = "SELECT * FROM vtiger_attachments WHERE attachmentsid = ?" ; + + $result = $adb->pquery($dbQuery, array($attachmentsid)) or die("Couldn't get file list"); + if($adb->num_rows($result) == 1) + { + $fileType = @$adb->query_result($result, 0, "type"); + $name = @$adb->query_result($result, 0, "name"); + $filepath = @$adb->query_result($result, 0, "path"); + $name = html_entity_decode($name, ENT_QUOTES, $default_charset); + $saved_filename = $attachmentsid."_".$name; + $disk_file_size = filesize($filepath.$saved_filename); + $filesize = $disk_file_size + ($disk_file_size % 1024); + $fileContent = fread(fopen($filepath.$saved_filename, "r"), $filesize); + + header("Content-type: $fileType"); + header("Content-length: $filesize"); + header("Cache-Control: private"); + header("Content-Disposition: attachment; filename=$name"); + header("Content-Description: PHP Generated Data"); + echo $fileContent; + } + else + { + echo $app_strings['LBL_RECORD_NOT_FOUND']; + } +} +?> \ No newline at end of file diff --git a/oss/vtiger/trunk/modules/uploads/language/en_us.lang.php b/oss/vtiger/trunk/modules/uploads/language/en_us.lang.php new file mode 100644 index 00000000..83c1083f --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/language/en_us.lang.php @@ -0,0 +1,35 @@ +'Attach File', +'LBL_ATTACH'=>'Attach', +'LBL_CANCEL'=>'Cancel', +'LBL_STEP_SELECT_FILE'=>'Step 1 : Select File', +'LBL_BROWSE_FILES'=>'Click the browse button and select the file to be attached', +'LBL_DESCRIPTION'=>'Step 2 : Write some description', +'LBL_OPTIONAL'=>'(optional)', +); + +?> diff --git a/oss/vtiger/trunk/modules/uploads/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/uploads/language/zh_cn.lang.php new file mode 100644 index 00000000..e5026769 --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/language/zh_cn.lang.php @@ -0,0 +1,35 @@ + '附件档案', +'LBL_ATTACH'=>'档案', +'LBL_CANCEL'=>'取消', + 'LBL_STEP_SELECT_FILE' => '步骤一:选择档案', + 'LBL_BROWSE_FILES' => '点选浏览器按钮并且选择要附加的档案', + 'LBL_DESCRIPTION' => '步骤二:填入一些描述', + 'LBL_OPTIONAL' => '(选择性输入)', +); + +?> diff --git a/oss/vtiger/trunk/modules/uploads/upload.php b/oss/vtiger/trunk/modules/uploads/upload.php new file mode 100644 index 00000000..a43de410 --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/upload.php @@ -0,0 +1,139 @@ + + + + + + + +
    + + + + + + + + + + +
    + + + + + +
     
    + + + + +
    + + + + + + + + + + + + + +
    +
    + +
    * 
    +   +
     
    + +
    +
    + + + + + +
    +  " class="crmbutton small save" onclick = "return titleValidation();" />   + " class="crmbutton small cancel" onclick="self.close();" /> +
    +
    +
    + + diff --git a/oss/vtiger/trunk/modules/uploads/uploadsAjax.php b/oss/vtiger/trunk/modules/uploads/uploadsAjax.php new file mode 100644 index 00000000..907b7657 --- /dev/null +++ b/oss/vtiger/trunk/modules/uploads/uploadsAjax.php @@ -0,0 +1,14 @@ + diff --git a/oss/vtiger/trunk/modules/vtmessages/language/zh_cn.lang.php b/oss/vtiger/trunk/modules/vtmessages/language/zh_cn.lang.php new file mode 100644 index 00000000..5d5022dd --- /dev/null +++ b/oss/vtiger/trunk/modules/vtmessages/language/zh_cn.lang.php @@ -0,0 +1,53 @@ + '留言板', +'LBL_VTMESSAGES_INFORMATION' => '留言信息', +'LBL_CUSTOM_INFORMATION' => '定制信息', +'SINGLE_RECORD'=>'留言', + +'Status'=>'状态', +'Message' => '留言', +'From' => '来源:', +'Related To'=>'关于:', +'Assigned To' => '留言', +'Created Time' => '创建时间', +'Modified Time' => '修改时间', +'Message by'=>'消息作者:', +'Tags'=>'标签', +'Topic ID'=>'主题ID', + +'LBL_SUBJECT'=>'主题', +'LBL_SUBJECT_EXAMPLE'=>' 如: 小组会议', +'LBL_RESET' => '重写', +'LBL_SEND' => '发送', +'LBL_REPLY' => '回复', +'LBL_TO'=> '到', +'LBL_AT'=> '在', +'LBL_SENDREPLY'=>'发送回复', +'LBL_MARKAS'=>'标记为', +'LBL_MESSAGENOW_TO'=>'留言给', +'LBL_SAYS'=>'说', +'LBL_YOU'=>'我', +'LBL_SAID'=>'说过', +'LBL_SELECTED_USERS'=>'选中用户', +'LBL_ATLEAST_SELECTONE_USER'=>'至少选择一个用户!', + +'LBL_VIEW'=>'查看', +'LBL_THREAD'=>'按线程', +'LBL_TOPIC'=>'按标题', + +'LBL_MAIL_SUBJECT_PREFIX'=>'留言板 - ', +'LBL_MAIL_GROUP_SALUTATION'=>'所有', +'LBL_MAIL_SUBJECT_NEW_SUFFIX_FORYOU'=>' 发出了一个信息.', +'LBL_MAIL_SUBJECT_REPLY_SUFFIX_FORYOU'=>' 发出了一个回复.', +); + +?>