[ Index ]

PHP Cross Reference of vtigercrm-6.1.0

title

Body

[close]

/modules/Vtiger/models/ -> Module.php (source)

   1  <?php
   2  /*+***********************************************************************************
   3   * The contents of this file are subject to the vtiger CRM Public License Version 1.0
   4   * ("License"); You may not use this file except in compliance with the License
   5   * The Original Code is:  vtiger CRM Open Source
   6   * The Initial Developer of the Original Code is vtiger.
   7   * Portions created by vtiger are Copyright (C) vtiger.
   8   * All Rights Reserved.
   9   *************************************************************************************/
  10  vimport('~~/vtlib/Vtiger/Module.php');
  11  
  12  /**
  13   * Vtiger Module Model Class
  14   */
  15  class Vtiger_Module_Model extends Vtiger_Module {
  16  
  17      protected $blocks = false;
  18      protected $nameFields = false;
  19      protected $moduleMeta = false;
  20      protected $fields = false;
  21      protected $relations = null;
  22  
  23      /**
  24       * Function to get the Module/Tab id
  25       * @return <Number>
  26       */
  27  	public function getId() {
  28          return $this->id;
  29      }
  30  
  31  	public function getName() {
  32          return $this->name;
  33      }
  34  
  35      /**
  36       * Function to check whether the module is an entity type module or not
  37       * @return <Boolean> true/false
  38       */
  39  	public function isEntityModule() {
  40          return ($this->isentitytype== '1') ? true :false ;
  41      }
  42  
  43      /**
  44       * Function to check whether the module is enabled for quick create
  45       * @return <Boolean> - true/false
  46       */
  47  	public function isQuickCreateSupported() {
  48          return $this->isEntityModule();
  49      }
  50  
  51      /**
  52       * Function to check whether the module is summary view supported
  53       * @return <Boolean> - true/false
  54       */
  55  	public function isSummaryViewSupported() {
  56          return true;
  57      }
  58  
  59      /**
  60       * Function to get singluar label key
  61       * @return <String> - Singular module label key
  62       */
  63  	public function getSingularLabelKey(){
  64          return 'SINGLE_'.$this->get('name');
  65      }
  66  
  67      /**
  68       * Function to get the value of a given property
  69       * @param <String> $propertyName
  70       * @return <Object>
  71       * @throws Exception
  72       */
  73  	public function get($propertyName) {
  74          if(property_exists($this,$propertyName)){
  75              return $this->$propertyName;
  76          }
  77          throw new Exception( $propertyName.' doest not exists in class '.get_class($this));
  78      }
  79  
  80      /**
  81       * Function to set the value of a given property
  82       * @param <String> $propertyName
  83       * @param <Object> $propertyValue
  84       * @return Vtiger_Module_Model instance
  85       */
  86  	public function set($propertyName, $propertyValue) {
  87          $this->$propertyName = $propertyValue;
  88          return $this;
  89      }
  90  
  91      /**
  92       * Function checks if the module is Active
  93       * @return <Boolean>
  94       */
  95  	public function isActive() {
  96          return in_array($this->get('presence'), array(0,2));
  97      }
  98  
  99      /**
 100       * Function checks if the module is enabled for tracking changes
 101       * @return <Boolean>
 102       */
 103  	public function isTrackingEnabled() {
 104          require_once 'modules/ModTracker/ModTracker.php';
 105          $trackingEnabled = ModTracker::isTrackingEnabledForModule($this->getName());
 106          return ($this->isActive() && $trackingEnabled);
 107      }
 108  
 109      /**
 110       * Function checks if comment is enabled
 111       * @return boolean
 112       */
 113  	public function isCommentEnabled() {
 114          $enabled = false;
 115          $db = PearDatabase::getInstance();
 116          $commentsModuleModel = Vtiger_Module_Model::getInstance('ModComments');
 117          if($commentsModuleModel && $commentsModuleModel->isActive()) {
 118              $relatedToFieldResult = $db->pquery('SELECT fieldid FROM vtiger_field WHERE fieldname = ? AND tabid = ?',
 119                      array('related_to', $commentsModuleModel->getId()));
 120              $fieldId = $db->query_result($relatedToFieldResult, 0, 'fieldid');
 121              if(!empty($fieldId)) {
 122                  $relatedModuleResult = $db->pquery('SELECT relmodule FROM vtiger_fieldmodulerel WHERE fieldid = ?', array($fieldId));
 123                  $rows = $db->num_rows($relatedModuleResult);
 124  
 125                  for($i=0; $i<$rows; $i++) {
 126                      $relatedModule = $db->query_result($relatedModuleResult, $i, 'relmodule');
 127                      if($this->getName() == $relatedModule) {
 128                          $enabled = true;
 129                      }
 130                  }
 131              }
 132          } else {
 133              $enabled = false;
 134          }
 135          return $enabled;
 136      }
 137  
 138      /**
 139       * Function to save a given record model of the current module
 140       * @param Vtiger_Record_Model $recordModel
 141       */
 142  	public function saveRecord($recordModel) {
 143          $moduleName = $this->get('name');
 144          $focus = CRMEntity::getInstance($moduleName);
 145          $fields = $focus->column_fields;
 146          foreach($fields as $fieldName => $fieldValue) {
 147              $fieldValue = $recordModel->get($fieldName);
 148              if(is_array($fieldValue)){
 149                  $focus->column_fields[$fieldName] = $fieldValue;
 150              }else if($fieldValue !== null) {
 151                  $focus->column_fields[$fieldName] = decode_html($fieldValue);
 152              }
 153          }
 154          $focus->mode = $recordModel->get('mode');
 155          $focus->id = $recordModel->getId();
 156          $focus->save($moduleName);
 157          return $recordModel->setId($focus->id);
 158      }
 159  
 160      /**
 161       * Function to delete a given record model of the current module
 162       * @param Vtiger_Record_Model $recordModel
 163       */
 164  	public function deleteRecord($recordModel) {
 165          $moduleName = $this->get('name');
 166          $focus = CRMEntity::getInstance($moduleName);
 167          $focus->trash($moduleName, $recordModel->getId());
 168          if(method_exists($focus, 'transferRelatedRecords')) {
 169              if($recordModel->get('transferRecordIDs'))
 170                  $focus->transferRelatedRecords($moduleName, $recordModel->get('transferRecordIDs'), $recordModel->getId());
 171          }
 172      }
 173  
 174      /**
 175       * Function to get the module meta information
 176       * @param <type> $userModel - user model
 177       */
 178  	public function getModuleMeta($userModel = false) {
 179          if(empty($this->moduleMeta)){
 180              if(empty($userModel)) {
 181              $userModel = Users_Record_Model::getCurrentUserModel();
 182          }
 183              $this->moduleMeta = Vtiger_ModuleMeta_Model::getInstance($this->get('name'), $userModel);
 184          }
 185          return $this->moduleMeta;
 186      }
 187  
 188      //Note : This api is using only in RelationListview - for getting columnfields of Related Module
 189      //Need to review........
 190  
 191      /**
 192       * Function to get the module field mapping
 193       * @return <array>
 194       */
 195  	public function getColumnFieldMapping(){
 196          $moduleMeta = $this->getModuleMeta();
 197          $meta = $moduleMeta->getMeta();
 198          $fieldColumnMapping =  $meta->getFieldColumnMapping();
 199          return array_flip($fieldColumnMapping);
 200      }
 201  
 202      /**
 203       * Function to get the ListView Component Name
 204       * @return string
 205       */
 206  	public function getListViewName() {
 207          return 'List';
 208      }
 209  
 210      /**
 211       * Function to get the DetailView Component Name
 212       * @return string
 213       */
 214  	public function getDetailViewName() {
 215          return 'Detail';
 216      }
 217  
 218      /**
 219       * Function to get the EditView Component Name
 220       * @return string
 221       */
 222  	public function getEditViewName(){
 223          return 'Edit';
 224      }
 225  
 226      /**
 227       * Function to get the DuplicateView Component Name
 228       * @return string
 229       */
 230  	public function getDuplicateViewName(){
 231          return 'Edit';
 232      }
 233  
 234      /**
 235       * Function to get the Delete Action Component Name
 236       * @return string
 237       */
 238  	public function getDeleteActionName() {
 239          return 'Delete';
 240      }
 241  
 242      /**
 243       * Function to get the Default View Component Name
 244       * @return string
 245       */
 246  	public function getDefaultViewName() {
 247          return 'List';
 248      }
 249  
 250      /**
 251       * Function to get the url for default view of the module
 252       * @return <string> - url
 253       */
 254  	public function getDefaultUrl() {
 255          return 'index.php?module='.$this->get('name').'&view='.$this->getDefaultViewName();
 256      }
 257  
 258      /**
 259       * Function to get the url for list view of the module
 260       * @return <string> - url
 261       */
 262  	public function getListViewUrl() {
 263          return 'index.php?module='.$this->get('name').'&view='.$this->getListViewName();
 264      }
 265  
 266      /**
 267       * Function to get the url for the Create Record view of the module
 268       * @return <String> - url
 269       */
 270  	public function getCreateRecordUrl() {
 271          return 'index.php?module='.$this->get('name').'&view='.$this->getEditViewName();
 272      }
 273  
 274      /**
 275       * Function to get the url for the Create Record view of the module
 276       * @return <String> - url
 277       */
 278  	public function getQuickCreateUrl() {
 279          return 'index.php?module='.$this->get('name').'&view=QuickCreateAjax';
 280      }
 281  
 282      /**
 283       * Function to get the url for the Import action of the module
 284       * @return <String> - url
 285       */
 286  	public function getImportUrl() {
 287          return 'index.php?module='.$this->get('name').'&view=Import';
 288      }
 289  
 290      /**
 291       * Function to get the url for the Export action of the module
 292       * @return <String> - url
 293       */
 294  	public function getExportUrl() {
 295          return 'index.php?module='.$this->get('name').'&view=Export';
 296      }
 297  
 298      /**
 299       * Function to get the url for the Find Duplicates action of the module
 300       * @return <String> - url
 301       */
 302  	public function getFindDuplicatesUrl() {
 303          return 'index.php?module='.$this->get('name').'&view=FindDuplicates';
 304      }
 305  
 306      /**
 307       * Function to get the url to view Dashboard for the module
 308       * @return <String> - url
 309       */
 310  	public function getDashBoardUrl() {
 311          return 'index.php?module='. $this->get('name').'&view=DashBoard';
 312      }
 313  
 314      /**
 315       * Function to get the url to view Details for the module
 316       * @return <String> - url
 317       */
 318  	public function getDetailViewUrl($id) {
 319          return 'index.php?module='. $this->get('name').'&view='.$this->getDetailViewName().'&record='.$id;
 320      }
 321      /**
 322       * Function to get a Vtiger Record Model instance from an array of key-value mapping
 323       * @param <Array> $valueArray
 324       * @return Vtiger_Record_Model or Module Specific Record Model instance
 325       */
 326  	public function getRecordFromArray($valueArray, $rawData=false) {
 327          $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'Record', $this->get('name'));
 328          $recordInstance = new $modelClassName();
 329          return $recordInstance->setData($valueArray)->setModuleFromInstance($this)->setRawData($rawData);
 330      }
 331  
 332      /**
 333       * Function returns all the blocks for the module
 334       * @return <Array of Vtiger_Block_Model> - list of block models
 335       */
 336  	public function getBlocks() {
 337          if(empty($this->blocks)) {
 338              $blocksList = array();
 339              $moduleBlocks = Vtiger_Block_Model::getAllForModule($this);
 340              foreach($moduleBlocks as $block){
 341                  $blocksList[$block->get('label')] = $block;
 342              }
 343              $this->blocks = $blocksList;
 344          }
 345          return $this->blocks;
 346      }
 347  
 348      /**
 349       * Function that returns all the fields for the module
 350       * @return <Array of Vtiger_Field_Model> - list of field models
 351       */
 352  	public function getFields($blockInstance=false) {
 353          if(empty($this->fields)){
 354              $moduleBlockFields = Vtiger_Field_Model::getAllForModule($this);
 355              $this->fields = array();
 356              foreach($moduleBlockFields as $moduleFields){
 357                  foreach($moduleFields as $moduleField){
 358                       $block = $moduleField->get('block');
 359                      if(empty($block)) {
 360                          continue;
 361                  }
 362                      $this->fields[$moduleField->get('name')] = $moduleField;
 363              }
 364              }
 365          }
 366          return $this->fields;
 367      }
 368  
 369  
 370      /**
 371       * Function gives fields based on the type
 372       * @param <String> $type - field type
 373       * @return <Array of Vtiger_Field_Model> - list of field models
 374       */
 375  	public function getFieldsByType($type) {
 376          if(!is_array($type)) {
 377              $type = array($type);
 378          }
 379          $fields = $this->getFields();
 380          $fieldList = array();
 381          foreach($fields as $field) {
 382              $fieldType = $field->getFieldDataType();
 383              if(in_array($fieldType,$type)) {
 384                  $fieldList[$field->getName()] = $field;
 385              }
 386          }
 387          return $fieldList;
 388      }
 389  
 390      /**
 391       * Function gives fields based on the type
 392       * @return <Vtiger_Field_Model> with field label as key
 393       */
 394  	public function getFieldsByLabel() {
 395          $fields = $this->getFields();
 396          $fieldList = array();
 397          foreach($fields as $field) {
 398              $fieldLabel = $field->get('label');
 399              $fieldList[$fieldLabel] = $field;
 400          }
 401          return $fieldList;
 402      }
 403  
 404      /**
 405       * Function gives fields based on the fieldid
 406       * @return <Vtiger_Field_Model> with field id as key
 407       */
 408  	public function getFieldsById() {
 409          $fields = $this->getFields();
 410          $fieldList = array();
 411          foreach($fields as $field) {
 412              $fieldId = $field->getId();
 413              $fieldList[$fieldId] = $field;
 414          }
 415          return $fieldList;
 416      }
 417  
 418      /**
 419       * Function returns all the relation models
 420       * @return <Array of Vtiger_Relation_Model>
 421       */
 422  	public function getRelations() {
 423          if(empty($this->relations)) {
 424              return Vtiger_Relation_Model::getAllRelations($this);
 425          }
 426          return $this->relations;
 427      }
 428  
 429      /**
 430       * Function that returns all the quickcreate fields for the module
 431       * @return <Array of Vtiger_Field_Model> - list of field models
 432       */
 433      public function getQuickCreateFields() {
 434          $fieldList = $this->getFields();
 435          $quickCreateFieldList = array();
 436          foreach($fieldList as $fieldName => $fieldModel) {
 437              if($fieldModel->isQuickCreateEnabled() && $fieldModel->isEditable()) {
 438                  $quickCreateFieldList[$fieldName] = $fieldModel;
 439              }
 440          }
 441          return $quickCreateFieldList;
 442      }
 443  
 444      /**
 445       * Function to get the field mode
 446       * @param <String> $fieldName - field name
 447       * @return <Vtiger_Field_Model>
 448       */
 449  	public function getField($fieldName){
 450          return Vtiger_Field_Model::getInstance($fieldName,$this);
 451      }
 452  
 453      /**
 454       * Function to get the field by column name.
 455       * @param <String> $columnName - column name
 456       * @return <Vtiger_Field_Model>
 457       */
 458  	public function getFieldByColumn($columnName) {
 459          $fields = $this->getFields();
 460          if ($fields) {
 461              foreach ($fields as $field) {
 462                  if ($field->get('column') == $columnName) {
 463                      return $field;
 464                  }
 465              }
 466          }
 467          return NULL;
 468      }
 469  
 470      /**
 471       * Function to retrieve name fields of a module
 472       * @return <array> - array which contains fields which together construct name fields
 473       */
 474  	public function getNameFields(){
 475  
 476          $nameFieldObject = Vtiger_Cache::get('EntityField',$this->getName());
 477          $moduleName = $this->getName();
 478          if($nameFieldObject && $nameFieldObject->fieldname) {
 479              $this->nameFields = explode(',', $nameFieldObject->fieldname);
 480          } else {
 481              $adb = PearDatabase::getInstance();
 482  
 483              $query = "SELECT fieldname, tablename, entityidfield FROM vtiger_entityname WHERE tabid = ?";
 484              $result = $adb->pquery($query, array($this->getId()));
 485              $this->nameFields = array();
 486              if($result){
 487                  $rowCount = $adb->num_rows($result);
 488                  if($rowCount > 0){
 489                      $fieldNames = $adb->query_result($result,0,'fieldname');
 490                      $this->nameFields = explode(',', $fieldNames);
 491                  }
 492              }
 493  
 494              //added to handle entity names for these two modules
 495              //@Note: need to move these to database
 496              switch($moduleName) {
 497                  case 'HelpDesk': $this->nameFields = array('ticket_title'); $fieldNames = 'ticket_title'; break;
 498                  case 'Documents': $this->nameFields = array('notes_title'); $fieldNames = 'notes_title';  break;
 499              }
 500              $entiyObj = new stdClass();
 501              $entiyObj->basetable = $adb->query_result($result, 0, 'tablename');
 502              $entiyObj->basetableid =  $adb->query_result($result, 0, 'entityidfield');
 503              $entiyObj->fieldname =  $fieldNames;
 504              Vtiger_Cache::set('EntityField',$this->getName(), $entiyObj);
 505          }
 506          
 507          return $this->nameFields;
 508      }
 509  
 510      /**
 511       * Function to get the list of recently visisted records
 512       * @param <Number> $limit
 513       * @return <Array> - List of Vtiger_Record_Model or Module Specific Record Model instances
 514       */
 515  	public function getRecentRecords($limit=10) {
 516          $db = PearDatabase::getInstance();
 517  
 518          $currentUserModel = Users_Record_Model::getCurrentUserModel();
 519          $deletedCondition = $this->getDeletedRecordCondition();
 520          $nonAdminQuery .= Users_Privileges_Model::getNonAdminAccessControlQuery($this->getName());
 521          $query = 'SELECT * FROM vtiger_crmentity '.$nonAdminQuery.' WHERE setype=? AND '.$deletedCondition.' AND modifiedby = ? ORDER BY modifiedtime DESC LIMIT ?';
 522          $params = array($this->getName(), $currentUserModel->id, $limit);
 523          $result = $db->pquery($query, $params);
 524          $noOfRows = $db->num_rows($result);
 525  
 526          $recentRecords = array();
 527          for($i=0; $i<$noOfRows; ++$i) {
 528              $row = $db->query_result_rowdata($result, $i);
 529              $row['id'] = $row['crmid'];
 530              $recentRecords[$row['id']] = $this->getRecordFromArray($row);
 531          }
 532          return $recentRecords;
 533      }
 534  
 535      /**
 536       * Function that returns deleted records condition
 537       * @return <String>
 538       */
 539      public function getDeletedRecordCondition() {
 540         return 'vtiger_crmentity.deleted = 0';
 541      }
 542  
 543      /**
 544       * Funtion that returns fields that will be showed in the record selection popup
 545       * @return <Array of fields>
 546       */
 547      public function getPopupFields() {
 548          $entityInstance = CRMEntity::getInstance($this->getName());
 549          return $entityInstance->search_fields_name;
 550      }
 551  
 552      /**
 553       * Function that returns related list header fields that will be showed in the Related List View
 554       * @return <Array> returns related fields list.
 555       */
 556  	public function getRelatedListFields() {
 557          $entityInstance = CRMEntity::getInstance($this->getName());
 558          $list_fields_name = $entityInstance->list_fields_name;
 559          $list_fields = $entityInstance->list_fields;
 560          $relatedListFields = array();
 561          foreach ($list_fields as $key => $fieldInfo) {
 562              foreach ($fieldInfo as $columnName) {
 563                  if(array_key_exists($key, $list_fields_name)){
 564                      $relatedListFields[$columnName] = $list_fields_name[$key];
 565                  }
 566              }
 567  
 568          }
 569          return $relatedListFields;
 570      }
 571  
 572  	public function getConfigureRelatedListFields(){
 573          $showRelatedFieldModel = $this->getSummaryViewFieldsList();
 574          $relatedListFields = array();
 575          if(count($showRelatedFieldModel) > 0) {
 576              foreach ($showRelatedFieldModel as $key => $field) {
 577                  $relatedListFields[$field->get('column')] = $field->get('name');
 578              }
 579          }
 580          return $relatedListFields;
 581      }
 582  
 583  	public function isWorkflowSupported() {
 584          if($this->isEntityModule()) {
 585              return true;
 586          }
 587          return false;
 588      }
 589  
 590      /**
 591       * Function checks if a module has module sequence numbering
 592       * @return boolean
 593       */
 594  	public function hasSequenceNumberField() {
 595          if(!empty($this->fields)) {
 596              $fieldList = $this->getFields();
 597              foreach($fieldList as $fieldName => $fieldModel) {
 598                  if($fieldModel->get('uitype') === '4') {
 599                      return true;
 600                  }
 601              }
 602          }else{
 603              $db = PearDatabase::getInstance();
 604              $query = 'SELECT 1 FROM vtiger_field WHERE uitype=4 and tabid=?';
 605              $params = array($this->getId());
 606              $result = $db->pquery($query, $params);
 607              return $db->num_rows($result) > 0 ? true : false;
 608          }
 609          return false;
 610      }
 611  
 612      /**
 613       * Static Function to get the instance of Vtiger Module Model for the given id or name
 614       * @param mixed id or name of the module
 615       */
 616  	public static function getInstance($value) {
 617          $instance = Vtiger_Cache::get('module',$value);
 618          if(!$instance){
 619              $instance = false;
 620              $moduleObject = parent::getInstance($value);
 621              if($moduleObject) {
 622                  $instance = self::getInstanceFromModuleObject($moduleObject);
 623                  Vtiger_Cache::set('module',$value,$instance);
 624                  if (is_string($value)) {
 625                      Vtiger_Cache::set('module', $moduleObject->id, $instance);
 626                  } else if (is_int($value)) {
 627                      Vtiger_Cache::set('module', $moduleObject->name, $instance);
 628                  }
 629              }
 630          }
 631          return $instance;
 632      }
 633  
 634  
 635      /**
 636       * Function to get the instance of Vtiger Module Model from a given Vtiger_Module object
 637       * @param Vtiger_Module $moduleObj
 638       * @return Vtiger_Module_Model instance
 639       */
 640  	public static function getInstanceFromModuleObject(Vtiger_Module $moduleObj){
 641          $objectProperties = get_object_vars($moduleObj);
 642          $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'Module', $objectProperties['name']);
 643          $moduleModel = new $modelClassName();
 644          foreach($objectProperties as $properName=>$propertyValue){
 645              $moduleModel->$properName = $propertyValue;
 646          }
 647          return $moduleModel;
 648      }
 649  
 650      /**
 651       * Function to get the instance of Vtiger Module Model from a given list of key-value mapping
 652       * @param <Array> $valueArray
 653       * @return Vtiger_Module_Model instance
 654       */
 655  	public static function getInstanceFromArray($valueArray) {
 656          $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'Module', $valueArray['name']);
 657          $instance = new $modelClassName();
 658          $instance->initialize($valueArray);
 659          return $instance;
 660      }
 661  
 662      /**
 663       * Function to get all modules from CRM
 664       * @param <array> $presence
 665       * @param <array> $restrictedModulesList
 666       * @return <array> List of module models <Vtiger_Module_Model>
 667       */
 668  	public static function getAll($presence = array(), $restrictedModulesList = array()) {
 669          $db = PearDatabase::getInstance();
 670          self::preModuleInitialize2();
 671          $moduleModels = Vtiger_Cache::get('vtiger', 'modules');
 672  
 673  
 674          if(!$moduleModels){
 675              $moduleModels = array();
 676  
 677              $query = 'SELECT * FROM vtiger_tab';
 678              $params = array();
 679              if($presence) {
 680                  $query .= ' WHERE presence IN ('. generateQuestionMarks($presence) .')';
 681                  array_push($params, $presence);
 682              }
 683  
 684              $result = $db->pquery($query, $params);
 685              $noOfModules = $db->num_rows($result);
 686              for($i=0; $i<$noOfModules; ++$i) {
 687                  $row = $db->query_result_rowdata($result, $i);
 688                  $moduleModels[$row['tabid']] = self::getInstanceFromArray($row);
 689                  Vtiger_Cache::set('module',$row['tabid'], $moduleModels[$row['tabid']]);
 690                  Vtiger_Cache::set('module',$row['name'], $moduleModels[$row['tabid']]);
 691              }
 692              if(!$presence){
 693                  Vtiger_Cache::set('vtiger', 'modules',$moduleModels);
 694              }
 695          }
 696  
 697          if($presence && $moduleModels){
 698              foreach ($moduleModels as $key => $moduleModel){
 699                  if(!in_array($moduleModel->get('presence'), $presence)){
 700                      unset($moduleModels[$key]);
 701                  }
 702              }
 703          }
 704  
 705          if($restrictedModulesList && $moduleModels) {
 706              foreach ($moduleModels as $key => $moduleModel){
 707                  if(in_array($moduleModel->getName(), $restrictedModulesList)){
 708                      unset($moduleModels[$key]);
 709                  }
 710              }
 711          }
 712  
 713          return $moduleModels;
 714      }
 715  
 716  	public static function getEntityModules() {
 717          self::preModuleInitialize2();
 718          $moduleModels = Vtiger_Cache::get('vtiger','EntityModules');
 719          if(!$moduleModels){
 720              $presence = array(0, 2);
 721              $moduleModels = self::getAll($presence);
 722              $restrictedModules = array('Webmails', 'Emails', 'Integration', 'Dashboard');
 723              foreach($moduleModels as $key => $moduleModel){
 724                  if(in_array($moduleModel->getName(),$restrictedModules) || $moduleModel->get('isentitytype') != 1){
 725                      unset($moduleModels[$key]);
 726                  }
 727              }
 728              Vtiger_Cache::set('vtiger','EntityModules',$moduleModels);
 729          }
 730          return $moduleModels;
 731      }
 732  
 733      /**
 734       * Function to get the list of all accessible modules for Quick Create
 735       * @return <Array> - List of Vtiger_Record_Model or Module Specific Record Model instances
 736       */
 737  	public static function getQuickCreateModules() {
 738          $userPrivModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
 739          $db = PearDatabase::getInstance();
 740          self::preModuleInitialize2();
 741  
 742          $sql = 'SELECT DISTINCT vtiger_tab.*
 743                      FROM vtiger_field
 744                      INNER JOIN vtiger_tab ON vtiger_tab.tabid = vtiger_field.tabid
 745                      WHERE quickcreate=0 AND vtiger_tab.presence != 1';
 746          $params = array();
 747          $result = $db->pquery($sql, $params);
 748          $noOfModules = $db->num_rows($result);
 749  
 750          $quickCreateModules = array();
 751          for($i=0; $i<$noOfModules; ++$i) {
 752              $row = $db->query_result_rowdata($result, $i);
 753              if($userPrivModel->hasModuleActionPermission($row['name'], 'EditView')) {
 754                  $moduleModel = self::getInstanceFromArray($row);
 755                  $quickCreateModules[$row['name']] = $moduleModel;
 756              }
 757          }
 758          return $quickCreateModules;
 759      }
 760  
 761      /**
 762       * Function to get the list of all searchable modules
 763       * @return <Array> - List of Vtiger_Module_Model instances
 764       */
 765  	public static function getSearchableModules() {
 766          $userPrivModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
 767  
 768          $entityModules = self::getEntityModules();
 769  
 770          $searchableModules = array();
 771          foreach ($entityModules as $tabid => $moduleModel) {
 772                  $moduleName = $moduleModel->getName();
 773                  if ($moduleName == 'Users' || $moduleName == 'Emails' || $moduleName == 'Events' ) continue;
 774                  if($userPrivModel->hasModuleActionPermission($moduleModel->getId(), 'DetailView')) {
 775                          $searchableModules[$moduleName] = $moduleModel;
 776                  }
 777          }
 778          return $searchableModules;
 779      }
 780  
 781  	protected static function preModuleInitialize2() {
 782          if(!Vtiger_Cache::get('EntityField','all')){
 783              $db = PearDatabase::getInstance();
 784              // Initialize meta information - to speed up instance creation (Vtiger_ModuleBasic::initialize2)
 785              $result = $db->pquery('SELECT modulename,tablename,entityidfield,fieldname FROM vtiger_entityname', array());
 786  
 787              for($index = 0, $len = $db->num_rows($result); $index < $len; ++$index) {
 788                  
 789                  $fieldNames = $db->query_result($result, $index, 'fieldname');
 790                  $modulename = $db->query_result($result, $index, 'modulename');
 791                  //added to handle entity names for these two modules
 792                  //@Note: need to move these to database
 793                  switch($modulename) {
 794                      case 'HelpDesk': $fieldNames = 'ticket_title'; break;
 795                      case 'Documents': $fieldNames = 'notes_title';  break;
 796                  }
 797                  $entiyObj = new stdClass();
 798                  $entiyObj->basetable = $db->query_result($result, $index, 'tablename');
 799                  $entiyObj->basetableid =  $db->query_result($result, $index, 'entityidfield');
 800                  $entiyObj->fieldname =  $fieldNames;
 801                  
 802                  Vtiger_Cache::set('EntityField',$modulename,$entiyObj);
 803                  Vtiger_Cache::set('EntityField','all',true);
 804              }
 805          }
 806      }
 807  
 808      public static function getPicklistSupportedModules() {
 809          vimport('~~/modules/PickList/PickListUtils.php');
 810          $modules = getPickListModules();
 811          $modulesModelsList = array();
 812          foreach($modules as $moduleLabel => $moduleName) {
 813              $instance = new self();
 814              $instance->name = $moduleName;
 815              $instance->label = $moduleLabel;
 816              $modulesModelsList[] = $instance;
 817          }
 818          return $modulesModelsList;
 819      }
 820  
 821  	public static function getCleanInstance($moduleName){
 822          $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'Module', $moduleName);
 823          $instance = new $modelClassName();
 824          return $instance;
 825      }
 826  
 827      /**
 828       * Function to get the Quick Links for the module
 829       * @param <Array> $linkParams
 830       * @return <Array> List of Vtiger_Link_Model instances
 831       */
 832  	public function getSideBarLinks($linkParams) {
 833          $linkTypes = array('SIDEBARLINK', 'SIDEBARWIDGET');
 834          $links = Vtiger_Link_Model::getAllByType($this->getId(), $linkTypes, $linkParams);
 835  
 836          $quickLinks = array(
 837              array(
 838                  'linktype' => 'SIDEBARLINK',
 839                  'linklabel' => 'LBL_RECORDS_LIST',
 840                  'linkurl' => $this->getListViewUrl(),
 841                  'linkicon' => '',
 842              ),
 843          );
 844          foreach($quickLinks as $quickLink) {
 845              $links['SIDEBARLINK'][] = Vtiger_Link_Model::getInstanceFromValues($quickLink);
 846          }
 847  
 848          $quickWidgets = array(
 849              array(
 850                  'linktype' => 'SIDEBARWIDGET',
 851                  'linklabel' => 'LBL_RECENTLY_MODIFIED',
 852                  'linkurl' => 'module='.$this->get('name').'&view=IndexAjax&mode=showActiveRecords',
 853                  'linkicon' => ''
 854              ),
 855          );
 856          foreach($quickWidgets as $quickWidget) {
 857              $links['SIDEBARWIDGET'][] = Vtiger_Link_Model::getInstanceFromValues($quickWidget);
 858          }
 859  
 860          return $links;
 861      }
 862  
 863      /**
 864       * Function returns export query - deprecated
 865       * @param <String> $where
 866       * @return <String> export query
 867       */
 868  	public function getExportQuery($focus, $where) {
 869          $focus = CRMEntity::getInstance($this->getName());
 870          $query = $focus->create_export_query($where);
 871          return $query;
 872      }
 873  
 874      /**
 875       * Function returns the default custom filter for the module
 876       * @return <Int> custom filter id
 877       */
 878  	public function getDefaultCustomFilter() {
 879          $db = PearDatabase::getInstance();
 880  
 881          $result = $db->pquery("SELECT cvid FROM vtiger_customview WHERE setdefault = 1 AND entitytype = ?",
 882                      array($this->getName()));
 883          if ($db->num_rows($result)) {
 884              return $db->query_result($result, 0, 'cvid');
 885          }
 886          return false;
 887      }
 888  
 889      /**
 890       * Function returns latest comments for the module
 891       * @param <Vtiger_Paging_Model> $pagingModel
 892       * @return <Array>
 893       */
 894  	public function getComments($pagingModel) {
 895          $comments = array();
 896          if(!$this->isCommentEnabled()) {
 897              return $comments;
 898          }
 899          //TODO: need to handle security and performance
 900          $db = PearDatabase::getInstance();
 901  
 902          $nonAdminAccessQuery = Users_Privileges_Model::getNonAdminAccessControlQuery('ModComments');
 903  
 904          $result = $db->pquery('SELECT vtiger_crmentity.*, vtiger_modcomments.* FROM vtiger_modcomments
 905                          INNER JOIN vtiger_crmentity ON vtiger_modcomments.modcommentsid = vtiger_crmentity.crmid
 906                              AND vtiger_crmentity.deleted = 0
 907                          INNER JOIN vtiger_crmentity crmentity2 ON vtiger_modcomments.related_to = crmentity2.crmid
 908                              AND crmentity2.deleted = 0 AND crmentity2.setype = ?
 909                           '.$nonAdminAccessQuery.'
 910                          ORDER BY vtiger_crmentity.createdtime DESC LIMIT ?, ?',
 911                          array($this->getName(), $pagingModel->getStartIndex(), $pagingModel->getPageLimit()));
 912  
 913          for($i=0; $i<$db->num_rows($result); $i++) {
 914              $row = $db->query_result_rowdata($result, $i);
 915              $commentModel = Vtiger_Record_Model::getCleanInstance('ModComments');
 916              $commentModel->setData($row);
 917              $time = $commentModel->get('createdtime');
 918              $comments[$time] = $commentModel;
 919          }
 920  
 921          return $comments;
 922      }
 923  
 924      /**
 925       * Function returns comments and recent activities across module
 926       * @param <Vtiger_Paging_Model> $pagingModel
 927       * @param <String> $type - comments, updates or all
 928       * @return <Array>
 929       */
 930  	public function getHistory($pagingModel, $type=false) {
 931          if(empty($type)) {
 932              $type = 'all';
 933          }
 934          //TODO: need to handle security
 935          $comments = array();
 936          if($type == 'all' || $type == 'comments') {
 937              $modCommentsModel = Vtiger_Module_Model::getInstance('ModComments');
 938              if($modCommentsModel->isPermitted('DetailView')){
 939                  $comments = $this->getComments($pagingModel);
 940              }
 941              if($type == 'comments') {
 942                  return $comments;
 943              }
 944          }
 945  
 946          $db = PearDatabase::getInstance();
 947          $result = $db->pquery('SELECT vtiger_modtracker_basic.*
 948                                  FROM vtiger_modtracker_basic
 949                                  INNER JOIN vtiger_crmentity ON vtiger_modtracker_basic.crmid = vtiger_crmentity.crmid
 950                                      AND deleted = 0 AND module = ?
 951                                  ORDER BY vtiger_modtracker_basic.id DESC LIMIT ?, ?',
 952                                  array($this->getName(), $pagingModel->getStartIndex(), $pagingModel->getPageLimit()));
 953  
 954          $activites = array();
 955          for($i=0; $i<$db->num_rows($result); $i++) {
 956              $row = $db->query_result_rowdata($result, $i);
 957              if(Users_Privileges_Model::isPermitted($row['module'], 'DetailView', $row['crmid'])){
 958                  $modTrackerRecorModel = new ModTracker_Record_Model();
 959                  $modTrackerRecorModel->setData($row)->setParent($row['crmid'], $row['module']);
 960                  $time = $modTrackerRecorModel->get('changedon');
 961                  $activites[$time] = $modTrackerRecorModel;
 962              }
 963          }
 964  
 965          $history = array_merge($activites, $comments);
 966  
 967          $dateTime = array();
 968          foreach($history as $time=>$model) {
 969                  $dateTime[] = $time;
 970          }
 971  
 972          if(!empty($history)) {
 973              array_multisort($dateTime,SORT_DESC,SORT_STRING,$history);
 974              return $history;
 975          }
 976          return false;
 977      }
 978  
 979      /**
 980       * Function returns the Calendar Events for the module
 981       * @param <String> $mode - upcoming/overdue mode
 982       * @param <Vtiger_Paging_Model> $pagingModel - $pagingModel
 983       * @param <String> $user - all/userid
 984       * @param <String> $recordId - record id
 985       * @return <Array>
 986       */
 987  	function getCalendarActivities($mode, $pagingModel, $user, $recordId = false) {
 988          $currentUser = Users_Record_Model::getCurrentUserModel();
 989          $db = PearDatabase::getInstance();
 990  
 991          if (!$user) {
 992              $user = $currentUser->getId();
 993          }
 994  
 995          $nowInUserFormat = Vtiger_Datetime_UIType::getDisplayDateValue(date('Y-m-d H:i:s'));
 996          $nowInDBFormat = Vtiger_Datetime_UIType::getDBDateTimeValue($nowInUserFormat);
 997          list($currentDate, $currentTime) = explode(' ', $nowInDBFormat);
 998  
 999          $query = "SELECT vtiger_crmentity.crmid, crmentity2.crmid AS parent_id, vtiger_crmentity.smownerid, vtiger_crmentity.setype, vtiger_activity.* FROM vtiger_activity
1000                      INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_activity.activityid
1001                      INNER JOIN vtiger_seactivityrel ON vtiger_seactivityrel.activityid = vtiger_activity.activityid
1002                      INNER JOIN vtiger_crmentity AS crmentity2 ON vtiger_seactivityrel.crmid = crmentity2.crmid AND crmentity2.deleted = 0 AND crmentity2.setype = ?
1003                      LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid";
1004  
1005          $query .= Users_Privileges_Model::getNonAdminAccessControlQuery('Calendar');
1006  
1007          $query .= " WHERE vtiger_crmentity.deleted=0
1008                      AND (vtiger_activity.activitytype NOT IN ('Emails'))
1009                      AND (vtiger_activity.status is NULL OR vtiger_activity.status NOT IN ('Completed', 'Deferred'))
1010                      AND (vtiger_activity.eventstatus is NULL OR vtiger_activity.eventstatus NOT IN ('Held'))";
1011  
1012          if ($recordId) {
1013              $query .= " AND vtiger_seactivityrel.crmid = ?";
1014          } elseif ($mode === 'upcoming') {
1015              $query .= " AND due_date >= '$currentDate'";
1016          } elseif ($mode === 'overdue') {
1017              $query .= " AND due_date < '$currentDate'";
1018          }
1019  
1020          $params = array($this->getName());
1021          if($user != 'all' && $user != '') {
1022              if($user === $currentUser->id) {
1023                  $query .= " AND vtiger_crmentity.smownerid = ?";
1024                  array_push($params, $user);
1025              }
1026          }
1027  
1028          $query .= " ORDER BY date_start, time_start LIMIT ". $pagingModel->getStartIndex() .", ". ($pagingModel->getPageLimit()+1);
1029  
1030  
1031          if ($recordId) {
1032              array_push($params, $recordId);
1033          }
1034  
1035          $result = $db->pquery($query, $params);
1036          $numOfRows = $db->num_rows($result);
1037  
1038          $groupsIds = Vtiger_Util_Helper::getGroupsIdsForUsers($currentUser->getId());
1039          $activities = array();
1040          for($i=0; $i<$numOfRows; $i++) {
1041              $newRow = $db->query_result_rowdata($result, $i);
1042              $model = Vtiger_Record_Model::getCleanInstance('Calendar');
1043              $ownerId = $newRow['smownerid'];
1044              $currentUser = Users_Record_Model::getCurrentUserModel();
1045              $visibleFields = array('activitytype','date_start','time_start','due_date','time_end','assigned_user_id','visibility','smownerid','crmid');
1046              $visibility = true;
1047              if(in_array($ownerId, $groupsIds)) {
1048                  $visibility = false;
1049              } else if($ownerId == $currentUser->getId()){
1050                  $visibility = false;
1051              }
1052              if(!$currentUser->isAdminUser() && $newRow['activitytype'] != 'Task' && $newRow['visibility'] == 'Private' && $ownerId && $visibility) {
1053                  foreach($newRow as $data => $value) {
1054                      if(in_array($data, $visibleFields) != -1) {
1055                          unset($newRow[$data]);
1056                      }
1057                  }
1058                  $newRow['subject'] = vtranslate('Busy','Events').'*';
1059              }
1060              if($newRow['activitytype'] == 'Task') {
1061                  unset($newRow['visibility']);
1062              }
1063  
1064              $model->setData($newRow);
1065              $model->setId($newRow['crmid']);
1066              $activities[] = $model;
1067          }
1068  
1069          $pagingModel->calculatePageRange($activities);
1070          if($numOfRows > $pagingModel->getPageLimit()){
1071              array_pop($activities);
1072              $pagingModel->set('nextPageExists', true);
1073          } else {
1074              $pagingModel->set('nextPageExists', false);
1075          }
1076  
1077          return $activities;
1078      }
1079  
1080      /**
1081       * Function to get list of fields which are required while importing records
1082       * @param <String> $module
1083       * @return <Array> list of fields
1084       */
1085  	function getRequiredFields($module = '') {
1086          $moduleInstance = CRMEntity::getInstance($this->getName());
1087          $requiredFields = $moduleInstance->required_fields;
1088          if (empty ($requiredFields)) {
1089              if (empty ($module)) {
1090                  $module = $this->getName();
1091              }
1092              $moduleInstance->initRequiredFields($module);
1093          }
1094          return $moduleInstance->required_fields;
1095      }
1096  
1097      /**
1098       * Function to get the module is permitted to specific action
1099       * @param <String> $actionName
1100       * @return <boolean>
1101       */
1102  	public function isPermitted($actionName) {
1103          return ($this->isActive() && Users_Privileges_Model::isPermitted($this->getName(), $actionName));
1104      }
1105  
1106      /**
1107       * Function to get Specific Relation Query for this Module
1108       * @param <type> $relatedModule
1109       * @return <type>
1110       */
1111  	public function getSpecificRelationQuery($relatedModule) {
1112          if($relatedModule == 'Documents'){
1113              return ' AND vtiger_notes.filestatus = 1 ';
1114          }
1115          return;
1116      }
1117  
1118      /**
1119       * Function to get where condition query for dashboards
1120       * @param <Integer> $owner
1121       * @return <String> query
1122       */
1123  	public function getOwnerWhereConditionForDashBoards ($owner) {
1124          $currentUserModel = Users_Record_Model::getCurrentUserModel();
1125          $sharingAccessModel = Settings_SharingAccess_Module_Model::getInstance($this->getName());
1126          $params = array();
1127          if(!empty($owner) && $currentUserModel->isAdminUser()) {//If admin user, then allow users data
1128              $ownerSql =  ' smownerid = '. $owner;
1129              $params[] = $owner;
1130          } else if(!empty($owner)){//If not admin user, then check sharing access for that module
1131              if($sharingAccessModel->isPrivate()) {
1132                  $subordinateUserModels = $currentUserModel->getSubordinateUsers();
1133                  $subordinateUsers = array();
1134                  foreach($subordinateUserModels as $id=>$name) {
1135                      $subordinateUsers[] = $id;
1136                  }
1137                  if(in_array($owner, $subordinateUsers)) {
1138                      $ownerSql = ' smownerid = '. $owner ;
1139                  } else {
1140                      $ownerSql = ' smownerid = '. $currentUserModel->getId();
1141                  }
1142              } else {
1143                  $ownerSql = ' smownerid = '. $owner ;
1144              }
1145          } else {//If no owner filter, then check if the module access is Private
1146              if($sharingAccessModel->isPrivate() && (!$currentUserModel->isAdminUser())) {
1147                  $subordinateUserModels = $currentUserModel->getSubordinateUsers();
1148                  foreach($subordinateUserModels as $id=>$name) {
1149                      $subordinateUsers[] = $id;
1150                      $params[] = $id;
1151                  }
1152                  if($subordinateUsers) {
1153                      $ownerSql =  ' smownerid IN ('. implode(',' , $subordinateUsers) .')';
1154                  } else {
1155                      $ownerSql =  ' smownerid = '.$currentUserModel->getId();
1156                  }
1157              }
1158          }
1159          return $ownerSql;
1160      }
1161  
1162      /**
1163       * Function to get Settings links
1164       * @return <Array>
1165       */
1166  	public function getSettingLinks(){
1167          if(!$this->isEntityModule()) {
1168              return array();
1169          }
1170          vimport('~~modules/com_vtiger_workflow/VTWorkflowUtils.php');
1171  
1172          $layoutEditorImagePath = Vtiger_Theme::getImagePath('LayoutEditor.gif');
1173          $editWorkflowsImagePath = Vtiger_Theme::getImagePath('EditWorkflows.png');
1174          $settingsLinks = array();
1175  
1176          $settingsLinks[] = array(
1177                      'linktype' => 'LISTVIEWSETTING',
1178                      'linklabel' => 'LBL_EDIT_FIELDS',
1179                      'linkurl' => 'index.php?parent=Settings&module=LayoutEditor&sourceModule='.$this->getName(),
1180                      'linkicon' => $layoutEditorImagePath
1181          );
1182  
1183          if(VTWorkflowUtils::checkModuleWorkflow($this->getName())) {
1184              $settingsLinks[] = array(
1185                      'linktype' => 'LISTVIEWSETTING',
1186                      'linklabel' => 'LBL_EDIT_WORKFLOWS',
1187                      'linkurl' => 'index.php?parent=Settings&module=Workflows&view=List&sourceModule='.$this->getName(),
1188                      'linkicon' => $editWorkflowsImagePath
1189              );
1190          }
1191  
1192          $settingsLinks[] = array(
1193                      'linktype' => 'LISTVIEWSETTING',
1194                      'linklabel' => 'LBL_EDIT_PICKLIST_VALUES',
1195                      'linkurl' => 'index.php?parent=Settings&module=Picklist&view=Index&source_module='.$this->getName(),
1196                      'linkicon' => ''
1197          );
1198  
1199          if($this->hasSequenceNumberField()) {
1200              $settingsLinks[] = array(
1201                  'linktype' => 'LISTVIEWSETTING',
1202                  'linklabel' => 'LBL_MODULE_SEQUENCE_NUMBERING',
1203                  'linkurl' => 'index.php?parent=Settings&module=Vtiger&view=CustomRecordNumbering&sourceModule='.$this->getName(),
1204                  'linkicon' => ''
1205              );
1206          }
1207  
1208          $webformSupportedModule = Settings_Webforms_Module_Model :: getSupportedModulesList();
1209          if(array_key_exists($this->getName(), $webformSupportedModule)){
1210              $settingsLinks[] =    array(
1211                      'linktype' => 'LISTVIEWSETTING',
1212                      'linklabel' => 'LBL_SETUP_WEBFORMS',
1213                      'linkurl' => 'index.php?module=Webforms&parent=Settings&view=Edit&sourceModule='.$this->getName(),
1214                      'linkicon' => '');
1215          }
1216          return $settingsLinks;
1217      }
1218  
1219      public function isCustomizable() {
1220          return $this->customized == '1' ? true : false;
1221      }
1222  
1223      public function isModuleUpgradable() {
1224          return $this->isCustomizable() ? true : false;
1225      }
1226  
1227      public function isExportable() {
1228          return $this->isCustomizable() ? true : false;
1229      }
1230  
1231      /**
1232       * Function to get list of field for summary view
1233       * @return <Array> list of field models <Vtiger_Field_Model>
1234       */
1235  	public function getSummaryViewFieldsList() {
1236          if (!$this->summaryFields) {
1237              $summaryFields = array();
1238              $fields = $this->getFields();
1239              foreach ($fields as $fieldName => $fieldModel) {
1240                  if ($fieldModel->isSummaryField() && $fieldModel->isActiveField()) {
1241                      $summaryFields[$fieldName] = $fieldModel;
1242                  }
1243              }
1244              $this->summaryFields = $summaryFields;
1245          }
1246          return $this->summaryFields;
1247      }
1248  
1249  
1250      /**
1251       * Function returns query for module record's search
1252       * @param <String> $searchValue - part of record name (label column of crmentity table)
1253       * @param <Integer> $parentId - parent record id
1254       * @param <String> $parentModule - parent module name
1255       * @return <String> - query
1256       */
1257  	public function getSearchRecordsQuery($searchValue, $parentId=false, $parentModule=false) {
1258          return "SELECT * FROM vtiger_crmentity WHERE label LIKE '%$searchValue%' AND vtiger_crmentity.deleted = 0";
1259      }
1260  
1261      /**
1262       * Function searches the records in the module, if parentId & parentModule
1263       * is given then searches only those records related to them.
1264       * @param <String> $searchValue - Search value
1265       * @param <Integer> $parentId - parent recordId
1266       * @param <String> $parentModule - parent module name
1267       * @return <Array of Vtiger_Record_Model>
1268       */
1269  	public function searchRecord($searchValue, $parentId=false, $parentModule=false, $relatedModule=false) {
1270          if(!empty($searchValue) && empty($parentId) && empty($parentModule)) {
1271              $matchingRecords = Vtiger_Record_Model::getSearchResult($searchValue, $this->getName());
1272          } else if($parentId && $parentModule) {
1273              $db = PearDatabase::getInstance();
1274              $result = $db->pquery($this->getSearchRecordsQuery($searchValue, $parentId, $parentModule), array());
1275              $noOfRows = $db->num_rows($result);
1276  
1277              $moduleModels = array();
1278              $matchingRecords = array();
1279              for($i=0; $i<$noOfRows; ++$i) {
1280                  $row = $db->query_result_rowdata($result, $i);
1281                  if(Users_Privileges_Model::isPermitted($row['setype'], 'DetailView', $row['crmid'])){
1282                      $row['id'] = $row['crmid'];
1283                      $moduleName = $row['setype'];
1284                      if(!array_key_exists($moduleName, $moduleModels)) {
1285                          $moduleModels[$moduleName] = Vtiger_Module_Model::getInstance($moduleName);
1286                      }
1287                      $moduleModel = $moduleModels[$moduleName];
1288                      $modelClassName = Vtiger_Loader::getComponentClassName('Model', 'Record', $moduleName);
1289                      $recordInstance = new $modelClassName();
1290                      $matchingRecords[$moduleName][$row['id']] = $recordInstance->setData($row)->setModuleFromInstance($moduleModel);
1291                  }
1292              }
1293          }
1294  
1295          return $matchingRecords;
1296      }
1297  
1298      /**
1299       * Function to get relation query for particular module with function name
1300       * @param <record> $recordId
1301       * @param <String> $functionName
1302       * @param Vtiger_Module_Model $relatedModule
1303       * @return <String>
1304       */
1305  	public function getRelationQuery($recordId, $functionName, $relatedModule) {
1306          $relatedModuleName = $relatedModule->getName();
1307  
1308          $focus = CRMEntity::getInstance($this->getName());
1309          $focus->id = $recordId;
1310  
1311          $result = $focus->$functionName($recordId, $this->getId(), $relatedModule->getId());
1312          $query = $result['query'] .' '. $this->getSpecificRelationQuery($relatedModuleName);
1313          $nonAdminQuery = $this->getNonAdminAccessControlQueryForRelation($relatedModuleName);
1314  
1315          //modify query if any module has summary fields, those fields we are displayed in related list of that module
1316          $relatedListFields = $relatedModule->getConfigureRelatedListFields();
1317          if(count($relatedListFields) > 0) {
1318              $currentUser = Users_Record_Model::getCurrentUserModel();
1319              $queryGenerator = new QueryGenerator($relatedModuleName, $currentUser);
1320              $queryGenerator->setFields($relatedListFields);
1321              $selectColumnSql = $queryGenerator->getSelectClauseColumnSQL();
1322              $newQuery = spliti('FROM', $query);
1323              $selectColumnSql = 'SELECT DISTINCT vtiger_crmentity.crmid,'.$selectColumnSql;
1324              $query = $selectColumnSql.' FROM '.$newQuery[1];
1325          }
1326  
1327          if ($nonAdminQuery) {
1328              $query = appendFromClauseToQuery($query, $nonAdminQuery);
1329          }
1330  
1331          return $query;
1332      }
1333  
1334      /**
1335       * Function to get Non admin access control query
1336       * @param <String> $relatedModuleName
1337       * @return <String>
1338       */
1339  	public function getNonAdminAccessControlQueryForRelation($relatedModuleName) {
1340          $modulesList = array('Faq', 'PriceBook', 'Vendors', 'Users');
1341  
1342          if (!in_array($relatedModuleName, $modulesList)) {
1343              return Users_Privileges_Model::getNonAdminAccessControlQuery($relatedModuleName);
1344          }
1345      }
1346  
1347      /**
1348       * Function returns the default column for Alphabetic search
1349       * @return <String> columnname
1350       */
1351  	public function getAlphabetSearchField(){
1352          $focus = CRMEntity::getInstance($this->get('name'));
1353          return $focus->def_basicsearch_col;
1354      }
1355  
1356      /**
1357       * Function which will give complusory mandatory fields
1358       * @return type
1359       */
1360      public function getCumplosoryMandatoryFieldList() {
1361          $focus = CRMEntity::getInstance($this->getName());
1362          $compulsoryMandtoryFields = $focus->mandatory_fields;
1363          if(empty($compulsoryMandtoryFields)) {
1364              $compulsoryMandtoryFields = array();
1365          }
1366          return $compulsoryMandtoryFields;
1367      }
1368  
1369  
1370      /**
1371       * Function returns all the related modules for workflows create entity task
1372       * @return <JSON>
1373       */
1374  	public function vtJsonDependentModules() {
1375          vimport('~~/modules/com_vtiger_workflow/WorkflowComponents.php');
1376          $db = PearDatabase::getInstance();
1377          $param = array('modulename'=>$this->getName());
1378          return vtJsonDependentModules($db, $param);
1379      }
1380  
1381      /**
1382       * Function returns mandatory field Models
1383       * @return <Array of Vtiger_Field_Model>
1384       */
1385  	public function getMandatoryFieldModels(){
1386          $fields = $this->getFields();
1387          $mandatoryFields = array();
1388          if ($fields) {
1389              foreach ($fields as $field) {
1390                  if ($field->isMandatory()) {
1391                      $mandatoryFields[] = $field;
1392                  }
1393              }
1394          }
1395          return $mandatoryFields;
1396      }
1397  
1398  	public function getRelatedModuleRecordIds(Vtiger_Request $request, $recordIds = array()) {
1399          $db = PearDatabase::getInstance();
1400          $relatedModules = $request->get('related_modules');
1401          $focus = CRMEntity::getInstance($this->getName());
1402          $relatedModuleMapping = $focus->related_module_table_index;
1403          $relatedIds = array();
1404          if(!empty($relatedModules)) {
1405              for ($i=0; $i<count($relatedModules); $i++) {
1406                  $params = array();
1407                  $module = $relatedModules[$i];
1408                  $tablename = $relatedModuleMapping[$module]['table_name'];
1409                  $tabIndex = $relatedModuleMapping[$module]['table_index'];
1410                  $relIndex = $relatedModuleMapping[$module]['rel_index'];
1411                  $sql = "SELECT vtiger_crmentity.crmid FROM vtiger_crmentity";
1412                  if($tablename == 'vtiger_crmentityrel'){
1413                      $sql .= " INNER JOIN $tablename ON ($tablename.relcrmid = vtiger_crmentity.crmid OR $tablename.crmid = vtiger_crmentity.crmid)
1414                          WHERE ($tablename.crmid IN (".  generateQuestionMarks($recordIds).")) OR ($tablename.relcrmid IN (".  generateQuestionMarks($recordIds)."))";
1415                      foreach ($recordIds as $key => $recordId) {
1416                          array_push($params, $recordId);
1417                      }
1418                  } else {
1419                      $sql .= " INNER JOIN $tablename ON $tablename.$tabIndex = vtiger_crmentity.crmid
1420                          WHERE $tablename.$relIndex IN (".  generateQuestionMarks($recordIds).")";
1421                  }
1422                  foreach ($recordIds as $key => $recordId) {
1423                      array_push($params, $recordId);
1424                  }
1425                  $result1 = $db->pquery($sql, $params);
1426                  $num_rows = $db->num_rows($result1);
1427                  for($j=0; $j<$num_rows; $j++){
1428                      $relatedIds[] = $db->query_result($result1, $j, 'crmid');
1429                  }
1430              }
1431              return $relatedIds;
1432          } else {
1433              return $relatedIds;
1434          }
1435      }
1436  
1437  	public function transferRecordsOwnership($transferOwnerId, $relatedModuleRecordIds){
1438          $db = PearDatabase::getInstance();
1439          $query = 'UPDATE vtiger_crmentity SET smownerid = ? WHERE crmid IN ('.  generateQuestionMarks($relatedModuleRecordIds).')';
1440          $db->pquery($query, array($transferOwnerId,$relatedModuleRecordIds));
1441      }
1442  
1443      /**
1444      * Function to get orderby sql from orderby field
1445      */
1446      public function getOrderBySql($orderBy){
1447               $orderByField = $this->getFieldByColumn($orderBy);
1448               return $orderByField->get('table') . '.' . $orderBy;
1449      }
1450  
1451       public function getDefaultSearchField(){
1452          $nameFields = $this->getNameFields();
1453          //To make the first field as the name field
1454          return $nameFields[0];
1455      }
1456  
1457      /**
1458       * Function to get popup view fields
1459       */
1460  	public function getPopupViewFieldsList(){
1461          $summaryFieldsList = $this->getSummaryViewFieldsList();
1462  
1463          if(count($summaryFieldsList) > 0){
1464               $popupFields = array_keys($summaryFieldsList);
1465          }else{
1466              $popupFields = array_values($this->getRelatedListFields());
1467          }
1468          return $popupFields;
1469      }
1470  
1471      /**
1472       * Funxtion to identify if the module supports quick search or not
1473       */
1474      public function isQuickSearchEnabled() {
1475          return true;
1476      }
1477  
1478      /**
1479       * function to check if the extension module is permitted for utility action
1480       * @return <boolean> false
1481       */
1482      public function isUtilityActionEnabled() {
1483          return false;
1484      }
1485      
1486      public function isListViewNameFieldNavigationEnabled() {
1487          return true;
1488      }
1489  }


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