[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/include/utils/ -> export.php (source)

   1  <?php
   2  /*********************************************************************************
   3   * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
   4   * ("License"); You may not use this file except in compliance with the
   5   * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
   6   * Software distributed under the License is distributed on an  "AS IS"  basis,
   7   * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
   8   * the specific language governing rights and limitations under the License.
   9   * The Original Code is:  SugarCRM Open Source
  10   * The Initial Developer of the Original Code is SugarCRM, Inc.
  11   * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
  12   * All Rights Reserved.
  13   * Contributor(s): ______________________________________.
  14   ********************************************************************************/
  15  
  16  require_once ('config.php');
  17  require_once ('include/logging.php');
  18  require_once ('include/database/PearDatabase.php');
  19  require_once ('modules/Accounts/Accounts.php');
  20  require_once ('modules/Contacts/Contacts.php');
  21  require_once ('modules/Leads/Leads.php');
  22  require_once ('modules/Contacts/Contacts.php');
  23  require_once ('modules/Emails/Emails.php');
  24  require_once ('modules/Calendar/Activity.php');
  25  require_once ('modules/Documents/Documents.php');
  26  require_once ('modules/Potentials/Potentials.php');
  27  require_once ('modules/Users/Users.php');
  28  require_once ('modules/Products/Products.php');
  29  require_once ('modules/HelpDesk/HelpDesk.php');
  30  require_once ('modules/Vendors/Vendors.php');
  31  require_once ('include/utils/UserInfoUtil.php');
  32  require_once ('modules/CustomView/CustomView.php');
  33  require_once  'modules/PickList/PickListUtils.php';
  34  require_once ('modules/Invoice/Invoice.php');
  35  require_once ('modules/Quotes/Quotes.php');
  36  require_once ('modules/PurchaseOrder/PurchaseOrder.php');
  37  require_once ('modules/SalesOrder/SalesOrder.php');
  38  
  39  // Set the current language and the language strings, if not already set.
  40  setCurrentLanguage();
  41  
  42  global $allow_exports,$app_strings;
  43  
  44  session_start();
  45  
  46  $current_user = new Users();
  47  
  48  if(isset($_SESSION['authenticated_user_id']))
  49  {
  50      $result = $current_user->retrieveCurrentUserInfoFromFile($_SESSION['authenticated_user_id'],"Users");
  51      if($result == null)
  52      {
  53          session_destroy();
  54          header("Location: index.php?action=Login&module=Users");
  55          exit;
  56      }
  57  
  58  }
  59  
  60  //Security Check
  61  if(isPermitted($_REQUEST['module'],"Export") == "no")
  62  {
  63      $allow_exports="none";
  64  }
  65  
  66  if ($allow_exports=='none' || ( $allow_exports=='admin' && ! is_admin($current_user) ) )
  67  {
  68  
  69  ?>
  70      <script type='text/javascript'>
  71          alert("<?php echo $app_strings['NOT_PERMITTED_TO_EXPORT']?>");
  72          window.location="index.php?module=<?php echo vtlib_purify($_REQUEST['module']) ?>&action=index";
  73      </script>
  74      
  75      <?php exit; ?>
  76  <?php
  77  }
  78  
  79  /**Function convert line breaks to space in description during export
  80   * Pram $str - text
  81   * retrun type string
  82  */
  83  function br2nl_vt($str)
  84  {
  85      global $log;
  86      $log->debug("Entering br2nl_vt(".$str.") method ...");
  87      $str = preg_replace("/(\r\n)/", " ", $str);
  88      $log->debug("Exiting br2nl_vt method ...");
  89      return $str;
  90  }
  91  
  92  /**
  93   * This function exports all the data for a given module
  94   * Param $type - module name
  95   * Return type text
  96   */
  97  function export($type){
  98      global $log,$list_max_entries_per_page;
  99      $log->debug("Entering export(".$type.") method ...");
 100      global $adb;
 101  
 102      $focus = 0;
 103      $content = '';
 104  
 105      if ($type != ""){
 106          // vtlib customization: Hook to dynamically include required module file.
 107          // Refer to the logic in setting $currentModule in index.php
 108          $focus = CRMEntity::getInstance($type);
 109      }
 110      $log = LoggerManager::getLogger('export_'.$type);
 111      $db = PearDatabase::getInstance();
 112  
 113      $oCustomView = new CustomView("$type");
 114      $viewid = $oCustomView->getViewId("$type");
 115      $sorder = $focus->getSortOrder();
 116      $order_by = $focus->getOrderBy();
 117  
 118      $search_type = vtlib_purify($_REQUEST['search_type']);
 119      $export_data = vtlib_purify($_REQUEST['export_data']);
 120      
 121      if(isset($_SESSION['export_where']) && $_SESSION['export_where']!='' && $search_type == 'includesearch'){
 122          $where =$_SESSION['export_where'];
 123      }
 124  
 125      $query = $focus->create_export_query($where);
 126      if($search_type != 'includesearch' && $type != 'Calendar') {
 127          $stdfiltersql = $oCustomView->getCVStdFilterSQL($viewid);
 128          $advfiltersql = $oCustomView->getCVAdvFilterSQL($viewid);
 129          if(isset($stdfiltersql) && $stdfiltersql != ''){
 130              $query .= ' and '.$stdfiltersql;
 131          }
 132          if(isset($advfiltersql) && $advfiltersql != '') {
 133              $query .= ' and '.$advfiltersql;
 134          }
 135      }
 136      $params = array();
 137  
 138      list($idstring, $export_data) = split("#@@#",getExportRecordIds($type, $viewid, $_REQUEST));
 139      
 140      if(($search_type == 'withoutsearch' || $search_type == 'includesearch') && $export_data == 'selecteddata'){
 141          $idstring = getSelectedRecords($_REQUEST, $type, $idstring, vtlib_purify($_REQUEST['excludedRecords']));
 142          if($type == 'Accounts' && count($idstring) > 0) {
 143              $query .= ' and vtiger_account.accountid in ('. generateQuestionMarks($idstring) .')';
 144              array_push($params, $idstring);
 145          } elseif($type == 'Contacts' && count($idstring) > 0) {
 146              $query .= ' and vtiger_contactdetails.contactid in ('. generateQuestionMarks($idstring) .')';
 147              array_push($params, $idstring);
 148          } elseif($type == 'Potentials' && count($idstring) > 0) {
 149              $query .= ' and vtiger_potential.potentialid in ('. generateQuestionMarks($idstring) .')';
 150              array_push($params, $idstring);
 151          } elseif($type == 'Leads' && count($idstring) > 0) {
 152              $query .= ' and vtiger_leaddetails.leadid in ('. generateQuestionMarks($idstring) .')';
 153              array_push($params, $idstring);
 154          } elseif($type == 'Products' && count($idstring) > 0) {
 155              $query .= ' and vtiger_products.productid in ('. generateQuestionMarks($idstring) .')';
 156              array_push($params, $idstring);
 157          } elseif($type == 'Documents' && count($idstring) > 0) {
 158              $query .= ' and vtiger_notes.notesid in ('. generateQuestionMarks($idstring) .')';
 159              array_push($params, $idstring);
 160          } elseif($type == 'HelpDesk' && count($idstring) > 0) {
 161              $query .= ' and vtiger_troubletickets.ticketid in ('. generateQuestionMarks($idstring) .')';
 162              array_push($params, $idstring);
 163          } elseif($type == 'Vendors' && count($idstring) > 0) {
 164              $query .= ' and vtiger_vendor.vendorid in ('. generateQuestionMarks($idstring) .')';
 165              array_push($params, $idstring);
 166          } elseif($type == 'Invoice' && count($idstring) > 0) {
 167              $query .= ' and vtiger_invoice.invoiceid in ('. generateQuestionMarks($idstring) .')';
 168              array_push($params, $idstring);
 169          } elseif($type == 'Quotes' && count($idstring) > 0) {
 170              $query .= ' and vtiger_quotes.quoteid in ('. generateQuestionMarks($idstring) .')';
 171              array_push($params, $idstring);
 172          } elseif($type == 'SalesOrder' && count($idstring) > 0) {
 173              $query .= ' and vtiger_salesorder.salesorderid in ('. generateQuestionMarks($idstring) .')';
 174              array_push($params, $idstring);
 175          } elseif($type == 'PurchaseOrder' && count($idstring) > 0) {
 176              $query .= ' and vtiger_purchaseorder.purchaseorderid in ('. generateQuestionMarks($idstring) .')';
 177              array_push($params, $idstring);
 178          }
 179          else if(count($idstring) > 0) {
 180              // vtlib customization: Hook to make the export feature available for custom modules.
 181              $query .= " and $focus->table_name.$focus->table_index in (" . generateQuestionMarks($idstring) . ')';
 182              array_push($params, $idstring);
 183              // END
 184          }
 185      }
 186      
 187      if(isset($order_by) && $order_by != ''){
 188          if($order_by == 'smownerid'){
 189              $query .= ' ORDER BY user_name '.$sorder;
 190          }elseif($order_by == 'lastname' && $type == 'Documents'){
 191              $query .= ' ORDER BY vtiger_contactdetails.lastname  '. $sorder;
 192          }elseif($order_by == 'crmid' && $type == 'HelpDesk'){
 193              $query .= ' ORDER BY vtiger_troubletickets.ticketid  '. $sorder;
 194          }else{
 195              $tablename = getTableNameForField($type,$order_by);
 196              $tablename = (($tablename != '')?($tablename."."):'');
 197              if( $adb->dbType == "pgsql"){
 198                  $query .= ' GROUP BY '.$tablename.$order_by;
 199              }
 200              $query .= ' ORDER BY '.$tablename.$order_by.' '.$sorder;
 201          }
 202      }
 203      
 204      if($export_data == 'currentpage'){
 205          $current_page = ListViewSession::getCurrentPage($type,$viewid);
 206          $limit_start_rec = ($current_page - 1) * $list_max_entries_per_page;
 207          if ($limit_start_rec < 0) $limit_start_rec = 0;
 208          $query .= ' LIMIT '.$limit_start_rec.','.$list_max_entries_per_page;
 209      }
 210  
 211      $result = $adb->pquery($query, $params, true, "Error exporting $type: "."<BR>$query");
 212      $fields_array = $adb->getFieldsArray($result);
 213      $fields_array = array_diff($fields_array,array("user_name"));
 214      
 215      $__processor = new ExportUtils($type, $fields_array);
 216      
 217      // Translated the field names based on the language used.
 218      $translated_fields_array = array();
 219      for($i=0; $i<count($fields_array); $i++) {
 220          $translated_fields_array[$i] = getTranslatedString($fields_array[$i],$type);
 221      }
 222      $header = implode("\",\"",array_values($translated_fields_array));
 223      $header = "\"" .$header;
 224      $header .= "\"\r\n";
 225      
 226      /** Output header information */
 227      echo $header;
 228  
 229      $column_list = implode(",",array_values($fields_array));
 230  
 231      while($val = $adb->fetchByAssoc($result, -1, false)){
 232          $new_arr = array();
 233          $val = $__processor->sanitizeValues($val);
 234          foreach ($val as $key => $value){
 235              if($type == 'Documents' && $key == 'description'){
 236                  $value = strip_tags($value);
 237                  $value = str_replace('&nbsp;','',$value);
 238                  array_push($new_arr,$value);
 239              }elseif($key != "user_name"){
 240                  // Let us provide the module to transform the value before we save it to CSV file
 241                  $value = $focus->transform_export_value($key, $value);
 242                  
 243                  array_push($new_arr, preg_replace("/\"/","\"\"",$value));
 244              }
 245          }
 246          $line = implode("\",\"",$new_arr);
 247          $line = "\"" .$line;
 248          $line .= "\"\r\n";
 249          
 250          /** Output each row information */
 251          echo $line;
 252      }
 253      $log->debug("Exiting export method ...");
 254      return true;
 255  }
 256  
 257  /** Send the output header and invoke function for contents output */
 258  $moduleName = vtlib_purify($_REQUEST['module']);
 259  $moduleName = getTranslatedString($moduleName, $moduleName);
 260  $moduleName = str_replace(" ","_",$moduleName);
 261  header("Content-Disposition:attachment;filename=$moduleName.csv");
 262  header("Content-Type:text/csv;charset=UTF-8");
 263  header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
 264  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" );
 265  header("Cache-Control: post-check=0, pre-check=0", false );
 266  
 267  export(vtlib_purify($_REQUEST['module']));
 268  
 269  exit;
 270  
 271  /**
 272   * this class will provide utility functions to process the export data.
 273   * this is to make sure that the data is sanitized before sending for export
 274   */
 275  class ExportUtils{
 276      var $fieldsArr = array();
 277      var $picklistValues = array();
 278      
 279  	function ExportUtils($module, $fields_array){
 280          self::__init($module, $fields_array);
 281      }
 282      
 283      
 284  	function __init($module, $fields_array){
 285          $infoArr = self::getInformationArray($module);
 286          
 287          //attach extra fields related information to the fields_array; this will be useful for processing the export data
 288          foreach($infoArr as $fieldname=>$fieldinfo){
 289              if(in_array($fieldinfo["fieldlabel"], $fields_array)){
 290                  $this->fieldsArr[$fieldname] = $fieldinfo;
 291              }
 292          }
 293      }
 294      
 295      /**
 296       * this function takes in an array of values for an user and sanitizes it for export
 297       * @param array $arr - the array of values
 298       */
 299  	function sanitizeValues($arr){
 300          global $current_user, $adb;
 301          $roleid = fetchUserRole($current_user->id);
 302          
 303          foreach($arr as $fieldlabel=>&$value){
 304              $fieldInfo = $this->fieldsArr[$fieldlabel];
 305              
 306              $uitype = $fieldInfo['uitype'];
 307              $fieldname = $fieldInfo['fieldname'];
 308              if($uitype == 15 || $uitype == 16 || $uitype == 33){
 309                  //picklists
 310                  if(empty($this->picklistValues[$fieldname])){
 311                      $this->picklistValues[$fieldname] = getAssignedPicklistValues($fieldname, $roleid, $adb);
 312                  }
 313                  $value = trim($value);
 314              }elseif($uitype == 10){
 315                  //have to handle uitype 10
 316                  $value = trim($value);
 317                  if(!empty($value)) {
 318                      $parent_module = getSalesEntityType($value);
 319                      $displayValueArray = getEntityName($parent_module, $value);
 320                      if(!empty($displayValueArray)){
 321                          foreach($displayValueArray as $k=>$v){
 322                              $displayValue = $v;
 323                          }
 324                      }
 325                      if(!empty($parent_module) && !empty($displayValue)){
 326                          $value = $parent_module."::::".$displayValue;
 327                      }else{
 328                          $value = "";
 329                      }
 330                  } else {
 331                      $value = '';
 332                  }
 333              } elseif($uitype == 71) {
 334                  $value = CurrencyField::convertToUserFormat($value);
 335              } elseif($uitype == 72) {
 336                  $value = CurrencyField::convertToUserFormat($value, null, true, true);
 337              } elseif($uitype == 7 && $fieldInfo['typeofdata'] == 'N~O' || $uitype == 9){
 338                  $value = decimalFormat($value);
 339              }
 340          }
 341          return $arr;
 342      }
 343      
 344      /**
 345       * this function takes in a module name and returns the field information for it
 346       */
 347  	function getInformationArray($module){
 348          require_once  'include/utils/utils.php';
 349          global $adb;
 350          $tabid = getTabid($module);
 351          
 352          $result = $adb->pquery("select * from vtiger_field where tabid=?", array($tabid));
 353          $count = $adb->num_rows($result);
 354          $arr = array();
 355          $data = array();
 356          
 357          for($i=0;$i<$count;$i++){
 358              $arr['uitype'] = $adb->query_result($result, $i, "uitype");
 359              $arr['fieldname'] = $adb->query_result($result, $i, "fieldname");
 360              $arr['columnname'] = $adb->query_result($result, $i, "columnname");
 361              $arr['tablename'] = $adb->query_result($result, $i, "tablename");
 362              $arr['fieldlabel'] = $adb->query_result($result, $i, "fieldlabel");
 363              $arr['typeofdata'] = $adb->query_result($result, $i, "typeofdata");
 364              $fieldlabel = strtolower($arr['fieldlabel']);
 365              $data[$fieldlabel] = $arr;
 366          }
 367          return $data;
 368      }
 369  }
 370  ?>


Generated: Fri Nov 28 20:08:37 2014 Cross-referenced by PHPXref 0.7.1