Пример #1
0
 /**
  * Returns true if the object blongs to the texmplate context ($memberIds)
  * @author Ignacio Vazquez - elpepe.uy@gmail.com
  * @param ContentDataObject $object
  * @param array $memberIds
  */
 static function validateObjectContext($object, $memberIds)
 {
     $valid = true;
     // Dimensiones requeridas para el tipo de objecto
     $dimensions = Dimensions::getAllowedDimensions(self::instance()->getObjectTypeId());
     $requiredDimensions = array();
     foreach ($dimensions as $dim) {
         if ($dim['is_required']) {
             $requiredDimensions[$dim['dimension_id']] = $dim;
             // Performance, dim id in the array key  ! ! !
         }
     }
     // Miembros del Objeto
     $objMembers = $object->getMemberIds();
     // P/cada miembro
     foreach ($objMembers as $mid) {
         $member = Members::instance()->findById($mid);
         if ($member instanceof Member) {
             /* @var  $member Member */
             $did = $member->getDimensionId();
             // Si la dimension del miembro esta en la requeridas
             if ($requiredDimensions[$did]) {
                 if (!in_array($mid, $memberIds)) {
                     $valid = false;
                 }
             }
         }
     }
     if (!$valid) {
         throw new DAOValidationError($this, array(lang("template members do not match object members")));
     }
 }
Пример #2
0
 function getInstance()
 {
     if (!isset(self::$instance[get_class()])) {
         self::$instance = new Members();
     }
     return self::$instance;
 }
 static function getChildObjectTypes($member_id)
 {
     $m = Members::instance()->findById($member_id);
     $d = $m->getDimensionId();
     $parent_object_type_id = $m->getObjectTypeId();
     $sql = "\n  \t\t\tSELECT distinct(child_object_type_id) FROM " . TABLE_PREFIX . "dimension_object_type_hierarchies \n  \t\t\tWHERE \n  \t\t \t\tdimension_id = {$d} AND \n  \t\t \t\tparent_object_type_id = {$parent_object_type_id} ";
     return self::findAll(array("conditions" => "object_type_id IN ({$sql}) AND dimension_id = {$d}"));
 }
 static function getChildObjectTypes($member)
 {
     if ($member instanceof Member) {
         $member_id = $member->getId();
         $m = $member;
     } else {
         $member_id = $member;
         $m = Members::instance()->findById($member_id);
         if (!$m instanceof Member) {
             return array();
         }
     }
     $d = $m->getDimensionId();
     $parent_object_type_id = $m->getObjectTypeId();
     $sql = "\r\n  \t\t\tSELECT distinct(child_object_type_id) FROM " . TABLE_PREFIX . "dimension_object_type_hierarchies \r\n  \t\t\tWHERE \r\n  \t\t \t\tdimension_id = {$d} AND enabled=1 AND\r\n  \t\t \t\tparent_object_type_id = {$parent_object_type_id} ";
     return self::findAll(array("conditions" => "object_type_id IN ({$sql}) AND dimension_id = {$d}"));
 }
  	static function getChildObjectTypes($member) {
  		if ($member instanceof Member) {
  			$member_id = $member->getId();
  			$m = $member;
  		} else {
  			$member_id = $member;
	  		$m = Members::instance()->findById($member_id);
	  		if (!$m instanceof Member) return array();
  		}
  		
  		$d = $m->getDimensionId() ;
  		$parent_object_type_id = $m->getObjectTypeId() ;
  		$sql = "
  			SELECT distinct(child_object_type_id) FROM ".TABLE_PREFIX."dimension_object_type_hierarchies 
  			WHERE 
  		 		dimension_id = $d AND 
  		 		parent_object_type_id = $parent_object_type_id ";
  		return  self::findAll(array("conditions"=>"object_type_id IN ($sql) AND dimension_id = $d")); 
  	}
Пример #6
0
 function quick_add_form()
 {
     $this->setLayout('empty');
     if ($dimension_id = array_var($_GET, 'dimension_id')) {
         $dimension = Dimensions::instance()->findById($dimension_id);
         $dimensionOptions = $dimension->getOptions(true);
         $object_Types = array();
         $parent_member_id = array_var($_GET, 'parent_member_id');
         if ($parent_member_id) {
             $parent_member = Members::instance()->findById($parent_member_id);
             $object_types = DimensionObjectTypes::getChildObjectTypes($parent_member_id);
         } else {
             $object_types = DimensionObjectTypes::instance()->findAll(array("conditions" => "dimension_id = {$dimension_id} AND is_root = 1 "));
         }
         if (count($object_types)) {
             if (count($object_types) == 1) {
                 // Input Hidden
                 tpl_assign('object_type', $object_types[0]);
                 tpl_assign('object_type_name', ObjectTypes::instance()->findById($object_types[0]->getObjectTypeId())->getName());
             } else {
                 // Input combo
                 tpl_assign('object_types', $object_types);
             }
         } else {
             tpl_assign("error_msg", $parent_member->getName() . " does not accept child nodes ");
         }
         $editUrls = array();
         foreach ($object_types as $object_type) {
             /* @var $object_type DimensionObjectType */
             if (ObjectTypes::instance()->findById($object_type->getObjectTypeId())->getType() != 'dimension_object') {
                 continue;
             }
             $options = $object_type->getOptions(1);
             if (isset($options->defaultAjax) && $options->defaultAjax->controller != "dashboard") {
                 $editUrls[$object_type->getObjectTypeId()] = get_url($options->defaultAjax->controller, 'add');
             } else {
                 $t = ObjectTypes::instance()->findById($object_type->getObjectTypeId());
                 /* @var $t ObjectType */
                 $class_name = ucfirst($t->getName()) . "Controller";
                 if ($t && controller_exists($t->getName(), $t->getPluginId())) {
                     $editUrls[$object_type->getObjectTypeId()] = get_url($t->getName(), 'add');
                 } else {
                     $editUrls[$object_type->getObjectTypeId()] = get_url('member', 'add', array("dim_id" => $dimension_id));
                 }
             }
         }
         tpl_assign('editUrls', $editUrls);
         tpl_assign('parent_member_id', $parent_member_id);
         tpl_assign('dimension_id', $dimension_id);
         if (is_object($dimensionOptions) && is_object($dimensionOptions->quickAdd) && $dimensionOptions->quickAdd->formAction) {
             tpl_assign('form_action', ROOT_URL . "/" . $dimensionOptions->quickAdd->formAction);
         } else {
             tpl_assign('form_action', get_url('member', 'add', array('quick' => '1')));
         }
     } else {
         die("SORRY. Invalid dimension");
     }
 }
Пример #7
0
 /**
 * Return manager instance
 *
 * @access protected
 * @param void
 * @return Members 
 */
 function manager() {
   if(!($this->manager instanceof Members)) $this->manager = Members::instance();
   return $this->manager;
 } // manager
Пример #8
0
/**
 * 
 * Fires AFTER User is deleted - Contact.class.php
 * Deletes All members associated with that user  
 * @param Contact $user
 */
function core_dimensions_after_user_deleted(Contact $user, $null)
{
    $uid = $user->getId();
    //Delete MyStuff
    if ($myStuff = Members::findById($user->getPersonalMemberId())) {
        $myStuff->delete();
    }
    // Delete All members
    $members = Members::instance()->findByObjectId($uid);
    if (count($members)) {
        foreach ($members as $member) {
            $member->delete();
            evt_add("reload dimension tree", $member->getDimensionId());
        }
    }
}
 function quick_add_form()
 {
     ajx_current("empty");
     $this->setLayout('empty');
     $dimension_id = array_var($_GET, 'dimension_id');
     $dimension = is_numeric($dimension_id) ? Dimensions::instance()->findById($dimension_id) : null;
     if ($dimension instanceof Dimension) {
         $object_Types = array();
         $parent_member_id = array_var($_GET, 'parent_member_id');
         $parent_member = Members::instance()->findById($parent_member_id);
         if ($parent_member instanceof Member) {
             $object_types = DimensionObjectTypes::getChildObjectTypes($parent_member);
             if (count($object_types) == 0) {
                 $parent_member = null;
                 $object_types = DimensionObjectTypes::instance()->findAll(array("conditions" => "enabled=1 AND dimension_id = {$dimension_id} AND is_root = 1 AND object_type_id<>(SELECT id from " . TABLE_PREFIX . "object_types WHERE name='company')"));
             }
         } else {
             $object_types = DimensionObjectTypes::instance()->findAll(array("conditions" => "enabled=1 AND dimension_id = {$dimension_id} AND is_root = 1 AND object_type_id<>(SELECT id from " . TABLE_PREFIX . "object_types WHERE name='company')"));
         }
         $obj_types = array();
         $editUrls = array();
         foreach ($object_types as $object_type) {
             $options = $object_type->getOptions(1);
             if (isset($options->defaultAjax) && $options->defaultAjax->controller != "dashboard") {
                 $editUrls[$object_type->getObjectTypeId()] = get_url($options->defaultAjax->controller, 'add');
             } else {
                 $t = ObjectTypes::instance()->findById($object_type->getObjectTypeId());
                 $obj_types[$t->getId()] = $t;
                 $class_name = ucfirst($t->getName()) . "Controller";
                 $controller_exists = controller_exists($t->getName(), $t->getPluginId());
                 if ($controller_exists) {
                     Env::useController(ucfirst($t->getName()));
                     eval('$controller = new ' . $class_name . '();');
                 }
                 if ($t && controller_exists($t->getName(), $t->getPluginId()) && $t->getHandlerClass() != '' && $controller_exists && method_exists($controller, 'add')) {
                     $params = array("type" => $t->getId());
                     if ($parent_member instanceof Member) {
                         $params['parent'] = $parent_member->getId();
                     }
                     $editUrls[$t->getId()] = get_url($t->getName(), 'add', $params);
                 } else {
                     $params = array("dim_id" => $dimension_id, "type" => $t->getId());
                     if ($parent_member instanceof Member) {
                         $params['parent'] = $parent_member->getId();
                     }
                     $editUrls[$t->getId()] = get_url('member', 'add', $params);
                 }
             }
         }
         $urls = array();
         foreach ($editUrls as $ot_id => $url) {
             $ot = array_var($obj_types, $ot_id);
             if ($ot instanceof ObjectType) {
                 $link_text = ucfirst(strtolower(lang('new ' . $ot->getName())));
                 $iconcls = $ot->getIconClass();
             } else {
                 $link_text = lang('new');
                 $iconcls = "";
             }
             $urls[] = array('link_text' => $link_text, 'url' => $url, 'iconcls' => $iconcls);
         }
         Hook::fire('member_quick_add_urls', array('dimension' => $dimension, 'object_types' => $object_types, 'parent_member' => $parent_member), $urls);
         if (count($urls) > 1) {
             ajx_extra_data(array('draw_menu' => 1, 'urls' => $urls));
         } else {
             ajx_extra_data(array('urls' => $urls));
         }
     } else {
         Logger::log("Invalid dimension: {$dimension_id}");
     }
 }
Пример #10
0
 static function getMembersByObjectAndDimension($object_id, $dimension_id, $extra_conditions = "")
 {
     $sql = "\n  \t\t\t\tSELECT distinct(id) \n  \t\t\t\tFROM " . TABLE_PREFIX . "object_members om \n  \t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m ON om.member_id = m.id \n  \t\t\t\tWHERE \n  \t\t\t\t\tdimension_id = {$dimension_id} AND \n  \t\t\t\t\tom.object_id = {$object_id} \n  \t\t\t\t\t{$extra_conditions}";
     $result = array();
     $rows = DB::executeAll($sql);
     if (!is_array($rows)) {
         return $result;
     }
     foreach ($rows as $row) {
         $member = Members::instance()->findById($row['id']);
         if ($member instanceof Member) {
             $result[] = $member;
         }
     }
     return $result;
 }
 /**
  * Execute the script
  *
  * @param void
  * @return boolean
  */
 function execute()
 {
     // ---------------------------------------------------
     //  Check MySQL version
     // ---------------------------------------------------
     $mysql_version = mysql_get_server_info($this->database_connection);
     if ($mysql_version && version_compare($mysql_version, '4.1', '>=')) {
         $constants['DB_CHARSET'] = 'utf8';
         @mysql_query("SET NAMES 'utf8'", $this->database_connection);
         tpl_assign('default_collation', $default_collation = 'collate utf8_unicode_ci');
         tpl_assign('default_charset', $default_charset = 'DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci');
     } else {
         tpl_assign('default_collation', $default_collation = '');
         tpl_assign('default_charset', $default_charset = '');
     }
     // if
     $installed_version = installed_version();
     $t_prefix = TABLE_PREFIX;
     if (version_compare($installed_version, '1.7.5') <= 0 && TABLE_PREFIX != "fo_") {
         $t_prefix = "fo_";
     }
     tpl_assign('table_prefix', $t_prefix);
     if (defined('DB_ENGINE')) {
         tpl_assign('engine', DB_ENGINE);
     } else {
         tpl_assign('engine', 'InnoDB');
     }
     // ---------------------------------------------------
     //  Execute migration
     // ---------------------------------------------------
     $additional_upgrade_steps = array();
     // RUN QUERIES
     $total_queries = 0;
     $executed_queries = 0;
     $upgrade_script = "";
     // upgrading from version 1.x
     if (version_compare($installed_version, '2.0.0.0-beta') < 0) {
         ini_set('memory_limit', '1024M');
         @set_time_limit(0);
         $upgrade_script .= tpl_fetch(get_template_path('db_migration/2_0_asado'));
         if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
             $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
         } else {
             $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
             return false;
         }
         $_SESSION['from_feng1'] = true;
         $upgrade_script = "";
         @unlink(ROOT . '/cache/autoloader.php');
         include ROOT . '/environment/classes/AutoLoader.class.php';
         include ROOT . '/environment/constants.php';
         if (!($callbacks = spl_autoload_functions())) {
             $callbacks = array();
         }
         foreach ($callbacks as $callback) {
             spl_autoload_unregister($callback);
         }
         spl_autoload_register('feng_upg_autoload');
         foreach ($callbacks as $callback) {
             spl_autoload_register($callback);
         }
         @(include ROOT . '/cache/autoloader.php');
         define('DONT_LOG', true);
         define('FORCED_TABLE_PREFIX', 'fo_');
         if (!defined('FILE_STORAGE_FILE_SYSTEM')) {
             define('FILE_STORAGE_FILE_SYSTEM', 'fs');
         }
         if (!defined('FILE_STORAGE_MYSQL')) {
             define('FILE_STORAGE_MYSQL', 'mysql');
         }
         if (!defined('MAX_SEARCHABLE_FILE_SIZE')) {
             define('MAX_SEARCHABLE_FILE_SIZE', 1048576);
         }
         try {
             DB::connect(DB_ADAPTER, array('host' => DB_HOST, 'user' => DB_USER, 'pass' => DB_PASS, 'name' => DB_NAME, 'persist' => DB_PERSIST));
             if (defined('DB_CHARSET') && trim(DB_CHARSET)) {
                 DB::execute("SET NAMES ?", DB_CHARSET);
             }
         } catch (Exception $e) {
             $this->printMessage("Error connecting to database: " . $e->getMessage() . "\n" . $e->getTraceAsString());
         }
         try {
             $db_result = DB::execute("SELECT value FROM " . $t_prefix . "config_options WHERE name = 'file_storage_adapter'");
             $db_result_row = $db_result->fetchRow();
             if ($db_result_row['value'] == FILE_STORAGE_FILE_SYSTEM) {
                 if (!defined('FILES_DIR')) {
                     define('FILES_DIR', ROOT . '/upload');
                 }
                 FileRepository::setBackend(new FileRepository_Backend_FileSystem(FILES_DIR, TABLE_PREFIX));
             } else {
                 FileRepository::setBackend(new FileRepository_Backend_DB(TABLE_PREFIX));
             }
             PublicFiles::setRepositoryPath(ROOT . '/public/files');
             if (!defined('PUBLIC_FOLDER')) {
                 define('PUBLIC_FOLDER', 'public');
             }
             if (trim(PUBLIC_FOLDER) == '') {
                 PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'files');
             } else {
                 PublicFiles::setRepositoryUrl(with_slash(ROOT_URL) . 'public/files');
             }
             $member_parents = array();
             $members = Members::findAll();
             foreach ($members as $member) {
                 $member_parents[$member->getId()] = $member->getAllParentMembersInHierarchy(false, false);
             }
             $object_members = DB::executeAll('SELECT * FROM ' . $t_prefix . 'object_members WHERE is_optimization=0 and not exists (SELECT x.object_id FROM ' . $t_prefix . 'object_members x where x.object_id=fo_object_members.object_id and x.is_optimization=1)');
             foreach ($object_members as $om) {
                 $parents = isset($member_parents[$om['member_id']]) ? $member_parents[$om['member_id']] : array();
                 if (count($parents) > 0) {
                     $sql_values = "";
                     foreach ($parents as $p) {
                         $sql_values .= ($sql_values == "" ? "" : ",") . "(" . $om['object_id'] . "," . $p->getId() . ",1)";
                     }
                     $sql = "INSERT INTO " . $t_prefix . "object_members (object_id, member_id, is_optimization) VALUES {$sql_values} ON DUPLICATE KEY UPDATE is_optimization=1;";
                     DB::execute($sql);
                 }
             }
             $this->printMessage("Finished generating Object Members");
             foreach ($members as $m) {
                 if ($m->getParentMember() instanceof Member && $m->getDimensionId() != $m->getParentMember()->getDimensionId()) {
                     $m->setDimensionId($m->getParentMember()->getDimensionId());
                     $m->save();
                 }
             }
             $app_move_logs = ApplicationLogs::findAll(array("conditions" => "action = 'move'"));
             foreach ($app_move_logs as &$app_log) {
                 /* @var $app_log ApplicationLog */
                 $exp_log_data = explode(";", $app_log->getLogData());
                 if (count($exp_log_data) > 1) {
                     $old_to = array_var($exp_log_data, 1);
                     $old_from = array_var($exp_log_data, 0);
                 } else {
                     $old_to = array_var($exp_log_data, 0);
                     $old_from = "";
                 }
                 $to_id = str_replace("to:", "", $old_to);
                 $new_to_id = Members::instance()->findOne(array("id" => true, "conditions" => "ws_id = '{$to_id}'"));
                 if (count($new_to_id) > 0) {
                     $new_to_id = $new_to_id[0];
                 }
                 $new_from_ids = "";
                 $from_ids = str_replace("from:", "", $old_from);
                 if ($from_ids != "") {
                     $new_from_ids_array = Members::instance()->findAll(array("id" => true, "conditions" => "ws_id IN ({$from_ids})"));
                     $new_from_ids = implode(",", $new_from_ids_array);
                 }
                 if ($new_to_id) {
                     if ($new_from_ids) {
                         $log_data = "from:{$new_from_ids};to:{$new_to_id}";
                     } else {
                         $log_data = "to:{$new_to_id}";
                     }
                     $app_log->setLogData($log_data);
                     $app_log->save();
                 }
             }
         } catch (Exception $e) {
             die("\nError occurred:\n-----------------\n" . $e->getMessage() . "\n" . $e->getTraceAsString());
         }
         //tpl_assign('install_inv_dw', true);
         $additional_upgrade_steps[] = array('url' => 'complete_migration.php?out=file', 'name' => 'Fill searchable objects and sharing table', 'filename' => dirname(__FILE__) . "/../complete_migration.php");
     } else {
         // upgrading from a pre-release of this version (beta, rc, etc)
         if (version_compare($installed_version, '2.0.0.4') <= 0) {
             if (!$this->checkTableExists($t_prefix . 'role_object_type_permissions', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tCREATE TABLE `" . $t_prefix . "role_object_type_permissions` (\r\n\t\t\t\t\t\t  `role_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t  `object_type_id` INTEGER UNSIGNED NOT NULL,\r\n\t\t\t\t\t\t  `can_delete` BOOLEAN NOT NULL,\r\n\t\t\t\t\t\t  `can_write` BOOLEAN NOT NULL,\r\n\t\t\t\t\t\t  PRIMARY KEY (`role_id`, `object_type_id`)\r\n\t\t\t\t\t\t) ENGINE = InnoDB;\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 1, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','mail','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Super Administrator','Administrator','Manager','Executive');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Collaborator Customer');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 1\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','timeslot','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Internal Collaborator','External Collaborator');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','event','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Guest Customer');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','event','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Guest');\r\n\t\t\t\t\t\tINSERT INTO " . $t_prefix . "role_object_type_permissions (role_id, object_type_id, can_delete, can_write)\r\n\t\t\t\t\t\t SELECT p.id, o.id, 0, 0\r\n\t\t\t\t\t\t FROM `" . $t_prefix . "object_types` o JOIN `" . $t_prefix . "permission_groups` p\r\n\t\t\t\t\t\t WHERE o.`name` IN ('message','weblink','file','task','milestone','event','contact','timeslot','report','comment')\r\n\t\t\t\t\t\t AND p.`name` IN ('Non-Exec Director');\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "role_object_type_permissions SET can_write = 1 WHERE object_type_id = (SELECT id FROM " . $t_prefix . "object_types WHERE name='comment');\r\n\t\t\t\t\t";
             }
             if (!$this->checkTableExists($t_prefix . 'widgets', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tCREATE TABLE  `" . $t_prefix . "widgets` (\r\n\t\t\t\t\t\t  `name` varchar(64) NOT NULL,\r\n\t\t\t\t\t\t  `title` varchar(255) NOT NULL,\r\n\t\t\t\t\t\t  `plugin_id` int(10) unsigned NOT NULL,\r\n\t\t\t\t\t\t  `path` varchar(512) NOT NULL,\r\n\t\t\t\t\t\t  `default_options` text NOT NULL,\r\n\t\t\t\t\t\t  `default_section` varchar(64) NOT NULL,\r\n\t\t\t\t\t\t  `default_order` int(10) NOT NULL,\r\n\t\t\t\t\t\t  PRIMARY KEY (`name`)\r\n\t\t\t\t\t\t) ENGINE = InnoDB;\r\n\t\t\t\t\t";
             }
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
         }
         if (version_compare($installed_version, '2.0.0.5') <= 0) {
             if (!$this->checkColumnExists($t_prefix . 'contacts', 'default_billing_id', $this->database_connection)) {
                 $upgrade_script = "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "contacts` ADD COLUMN `default_billing_id` INTEGER NOT NULL DEFAULT 0;\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks`\r\n\t\t\t\t\t\t ADD COLUMN `use_due_time` BOOLEAN DEFAULT 0,\r\n\t\t\t\t\t\t ADD COLUMN `use_start_time` BOOLEAN DEFAULT 0;\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "project_tasks t SET\r\n\t\t\t\t\t\t t.due_date = ADDTIME(t.due_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1)))\r\n\t\t\t\t\t\t WHERE t.due_date > 0;\r\n\t\t\t\t\t\tUPDATE " . $t_prefix . "project_tasks t SET\r\n\t\t\t\t\t\t t.start_date = ADDTIME(t.start_date, CONCAT(SUBSTRING_INDEX((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)), '.', 1), ':', SUBSTRING_INDEX(abs((SELECT c.timezone FROM " . $t_prefix . "contacts c WHERE c.object_id=(SELECT o.updated_by_id FROM " . $t_prefix . "objects o WHERE o.id=t.object_id)) % 1)*60, '.', 1)))\r\n\t\t\t\t\t\t WHERE t.start_date > 0;\r\n\t\t\t\t\t\tINSERT INTO `" . $t_prefix . "contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) VALUES\r\n\t\t\t\t\t\t ('general', 'work_day_end_time', '18:00', 'TimeConfigHandler', 0, 410, 'Work day end time');\t\t\t\t\t\t\r\n\t\t\t\t\t";
             }
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
         }
         if (version_compare($installed_version, '2.0.0.6') <= 0) {
             //WS Widgets
             $upgrade_script = "\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "contact_config_options` SET `default_value` = '15' WHERE `" . $t_prefix . "contact_config_options`.`name` = 'noOfTasks' LIMIT 1 ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "widgets SET default_section = 'none' WHERE name = 'people' AND NOT EXISTS (SELECT id from " . $t_prefix . "plugins WHERE name = 'crpm');\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimensions SET options = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}, \"quickAdd\":true,\"showInPaths\":true}' \r\n\t\t\t\t\t\tWHERE  code='workspaces';\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "tab_panels` SET default_action = 'main_dashboard', initial_action = 'main_dashboard'\r\n\t\t\t\t\t\tWHERE id = 'overview-panel' ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "object_types SET type = 'dimension_object', handler_class='Workspaces', table_name = 'workpaces' WHERE name = 'workspace' ;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimension_object_types SET OPTIONS = '{\"defaultAjax\":{\"controller\":\"dashboard\", \"action\": \"main_dashboard\"}}' \r\n\t\t\t\t\t\tWHERE dimension_id = (SELECT id FROM " . $t_prefix . "dimensions WHERE code = 'workspaces');\r\n\t\t\t\t\tCREATE TABLE IF NOT EXISTS `" . $t_prefix . "contact_widgets` (\r\n\t\t\t\t\t  `widget_name` varchar(40) NOT NULL,\r\n\t\t\t\t\t  `contact_id` int(11) NOT NULL,\r\n\t\t\t\t\t  `section` varchar(40) NOT NULL,\r\n\t\t\t\t\t  `order` int(11) NOT NULL,\r\n\t\t\t\t\t  `options` varchar(255) NOT NULL,\r\n\t\t\t\t\t  PRIMARY KEY (`widget_name`,`contact_id`) USING BTREE\r\n\t\t\t\t\t) ENGINE=InnoDB;\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "widgets(name, title, plugin_id, default_section,default_order) \r\n\t\t\t\t\t VALUES ('messages','notes',0,'none',1000)\r\n\t\t\t\t\t ON DUPLICATE KEY update name = name;\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "dimension_object_type_contents (dimension_id, dimension_object_type_id, content_object_type_id, is_required, is_multiple)\r\n\t\t\t\t\t SELECT d.id, ot.id, (SELECT tmp.id FROM " . $t_prefix . "object_types tmp WHERE tmp.name='contact'), 0, 1\r\n\t\t\t\t\t FROM " . $t_prefix . "dimensions d JOIN " . $t_prefix . "object_types ot\r\n\t\t\t\t\t WHERE d.code = 'customer_project' AND ot.name IN ('customer', 'project', 'folder', 'customer_folder', 'project_folder')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE dimension_id=dimension_id;\r\n\t\t\t\t\tUPDATE " . $t_prefix . "dimension_object_type_contents SET is_multiple = 1 WHERE content_object_type_id = (SELECT id FROM " . $t_prefix . "object_types WHERE name='mail');\r\n\t\t\t\t";
             if (@mysql_fetch_row(@mysql_query("SELECT id from " . $t_prefix . "plugins WHERE name = 'workspaces'"))) {
                 $upgrade_script .= "INSERT INTO " . $t_prefix . "widgets(name, title, plugin_id, default_section,default_order) \r\n\t\t\t\t\t\tVALUES ('ws_description', 'workspace description',(SELECT id from " . $t_prefix . "plugins WHERE name = 'workspaces'), 'left',-100)\r\n\t\t\t\t\t\tON DUPLICATE KEY update name = name ;";
             }
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
             if ($obj = @mysql_fetch_object(@mysql_query("SELECT id FROM " . $t_prefix . "object_types WHERE name = 'workspace' "))) {
                 $wsTypeId = $obj->id;
                 $res = @mysql_query("SELECT * FROM " . $t_prefix . "members WHERE dimension_id = (SELECT id FROM " . $t_prefix . "dimensions WHERE code='workspaces')");
                 while ($m = @mysql_fetch_object($res)) {
                     @mysql_query("INSERT INTO " . $t_prefix . "objects (object_type_id, name) VALUES ({$wsTypeId}, '" . $m->name . "' )");
                     if ($id = @mysql_insert_id()) {
                         @mysql_query("INSERT INTO " . $t_prefix . "workspaces (object_id) VALUES ({$id})");
                         @mysql_query("UPDATE " . $t_prefix . "members SET object_id={$id} WHERE id = {$m->id} ");
                     }
                 }
             }
         }
         if (version_compare($installed_version, '2.0.0.7') <= 0) {
             $upgrade_script = "";
             if (!$this->checkTableExists($t_prefix . 'mail_spam_filters', $this->database_connection)) {
                 $upgrade_script .= "\r\n                                                    CREATE TABLE IF NOT EXISTS `" . $t_prefix . "mail_spam_filters` (\r\n                                                     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n                                                     `account_id` int(10) unsigned NOT NULL,\r\n                                                     `text_type` enum('email_address','subject') COLLATE utf8_unicode_ci NOT NULL,\r\n                                                     `text` text COLLATE utf8_unicode_ci NOT NULL,\r\n                                                     `spam_state` enum('no spam','spam') COLLATE utf8_unicode_ci NOT NULL,\r\n                                                     PRIMARY KEY (`id`)\r\n                                                    ) ENGINE=InnoDB;\r\n                                        ";
             }
             $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`) \r\n\t\t\t\t\tVALUES ('general', 'untitled_notes', '0', 'BoolConfigHandler', '0', '0', NULL) ON DUPLICATE KEY UPDATE name=name;";
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
         }
         if (version_compare($installed_version, '2.0.0.8') < 0) {
             $upgrade_script = "";
             if (!$this->checkTableExists($t_prefix . 'external_calendar_users', $this->database_connection)) {
                 $upgrade_script .= "\r\n                                                    CREATE TABLE IF NOT EXISTS `" . $t_prefix . "external_calendar_users` (\r\n                                                      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n                                                      `contact_id` int(10) unsigned NOT NULL,\r\n                                                      `auth_user` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\r\n                                                      `auth_pass` varchar(100) COLLATE utf8_unicode_ci NOT NULL,\r\n                                                      `type` text COLLATE utf8_unicode_ci NOT NULL,\r\n                                                      `sync` TINYINT( 1 ) NULL DEFAULT '0',\r\n                                                      PRIMARY KEY (`id`)\r\n                                                    ) ENGINE = InnoDB;\r\n\t\t\t\t\t";
             }
             if (!$this->checkTableExists($t_prefix . 'external_calendars', $this->database_connection)) {
                 $upgrade_script .= "\r\n                                                    CREATE TABLE IF NOT EXISTS `" . $t_prefix . "external_calendars` (\r\n                                                      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\r\n                                                      `ext_cal_user_id` int(10) unsigned NOT NULL,\r\n                                                      `calendar_user` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\r\n                                                      `calendar_visibility` varchar(255) COLLATE utf8_unicode_ci NOT NULL,\r\n                                                      `calendar_name` text COLLATE utf8_unicode_ci NOT NULL,\r\n                                                      `calendar_feng` TINYINT( 1 ) NOT NULL DEFAULT '0',\r\n                                                      PRIMARY KEY (`id`)\r\n                                                    ) ENGINE = InnoDB;\r\n\t\t\t\t\t";
             }
             if (!$this->checkColumnExists($t_prefix . 'project_events', 'ext_cal_id', $this->database_connection)) {
                 $upgrade_script .= "\r\n\t\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events`  ADD `ext_cal_id` INT(10) UNSIGNED NOT NULL;\r\n\t\t\t\t\t";
             }
             $upgrade_script .= "\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` CHANGE `special_id` `special_id` VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "file_types` SET `is_searchable` = '1' WHERE `extension` = 'docx';\r\n\t\t\t\t\tUPDATE `" . $t_prefix . "file_types` SET `is_searchable` = '1' WHERE `extension` = 'pdf';\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\t\tVALUES ('general', 'repeating_task', '0', 'BoolConfigHandler', '0', '0', '')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "contact_config_options` (`category_name`, `name`, `default_value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\t\tVALUES ('calendar panel', 'calendar task filter', 'pending', 'StringConfigHandler', '1', '0', NULL),\r\n\t\t\t\t\t\t\t('task panel', 'close timeslot open', '1', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t\t\t('calendar panel', 'reminders_events', 'reminder_email,1,60', 'StringConfigHandler', '0', '0', NULL)\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "cron_events` (`name`, `recursive`, `delay`, `is_system`, `enabled`, `date`)\r\n\t\t\t\t\t\tVALUES ('import_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00'),\r\n\t\t\t\t\t\t\t('export_google_calendar', '1', '10', '0', '0', '0000-00-00 00:00:00')\r\n\t\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t\t";
             $upgrade_script .= "\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "config_options` WHERE `name`='use_time_in_task_dates' AND NOT EXISTS (SELECT id FROM `" . $t_prefix . "plugins` WHERE `name`='crpm' AND is_activated=1);\r\n\t\t\t\t\tINSERT INTO " . $t_prefix . "contact_config_options (category_name, name, default_value, config_handler_class, is_system, option_order) VALUES\r\n\t\t\t\t\t\t('general','show_object_direct_url',0,'BoolConfigHandler',0,0),\r\n\t\t\t\t\t\t('general','drag_drop_prompt','prompt','DragDropPromptConfigHandler',0,0)\r\n\t\t\t\t\t ON DUPLICATE KEY UPDATE name = name;\r\n\t\t\t\t";
             $upgrade_script .= "\r\n\t\t\t\t\tINSERT INTO `" . $t_prefix . "tab_panels` (`id`,`title`,`icon_cls`,`refresh_on_context_change`,`default_controller`,`default_action`,`initial_controller`,`initial_action`,`enabled`,`type`,`ordering`,`plugin_id`,`object_type_id`) VALUES \r\n\t\t\t\t\t('contacts-panel','contacts','ico-contacts',1,'contact','init','','',0,'system',7,0,16) ON DUPLICATE KEY UPDATE title=title;\r\n\t\t\t\t";
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
         }
         if (version_compare($installed_version, '2.0.1') < 0) {
             $upgrade_script = "";
             $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\tVALUES ('general', 'working_days', '1,2,3,4,5,6,7', 'StringConfigHandler', '0', '0', NULL);\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `original_task_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_tasks` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_events` ADD `original_event_id` INT( 10 ) UNSIGNED NULL DEFAULT '0';\r\n\t\t\t\t\tALTER TABLE `" . $t_prefix . "project_messages` ADD `type_content` ENUM( 'text', 'html' ) NOT NULL DEFAULT 'text';\r\n\t\t\t\t";
             $upgrade_script .= "INSERT INTO `" . $t_prefix . "config_options` (`category_name`, `name`, `value`, `config_handler_class`, `is_system`, `option_order`, `dev_comment`)\r\n\t\t\t\t\tVALUES ('general', 'wysiwyg_tasks', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('general', 'wysiwyg_messages', '0', 'BoolConfigHandler', '0', '0', NULL),\r\n\t\t\t\t\t('task panel', 'tasksShowTimeEstimates', '1', 'BoolConfigHandler', '1', '0', NULL)\r\n\t\t\t\tON DUPLICATE KEY UPDATE name=name;\r\n\t\t\t\t";
             $upgrade_script .= "UPDATE `" . $t_prefix . "widgets` SET plugin_id = (SELECT id FROM `" . $t_prefix . "plugins` WHERE name='workspaces') WHERE name='workspaces';\r\n\t\t\t\t";
             // clean old users dimension
             $upgrade_script .= "DELETE FROM `" . $t_prefix . "object_members` WHERE member_id IN (SELECT `id` FROM `" . $t_prefix . "members` WHERE `dimension_id` IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users'));\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "contact_dimension_permissions` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "members` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_type_contents` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_type_hierarchies` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimension_object_types` WHERE dimension_id IN (SELECT `id` FROM `" . $t_prefix . "dimensions` WHERE `code`='feng_users');\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "dimensions` WHERE code='feng_users';\r\n\t\t\t\t\tDELETE FROM `" . $t_prefix . "object_types` WHERE name='user';\r\n\t\t\t\t\tUPDATE " . $t_prefix . "contacts c SET c.personal_member_id = 0 WHERE c.user_type>0 AND NOT (SELECT count(m2.id) FROM " . $t_prefix . "members m2 WHERE m2.object_id=c.personal_member_id)=0;\r\n\t\t\t\t";
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
         }
         // Plugin Version Support
         $upgrade_script = '';
         if (!$this->checkColumnExists($t_prefix . "plugins", 'version', $this->database_connection)) {
             $upgrade_script = 'ALTER TABLE ' . $t_prefix . 'plugins ADD COLUMN `version` INTEGER  NOT NULL  DEFAULT 1 AFTER `name` ';
             if ($this->executeMultipleQueries($upgrade_script, $total_queries, $executed_queries, $this->database_connection)) {
                 $this->printMessage("Database schema transformations executed (total queries: {$total_queries})");
             } else {
                 $this->printMessage('Failed to execute DB schema transformations. MySQL said: ' . mysql_error(), true);
                 return false;
             }
         }
     }
     $this->printMessage('Feng Office has been upgraded. You are now running Feng Office ' . $this->getVersionTo() . ' Enjoy!');
     tpl_assign('additional_steps', $additional_upgrade_steps);
 }
Пример #12
0
 private function list_members($request)
 {
     $service = $request['srv'];
     $members = array();
     $type = ObjectTypes::instance()->findByName($service);
     $typeId = $type->getId();
     $ids = array();
     $dimensionController = new DimensionController();
     foreach ($dimensionController->initial_list_dimension_members(Dimensions::findByCode('customer_project')->getId(), $typeId) as $member) {
         $ids[] = $member['object_id'];
     }
     if (count($ids)) {
         $args['conditions'] = " `object_id` IN (" . implode(",", $ids) . ") AND object_type_id = {$typeId}";
         foreach (Members::instance()->findAll($args) as $member) {
             /* @var $member Member */
             $memberInfo = array('id' => $member->getId(), 'name' => $member->getName(), 'type' => $service, 'path' => $member->getPath());
             $members[] = $memberInfo;
         }
     }
     return $this->response('json', $members);
 }
Пример #13
0
 function canContainObject($object_type_id)
 {
     return Members::instance()->canContainObject($object_type_id, $this->getObjectTypeId(), $this->getDimensionId());
 }
Пример #14
0
<?php

$genid = gen_id();
$typeId = ObjectTypes::instance()->findByName("workspace")->getId();
//Check if There is a workspace in the active context
/* @var $member Member */
foreach (active_context_members(false) as $memberId) {
    $member = Members::instance()->findById($memberId);
    if ($member->getObjectTypeId() == $typeId) {
        $id = $member->getObjectId();
        if ($workspace = Workspaces::instance()->findById($id) && trim($member->getDescription()) != "") {
            $description = $member->getDescription();
            include_once 'template.php';
            break;
        }
    }
}
Пример #15
0
 /**
  * Lists all contacts and clients
  *
  */
 function list_all()
 {
     ajx_current("empty");
     // Get all variables from request
     $start = array_var($_GET, 'start', 0);
     $limit = array_var($_GET, 'limit', config_option('files_per_page'));
     $page = 1;
     if ($start > 0) {
         $page = $start / $limit + 1;
     }
     $order = array_var($_GET, 'sort');
     $order_dir = array_var($_GET, 'dir');
     $action = array_var($_GET, 'action');
     $attributes = array("ids" => explode(',', array_var($_GET, 'ids')), "types" => explode(',', array_var($_GET, 'types')), "accountId" => array_var($_GET, 'account_id'), "viewType" => array_var($_GET, 'view_type'));
     //Resolve actions to perform
     $actionMessage = array();
     if (isset($action)) {
         $actionMessage = $this->resolveAction($action, $attributes);
         if ($actionMessage["errorCode"] == 0) {
             flash_success($actionMessage["errorMessage"]);
         } else {
             flash_error($actionMessage["errorMessage"]);
         }
     }
     $extra_conditions = "";
     if ($attributes['viewType'] == 'contacts') {
         $extra_conditions = 'AND `is_company` = 0';
     } else {
         if ($attributes['viewType'] == 'companies') {
             $extra_conditions = 'AND `is_company` = 1';
         }
     }
     $extra_conditions .= " AND disabled = 0 ";
     switch ($order) {
         case 'updatedOn':
             $order = '`updated_on`';
             break;
         case 'createdOn':
             $order = '`created_on`';
             break;
         case 'name':
             $order = ' concat(surname, first_name) ';
             break;
         default:
             $order = '`name`';
             break;
     }
     if (!$order_dir) {
         switch ($order) {
             case 'name':
                 $order_dir = 'ASC';
                 break;
             default:
                 $order_dir = 'DESC';
         }
     }
     $context = active_context();
     if (context_type() == 'mixed') {
         // There are members selected
         //$content_objects = Contacts::getContentObjects($context, ObjectTypes::findById(Contacts::instance()->getObjectTypeId()), $order, $order_dir, $extra_conditions, null, false,false, $start, $limit);
         $content_objects = Contacts::instance()->listing(array("order" => $order, "order_dir" => $order_dir, "extra_conditions" => $extra_conditions, "start" => $start, "limit" => $limit));
     } else {
         // Estoy parado en 'All'. Filtro solo por permisos TODO: Fix this !
         $conditions = "archived_on = '0000-00-00 00:00:00' AND trashed_on = '0000-00-00 00:00:00' {$extra_conditions}";
         $content_objects = new stdClass();
         $content_objects->objects = Contacts::instance()->findAll(array("conditions" => $conditions, "order" => "{$order} {$order_dir}", "offset" => $start, "limit" => $limit));
         $content_objects->total = Contacts::instance()->count(array("conditions" => $conditions));
         foreach ($content_objects->objects as $k => $contact) {
             /* @var $contact Contact */
             if (Plugins::instance()->isActivePlugin("core_dimensions")) {
                 $m = array_var(Members::instance()->findByObjectId($contact->getId(), Dimensions::findByCode("feng_persons")->getId()), 0);
                 if ($m instanceof Member) {
                     $mid = $m->getId();
                     if (!ContactMemberPermissions::instance()->contactCanReadMember(logged_user()->getPermissionGroupId(), $mid, logged_user())) {
                         unset($content_objects->objects[$k]);
                         $content_objects->total--;
                     }
                 }
             }
         }
         $content_objects->objects = array_values($content_objects->objects);
     }
     // Prepare response object
     $object = $this->newPrepareObject($content_objects->objects, $content_objects->total, $start, $attributes);
     ajx_extra_data($object);
     tpl_assign("listing", $object);
 }
 /**
  * Add single mail
  *
  * @access public
  * @param void
  * @return null
  */
 function add_mail()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->addHelper('textile');
     $mail_accounts = MailAccounts::getMailAccountsByUser(logged_user());
     if (count($mail_accounts) < 1) {
         flash_error(lang('no mail accounts set'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_mail');
     $mail_data = array_var($_POST, 'mail');
     $sendBtnClick = array_var($mail_data, 'sendBtnClick', '') == 'true' ? true : false;
     $isDraft = array_var($mail_data, 'isDraft', '') == 'true' ? true : false;
     $isUpload = array_var($mail_data, 'isUpload', '') == 'true' ? true : false;
     $autosave = array_var($mail_data, 'autosave', '') == 'true';
     $id = array_var($mail_data, 'id');
     $mail = MailContents::findById($id);
     $isNew = false;
     if (!$mail) {
         $isNew = true;
         $mail = new MailContent();
     }
     tpl_assign('mail_to', urldecode(array_var($_GET, 'to')));
     tpl_assign('link_to_objects', array_var($_GET, 'link_to_objects'));
     $def_acc_id = $this->getDefaultAccountId();
     if ($def_acc_id > 0) {
         $def_acc = MailAccounts::getAccountById($def_acc_id);
         if ($def_acc instanceof MailAccount) {
             tpl_assign('default_account', $def_acc);
         }
     }
     tpl_assign('mail', $mail);
     tpl_assign('mail_data', $mail_data);
     tpl_assign('mail_accounts', $mail_accounts);
     Hook::fire('send_to', array_var($_GET, 'ids'), array_var($_GET, 'me'));
     // Form is submited
     if (is_array($mail_data)) {
         $account = MailAccounts::findById(array_var($mail_data, 'account_id'));
         if (!$account instanceof MailAccount) {
             flash_error(lang('mail account dnx'));
             ajx_current("empty");
             return;
         }
         $accountUser = MailAccountContacts::getByAccountAndContact($account, logged_user());
         if (!$accountUser instanceof MailAccountContact) {
             flash_error(lang('no access permissions'));
             ajx_current("empty");
             return;
         }
         if ($account->getOutgoingTrasnportType() == 'ssl' || $account->getOutgoingTrasnportType() == 'tls') {
             $available_transports = stream_get_transports();
             if (array_search($account->getOutgoingTrasnportType(), $available_transports) === FALSE) {
                 flash_error('The server does not support SSL.');
                 ajx_current("empty");
                 return;
             }
         }
         $cp_errs = $this->checkRequiredCustomPropsBeforeSave(array_var($_POST, 'object_custom_properties', array()));
         if (is_array($cp_errs) && count($cp_errs) > 0) {
             foreach ($cp_errs as $err) {
                 flash_error($err);
             }
             ajx_current("empty");
             return;
         }
         $subject = array_var($mail_data, 'subject');
         $body = array_var($mail_data, 'body');
         if (($pre_body_fname = array_var($mail_data, 'pre_body_fname')) != "") {
             $body = str_replace(lang('content too long not loaded'), '', $body, $count = 1);
             $tmp_filename = ROOT . "/tmp/{$pre_body_fname}";
             if (is_file($tmp_filename)) {
                 $body .= file_get_contents($tmp_filename);
                 if (!$isDraft) {
                     @unlink($tmp_filename);
                 }
             }
         }
         if (array_var($mail_data, 'format') == 'html') {
             $css = "font-family:sans-serif,Arial,Verdana; font-size:14px; line-height:1.6; color:#222;";
             Hook::fire('email_base_css', null, $css);
             str_replace(array("\r", "\n"), "", $css);
             $body = '<div style="' . $css . '">' . $body . '</div>';
             $body = str_replace('<blockquote>', '<blockquote style="border-left:1px solid #987ADD;padding-left:10px;">', $body);
         }
         $type = 'text/' . array_var($mail_data, 'format');
         $to = trim(array_var($mail_data, 'to'));
         if (str_ends_with($to, ",") || str_ends_with($to, ";")) {
             $to = substr($to, 0, strlen($to) - 1);
         }
         $mail_data['to'] = $to;
         $cc = trim(array_var($mail_data, 'cc'));
         if (str_ends_with($cc, ",") || str_ends_with($cc, ";")) {
             $cc = substr($cc, 0, strlen($cc) - 1);
         }
         $mail_data['cc'] = $cc;
         $bcc = trim(array_var($mail_data, 'bcc'));
         if (str_ends_with($bcc, ",") || str_ends_with($bcc, ";")) {
             $bcc = substr($bcc, 0, strlen($bcc) - 1);
         }
         $mail_data['bcc'] = $bcc;
         if (!$isDraft && trim($to . $cc . $bcc) == '') {
             flash_error(lang('recipient must be specified'));
             ajx_current("empty");
             return;
         }
         $invalid_to = MailUtilities::validate_email_addresses($to);
         if (is_array($invalid_to)) {
             flash_error(lang('error invalid recipients', lang('mail to'), implode(", ", $invalid_to)));
             ajx_current("empty");
             return;
         }
         $invalid_cc = MailUtilities::validate_email_addresses($cc);
         if (is_array($invalid_cc)) {
             flash_error(lang('error invalid recipients', lang('mail CC'), implode(", ", $invalid_cc)));
             ajx_current("empty");
             return;
         }
         $invalid_bcc = MailUtilities::validate_email_addresses($bcc);
         if (is_array($invalid_bcc)) {
             flash_error(lang('error invalid recipients', lang('mail BCC'), implode(", ", $invalid_bcc)));
             ajx_current("empty");
             return;
         }
         $last_mail_in_conversation = array_var($mail_data, 'last_mail_in_conversation');
         $conversation_id = array_var($mail_data, 'conversation_id');
         if ($last_mail_in_conversation && $conversation_id) {
             $new_mail_in_conversation = MailContents::getLastMailIdInConversation($conversation_id, true);
             if ($new_mail_in_conversation != $last_mail_in_conversation) {
                 ajx_current("empty");
                 evt_add("new email in conversation", array('id' => $new_mail_in_conversation, 'genid' => array_var($_POST, 'instanceName')));
                 return;
             }
         }
         $mail->setFromAttributes($mail_data);
         $mail->setTo($to);
         $mail->setCc($cc);
         $mail->setBcc($bcc);
         $mail->setSubject($mail_data['subject']);
         $utils = new MailUtilities();
         // attachment
         $linked_attachments = array();
         $attachments = array();
         $project_files_attachments = array();
         $objects = array_var($_POST, 'linked_objects');
         $attach_contents = array_var($_POST, 'attach_contents', array());
         $original_email = isset($mail_data['original_id']) ? MailContents::findById($mail_data['original_id']) : null;
         if (is_array($objects)) {
             $err = 0;
             $count = -1;
             foreach ($objects as $objid) {
                 $count++;
                 $split = explode(":", $objid);
                 if (count($split) == 2) {
                     $object = Objects::instance()->findObject($split[1]);
                 } else {
                     if (count($split) == 4) {
                         if ($split[0] == 'FwdMailAttach') {
                             $tmp_filename = ROOT . "/tmp/" . logged_user()->getId() . "_" . ($original_email ? $original_email->getAccountId() : $mail_data['account_id']) . "_FwdMailAttach_" . $split[3];
                             if (is_file($tmp_filename)) {
                                 $attachments[] = array("data" => file_get_contents($tmp_filename), "name" => $split[1], "type" => $split[2]);
                                 continue;
                             }
                         }
                     }
                 }
                 if (!isset($object) || !$object) {
                     flash_error(lang('file dnx'));
                     $err++;
                 } else {
                     if (isset($attach_contents[$count])) {
                         if ($split[0] == 'ProjectFiles') {
                             $file = ProjectFiles::findById($object->getId());
                             if (!$file instanceof ProjectFile) {
                                 flash_error(lang('file dnx'));
                                 $err++;
                             }
                             // if
                             //			 					if(!$file->canDownload(logged_user())) {
                             //			 						flash_error(lang('no access permissions'));
                             //			 						$err++;
                             //			 					} // if
                             $project_files_attachments[] = $file;
                             $attachments[] = array("data" => $file->getFileContent(), "name" => $file->getFilename(), "type" => $file->getTypeString());
                         } else {
                             if ($split[0] == 'MailContents') {
                                 $email = MailContents::findById($object->getId());
                                 if (!$email instanceof MailContent) {
                                     flash_error(lang('email dnx'));
                                     $err++;
                                 }
                                 // if
                                 if (!$email->canView(logged_user())) {
                                     flash_error(lang('no access permissions'));
                                     $err++;
                                 }
                                 // if
                                 $attachments[] = array("data" => $email->getContent(), "name" => $email->getSubject() . ".eml", "type" => 'message/rfc822');
                             }
                         }
                     } else {
                         $linked_attachments[] = array("data" => $object->getViewUrl(), "name" => clean($object->getObjectName()), "type" => lang($object->getObjectTypeName()), "id" => $object->getId());
                     }
                 }
             }
             if ($err > 0) {
                 flash_error(lang('some objects could not be linked', $err));
                 ajx_current('empty');
                 return;
             }
         }
         $to = preg_split('/;|,/', $to);
         $to = $utils->parse_to($to);
         if ($body == '') {
             $body .= ' ';
         }
         try {
             $linked_users = array();
             //create contacts from recipients of email
             if (user_config_option('create_contacts_from_email_recipients') || can_manage_contacts(logged_user())) {
                 foreach ($to as $to_user) {
                     $linked_user = Contacts::getByEmail($to_user[1]);
                     if (!$linked_user instanceof Contact) {
                         try {
                             DB::beginWork();
                             $linked_user = create_user_from_email($to_user[1], $to_user[0], null, false);
                             DB::commit();
                         } catch (Exception $e) {
                             Logger::log($e->getMessage());
                             DB::rollback();
                         }
                     }
                     if ($linked_user instanceof Contact) {
                         $linked_users[] = $linked_user;
                     }
                 }
             }
             if (count($linked_attachments)) {
                 $linked_atts = $type == 'text/html' ? '<div style="font-family:arial;"><br><br><br><span style="font-size:12pt;font-weight:bold;color:#777">' . lang('linked attachments') . '</span><ul>' : "\n\n\n-----------------------------------------\n" . lang('linked attachments') . "\n\n";
                 foreach ($linked_attachments as $att) {
                     $linked_atts .= $type == 'text/html' ? '<li><a href="' . $att['data'] . '">' . $att['name'] . ' (' . $att['type'] . ')</a></li>' : $att['name'] . ' (' . $att['type'] . '): ' . $att['data'] . "\n";
                     foreach ($linked_users as $linked_user) {
                         try {
                             $linked_user->giveAccessToObject(Objects::findObject($att['id']));
                         } catch (Exception $e) {
                             //Logger::log($e->getMessage());
                         }
                     }
                 }
                 $linked_atts .= $type == 'text/html' ? '</ul></div>' : '';
             } else {
                 $linked_atts = '';
             }
             $body .= $linked_atts;
             if (count($attachments) > 0) {
                 $i = 0;
                 $str = "";
                 /*	foreach ($attachments as $att) {
                 					$str .= "--000000000000000000000000000$i\n";
                 					$str .= "Name: ".$att['name'] .";\n";
                 					$str .= "Type: ".$att['type'] .";\n";
                 					//$str .= "Encoding: ".$att['type'] .";\n";
                 					$str .= base64_encode($att['data']) ."\n";
                 					$str .= "--000000000000000000000000000$i--\n";
                 					$i++;
                 				}
                 			*/
                 $str = "#att_ver 2\n";
                 foreach ($attachments as $att) {
                     $rep_id = $utils->saveContent($att['data']);
                     if (str_starts_with($att['name'], "#")) {
                         $att['name'] = str_replace_first("#", "@@sharp@@", $att['name']);
                     }
                     $str .= $att['name'] . "|" . $att['type'] . "|" . $rep_id . "\n";
                 }
                 // save attachments, when mail is sent this file is deleted and full content is saved
                 $repository_id = $utils->saveContent($str);
                 if (!$isNew) {
                     if (FileRepository::isInRepository($mail->getContentFileId())) {
                         // delete old attachments
                         $content = FileRepository::getFileContent($mail->getContentFileId());
                         if (str_starts_with($content, "#att_ver")) {
                             $lines = explode("\n", $content);
                             foreach ($lines as $line) {
                                 if (!str_starts_with($line, "#") && trim($line) !== "") {
                                     $data = explode("|", $line);
                                     if (isset($data[2]) && FileRepository::isInRepository($data[2])) {
                                         FileRepository::deleteFile($data[2]);
                                     }
                                 }
                             }
                         }
                         FileRepository::deleteFile($mail->getContentFileId());
                     }
                 }
                 $mail->setContentFileId($repository_id);
             }
             $mail->setHasAttachments(is_array($attachments) && count($attachments) > 0 ? 1 : 0);
             $mail->setAccountEmail($account->getEmailAddress());
             $mail->setSentDate(DateTimeValueLib::now());
             $mail->setReceivedDate(DateTimeValueLib::now());
             DB::beginWork();
             $msg_id = MailUtilities::generateMessageId($account->getEmailAddress());
             $conversation_id = array_var($mail_data, 'conversation_id');
             $in_reply_to_id = array_var($mail_data, 'in_reply_to_id');
             if ($conversation_id) {
                 $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id'));
                 if ($in_reply_to instanceof MailContent && $in_reply_to->getSubject() && strpos(strtolower($mail->getSubject()), strtolower($in_reply_to->getSubject())) === false) {
                     $conversation_id = null;
                     $in_reply_to_id = '';
                 }
             }
             if (!$conversation_id) {
                 $conversation_id = MailContents::getNextConversationId($account->getId());
             }
             $mail->setMessageId($msg_id);
             $mail->setConversationId($conversation_id);
             $mail->setInReplyToId($in_reply_to_id);
             $mail->setUid(gen_id());
             $mail->setState($isDraft && !$sendBtnClick ? 2 : 200);
             set_user_config_option('last_mail_format', array_var($mail_data, 'format', 'plain'), logged_user()->getId());
             $body = utf8_safe($body);
             if (array_var($mail_data, 'format') == 'html') {
                 $body = preg_replace("/<body*[^>]*>/i", '<body>', $body);
                 // commented because sometimes brokes the html and leaves the body in blank
                 //$body = convert_to_links(preg_replace("/<body*[^>]*>/i",'<body>', $body));
                 $mail->setBodyHtml($body);
                 $mail->setBodyPlain(utf8_safe(html_to_text($body)));
             } else {
                 $mail->setBodyPlain($body);
                 $mail->setBodyHtml('');
             }
             $mail->setFrom($account->getEmailAddress());
             if ($accountUser->getIsDefault() && $accountUser->getSenderName() == "") {
                 $mail->setFromName(logged_user()->getObjectName());
             } else {
                 $mail->setFromName($accountUser->getSenderName());
             }
             $mail->save();
             //$mail->setIsRead(logged_user()->getId(), true);
             if (Plugins::instance()->isActivePlugin('mail_rules')) {
                 if (array_var($mail_data, 'format') == 'html') {
                     $img = MailTracks::get_track_mark_img($mail->getId());
                     $body = $body . $img;
                     $mail->setBodyHtml($body);
                     $mail->setBodyPlain(utf8_safe(html_to_text($body)));
                     $mail->save();
                 }
             }
             foreach ($project_files_attachments as $pfatt) {
                 if ($pfatt instanceof ProjectFile) {
                     $pfatt->setMailId($mail->getId());
                     $pfatt->save();
                     $pfatt->addToSharingTable();
                 }
             }
             $member_ids = active_context_members(false);
             // if replying a classified email classify on same workspace
             $classified_with_conversation = false;
             if (array_var($mail_data, 'original_id')) {
                 $in_reply_to = MailContents::findById(array_var($mail_data, 'original_id'));
                 if ($in_reply_to instanceof MailContent) {
                     $member_ids = array_merge($member_ids, $in_reply_to->getMemberIds());
                     $classified_with_conversation = true;
                 }
             }
             // autoclassify sent email if not classified
             if (!$classified_with_conversation) {
                 $acc_mem_ids = explode(',', $account->getMemberId());
                 foreach ($acc_mem_ids as $acc_mem_id) {
                     $member_ids[] = $acc_mem_id;
                 }
             }
             $object_controller = new ObjectController();
             foreach ($member_ids as $k => &$mem_id) {
                 if ($mem_id == "") {
                     unset($member_ids[$k]);
                 }
             }
             if (count($member_ids) > 0) {
                 //$object_controller->add_to_members($mail, $member_ids);
                 $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')'));
                 $mail->addToMembers($members, true);
                 $mail->addToSharingTable();
             }
             $object_controller->link_to_new_object($mail);
             $object_controller->add_subscribers($mail);
             /*
             				if (array_var($mail_data, 'link_to_objects') != ''){
             					$lto = explode('|', array_var($mail_data, 'link_to_objects'));
             					foreach ($lto as $object_string){
             						$split_object = explode('-', $object_string);
             						$object = Objects::findObject($split_object[1]);
             						if ($object instanceof ContentDataObject){
             							$mail->linkObject($object);
             						}
             					}
             				}*/
             //subscribe user
             $user = Contacts::findById($account->getContactId());
             if ($user instanceof Contact) {
                 $mail->subscribeUser($user);
             }
             /*if (user_config_option('create_contacts_from_email_recipients') && can_manage_contacts(logged_user())) {
             			// automatically create contacts
             			foreach ($to as $recipient) {
             				$recipient_name = trim($recipient[0]);
             				$recipient_address = trim($recipient[1]);
             				if (!$recipient_address) continue;
             				$contact = Contacts::getByEmail($recipient_address);
             				if (!$contact instanceof Contact) {
             					try {
             						$contact = new Contact();
             						$contact->addEmail($recipient_address, 'personal');
             						if ($recipient_name && $recipient_name != $recipient_address) {
             							$contact->setFirstName($recipient_name);
             						} else {
             							$index = strpos($recipient_address, "@");
             							$recipient_name = substr($recipient_address, 0, $index);
             							$contact->setFirstName($recipient_name);
             						}
             						$contact->save();
             					} catch (Exception $e) {
             						Logger::log($e->getMessage());
             					}
             				}
             			}
             		}*/
             $mail->addToSharingTable();
             $mail->orderConversation();
             DB::commit();
             ApplicationLogs::createLog($mail, ApplicationLogs::ACTION_ADD, false, true);
             $mail->setIsRead(logged_user()->getId(), true);
             if (!$autosave) {
                 if ($isDraft && !$sendBtnClick) {
                     flash_success(lang('success save mail'));
                     ajx_current("empty");
                 } else {
                     evt_add("must send mails", array("account" => $mail->getAccountId()));
                     //flash_success(lang('mail is being sent'));
                     ajx_current("back");
                 }
                 evt_add("email saved", array("id" => $mail->getId(), "instance" => array_var($_POST, 'instanceName')));
             } else {
                 evt_add("draft mail autosaved", array("id" => $mail->getId(), "hf_id" => $mail_data['hf_id']));
                 flash_success(lang('success autosave draft'));
                 ajx_current("empty");
             }
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
Пример #17
0
function save_permissions($pg_id, $is_guest = false)
{
    $sys_permissions_data = array_var($_POST, 'sys_perm');
    $changed_members = array();
    //module permissions
    $mod_permissions_data = array_var($_POST, 'mod_perm');
    TabPanelPermissions::clearByPermissionGroup($pg_id);
    if (!is_null($mod_permissions_data) && is_array($mod_permissions_data)) {
        foreach ($mod_permissions_data as $tab_id => $val) {
            $tpp = new TabPanelPermission();
            $tpp->setPermissionGroupId($pg_id);
            $tpp->setTabPanelId($tab_id);
            $tpp->save();
        }
    }
    //system permissions
    $system_permissions = SystemPermissions::findById($pg_id);
    if (!$system_permissions instanceof SystemPermission) {
        $system_permissions = new SystemPermission();
        $system_permissions->setPermissionGroupId($pg_id);
    }
    $system_permissions->setAllPermissions(false);
    $other_permissions = array();
    Hook::fire('add_user_permissions', $pg_id, $other_permissions);
    foreach ($other_permissions as $k => $v) {
        $system_permissions->setColumnValue($k, false);
    }
    $sys_permissions_data['can_task_assignee'] = !$is_guest;
    $system_permissions->setFromAttributes($sys_permissions_data);
    $system_permissions->save();
    //member permissions
    $permissionsString = array_var($_POST, 'permissions');
    if ($permissionsString && $permissionsString != '') {
        $permissions = json_decode($permissionsString);
    }
    if (isset($permissions) && !is_null($permissions) && is_array($permissions)) {
        $allowed_members_ids = array();
        foreach ($permissions as $perm) {
            if (!isset($all_perm_deleted[$perm->m])) {
                $all_perm_deleted[$perm->m] = true;
            }
            $allowed_members_ids[$perm->m] = array();
            $allowed_members_ids[$perm->m]['pg'] = $pg_id;
            $cmp = ContactMemberPermissions::findById(array('permission_group_id' => $pg_id, 'member_id' => $perm->m, 'object_type_id' => $perm->o));
            if (!$cmp instanceof ContactMemberPermission) {
                $cmp = new ContactMemberPermission();
                $cmp->setPermissionGroupId($pg_id);
                $cmp->setMemberId($perm->m);
                $cmp->setObjectTypeId($perm->o);
            }
            $cmp->setCanWrite($is_guest ? false : $perm->w);
            $cmp->setCanDelete($is_guest ? false : $perm->d);
            if ($perm->r) {
                if (isset($allowed_members_ids[$perm->m]['w'])) {
                    if ($allowed_members_ids[$perm->m]['w'] != 1) {
                        $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w;
                    }
                } else {
                    $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w;
                }
                if (isset($allowed_members_ids[$perm->m]['d'])) {
                    if ($allowed_members_ids[$perm->m]['d'] != 1) {
                        $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d;
                    }
                } else {
                    $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d;
                }
                $cmp->save();
                $all_perm_deleted[$perm->m] = false;
            } else {
                $cmp->delete();
            }
            $changed_members[] = $perm->m;
        }
        $sharingTablecontroller = new SharingTableController();
        $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions);
        foreach ($allowed_members_ids as $key => $mids) {
            $mbm = Members::findById($key);
            $root_cmp = ContactMemberPermissions::findById(array('permission_group_id' => $mids['pg'], 'member_id' => $key, 'object_type_id' => $mbm->getObjectTypeId()));
            if (!$root_cmp instanceof ContactMemberPermission) {
                $root_cmp = new ContactMemberPermission();
                $root_cmp->setPermissionGroupId($mids['pg']);
                $root_cmp->setMemberId($key);
                $root_cmp->setObjectTypeId($mbm->getObjectTypeId());
            }
            $root_cmp->setCanWrite($mids['w']);
            $root_cmp->setCanDelete($mids['d']);
            $root_cmp->save();
        }
        foreach ($all_perm_deleted as $mid => $pd) {
            if ($pd) {
                ContactMemberPermissions::instance()->delete("`permission_group_id` = {$pg_id} AND `member_id` = {$mid}");
            }
        }
    }
    // set all permissiions to read_only
    if ($is_guest) {
        $all_saved_permissions = ContactMemberPermissions::findAll(array("conditions" => "`permission_group_id` = {$pg_id}"));
        foreach ($all_saved_permissions as $sp) {
            /* @var $sp ContactMemberPermission */
            if ($sp->getCanDelete() || $sp->getCanWrite()) {
                $sp->setCanDelete(false);
                $sp->setCanWrite(false);
                $sp->save();
            }
        }
        $cdps = ContactDimensionPermissions::findAll(array("conditions" => "`permission_type` = 'allow all'"));
        foreach ($cdps as $cdp) {
            $cdp->setPermissionType('check');
            $cdp->save();
        }
    }
    // check the status of the changed dimensions to set 'allow_all', 'deny_all' or 'check'
    $dimensions = Dimensions::findAll(array("conditions" => array("`id` IN (SELECT DISTINCT `dimension_id` FROM " . Members::instance()->getTableName(true) . " WHERE `id` IN (?))", $changed_members)));
    foreach ($dimensions as $dimension) {
        $mem_ids = $dimension->getAllMembers(true);
        if (count($mem_ids) == 0) {
            $mem_ids[] = 0;
        }
        $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND `member_id` IN (" . implode(",", $mem_ids) . ") AND `can_delete` = 0"));
        if ($count > 0) {
            $dimension->setContactDimensionPermission($pg_id, 'check');
        } else {
            $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND `member_id` IN (" . implode(",", $mem_ids) . ")"));
            if ($count == 0) {
                $dimension->setContactDimensionPermission($pg_id, 'deny all');
            } else {
                $allow_all = true;
                $dim_obj_types = $dimension->getAllowedObjectTypeContents();
                $members = Members::findAll("`id` IN (" . implode(",", $mem_ids) . ")");
                foreach ($dim_obj_types as $dim_obj_type) {
                    $mem_ids_for_ot = array();
                    foreach ($members as $member) {
                        if ($dim_obj_type->getDimensionObjectTypeId() == $member->getObjectTypeId()) {
                            $mem_ids_for_ot[] = $member->getId();
                        }
                    }
                    if (count($mem_ids_for_ot) == 0) {
                        $mem_ids_for_ot[] = 0;
                    }
                    $count = ContactMemberPermissions::count(array('conditions' => "`permission_group_id`={$pg_id} AND \n\t\t\t\t\t\t`object_type_id` = " . $dim_obj_type->getContentObjectTypeId() . " AND `can_delete` = 1 AND `member_id` IN (" . implode(",", $mem_ids_for_ot) . ")"));
                    if ($count != count($mem_ids_for_ot)) {
                        $allow_all = false;
                        break;
                    }
                }
                if ($allow_all) {
                    $dimension->setContactDimensionPermission($pg_id, 'allow all');
                } else {
                    $dimension->setContactDimensionPermission($pg_id, 'check');
                }
            }
        }
    }
}
 /**
  * This function will return paginated result. Result is an array where first element is 
  * array of returned object and second populated pagination object that can be used for 
  * obtaining and rendering pagination data using various helpers.
  * 
  * Items and pagination array vars are indexed with 0 for items and 1 for pagination
  * because you can't use associative indexing with list() construct
  *
  * @access public
  * @param array $arguments Query argumens (@see find()) Limit and offset are ignored!
  * @param integer $items_per_page Number of items per page
  * @param integer $current_page Current page number
  * @return array
  */
 function paginate($arguments = null, $items_per_page = 10, $current_page = 1)
 {
     if (isset($this) && instance_of($this, 'Members')) {
         return parent::paginate($arguments, $items_per_page, $current_page);
     } else {
         return Members::instance()->paginate($arguments, $items_per_page, $current_page);
     }
     // if
 }
 function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '', $read = null, &$received_count)
 {
     try {
         if (strpos($content, '+OK ') > 0) {
             $content = substr($content, strpos($content, '+OK '));
         }
         self::parseMail($content, $decoded, $parsedMail, $warnings);
         $encoding = array_var($parsedMail, 'Encoding', 'UTF-8');
         $enc_conv = EncodingConverter::instance();
         $to_addresses = self::getAddresses(array_var($parsedMail, "To"));
         $from = self::getAddresses(array_var($parsedMail, "From"));
         $message_id = self::getHeaderValueFromContent($content, "Message-ID");
         $in_reply_to_id = self::getHeaderValueFromContent($content, "In-Reply-To");
         $uid = trim($uidl);
         if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
             $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
         }
         if ($uid == '') {
             $uid = trim($message_id);
             if ($uid == '') {
                 $uid = array_var($parsedMail, 'Subject', 'MISSING UID');
             }
             if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) {
                 $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding);
             }
         }
         // do not save duplicate emails
         if (MailContents::mailRecordExists($account->getId(), $uid, $imap_folder_name == '' ? null : $imap_folder_name)) {
             return;
         }
         if (!$from) {
             $parsedMail["From"] = self::getFromAddressFromContent($content);
             $from = array_var($parsedMail["From"][0], 'address', '');
         }
         if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) {
             if (trim($message_id) != "") {
                 $id_condition = " AND `message_id`='" . trim($message_id) . "' AND `from`='{$from}'";
             } else {
                 $id_condition = " AND `name`= " . DB::escape(trim(array_var($parsedMail, 'Subject'))) . " AND `from`='{$from}'";
                 if (array_var($parsedMail, 'Date')) {
                     $sent_date_dt = new DateTimeValue(strtotime(array_var($parsedMail, 'Date')));
                     $sent_date_str = $sent_date_dt->toMySQL();
                     $id_condition .= " AND `sent_date`='" . $sent_date_str . "'";
                 }
             }
             $same = MailContents::findOne(array('conditions' => "`account_id`=" . $account->getId() . $id_condition, 'include_trashed' => true));
             if ($same instanceof MailContent) {
                 return;
             }
         }
         $from_spam_junk_folder = strpos(strtolower($imap_folder_name), 'spam') !== FALSE || strpos(strtolower($imap_folder_name), 'junk') !== FALSE || strpos(strtolower($imap_folder_name), 'trash') !== FALSE;
         $user_id = logged_user() instanceof Contact ? logged_user()->getId() : $account->getContactId();
         $max_spam_level = user_config_option('max_spam_level', null, $user_id);
         if ($max_spam_level < 0) {
             $max_spam_level = 0;
         }
         $spam_level_header = 'x-spam-level:';
         foreach ($decoded[0]['Headers'] as $hdr_name => $hdrval) {
             if (strpos(strtolower($hdr_name), "spamscore") !== false || strpos(strtolower($hdr_name), "x-spam-level")) {
                 $spam_level_header = $hdr_name;
                 break;
             }
         }
         $mail_spam_level = strlen(trim(array_var($decoded[0]['Headers'], $spam_level_header, '')));
         // if max_spam_level >= 10 then nothing goes to junk folder
         $spam_in_subject = false;
         if (config_option('check_spam_in_subject')) {
             $spam_in_subject = strpos_utf(strtoupper(array_var($parsedMail, 'Subject')), "**SPAM**") !== false;
         }
         if ($max_spam_level < 10 && ($mail_spam_level > $max_spam_level || $from_spam_junk_folder) || $spam_in_subject) {
             $state = 4;
             // send to Junk folder
         }
         //if you are in the table spam MailSpamFilters
         if ($state != 4) {
             $spam_email = MailSpamFilters::getFrom($account->getId(), $from);
             if ($spam_email) {
                 $state = 0;
                 if ($spam_email[0]->getSpamState() == "spam") {
                     $state = 4;
                 }
             } else {
                 if ($state == 0) {
                     if (strtolower($from) == strtolower($account->getEmailAddress())) {
                         if (strpos($to_addresses, $from) !== FALSE) {
                             $state = 5;
                         } else {
                             $state = 1;
                         }
                         //Show only in sent folder
                     }
                 }
             }
         }
         if (!isset($parsedMail['Subject'])) {
             $parsedMail['Subject'] = '';
         }
         $mail = new MailContent();
         $mail->setAccountId($account->getId());
         $mail->setState($state);
         $mail->setImapFolderName($imap_folder_name);
         $mail->setFrom($from);
         $cc = trim(self::getAddresses(array_var($parsedMail, "Cc")));
         if ($cc == '' && array_var($decoded, 0) && array_var($decoded[0], 'Headers')) {
             $cc = array_var($decoded[0]['Headers'], 'cc:', '');
         }
         $mail->setCc($cc);
         $from_name = trim(array_var(array_var(array_var($parsedMail, 'From'), 0), 'name'));
         $from_encoding = detect_encoding($from_name);
         if ($from_name == '') {
             $from_name = $from;
         } else {
             if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $from_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($from_name)) {
                 //KOI8-R and CP866 are Russian encodings which PHP does not detect
                 $utf8_from = $enc_conv->convert($encoding, 'UTF-8', $from_name);
                 if ($enc_conv->hasError()) {
                     $utf8_from = utf8_encode($from_name);
                 }
                 $utf8_from = utf8_safe($utf8_from);
                 $mail->setFromName($utf8_from);
             } else {
                 $mail->setFromName($from_name);
             }
         }
         $subject_aux = $parsedMail['Subject'];
         $subject_encoding = detect_encoding($subject_aux);
         $subject_multipart_encoding = array_var($parsedMail, 'SubjectEncoding', strtoupper($encoding));
         if ($subject_multipart_encoding != 'UTF-8' && ($subject_multipart_encoding == 'KOI8-R' || $subject_multipart_encoding == 'CP866' || $subject_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($subject_aux))) {
             //KOI8-R and CP866 are Russian encodings which PHP does not detect
             $utf8_subject = $enc_conv->convert($subject_multipart_encoding, 'UTF-8', $subject_aux);
             if ($enc_conv->hasError()) {
                 $utf8_subject = utf8_encode($subject_aux);
             }
             $utf8_subject = utf8_safe($utf8_subject);
             $mail->setSubject($utf8_subject);
         } else {
             $utf8_subject = utf8_safe($subject_aux);
             $mail->setSubject($utf8_subject);
         }
         $mail->setTo($to_addresses);
         $sent_timestamp = false;
         if (array_key_exists("Date", $parsedMail)) {
             $sent_timestamp = strtotime($parsedMail["Date"]);
         }
         if ($sent_timestamp === false || $sent_timestamp === -1 || $sent_timestamp === 0) {
             $mail->setSentDate(DateTimeValueLib::now());
         } else {
             $mail->setSentDate(new DateTimeValue($sent_timestamp));
         }
         // if this constant is defined, mails older than this date will not be fetched
         if (defined('FIRST_MAIL_DATE')) {
             $first_mail_date = DateTimeValueLib::makeFromString(FIRST_MAIL_DATE);
             if ($mail->getSentDate()->getTimestamp() < $first_mail_date->getTimestamp()) {
                 // return true to stop getting older mails from the server
                 return true;
             }
         }
         $received_timestamp = false;
         if (array_key_exists("Received", $parsedMail) && $parsedMail["Received"]) {
             $received_timestamp = strtotime($parsedMail["Received"]);
         }
         if ($received_timestamp === false || $received_timestamp === -1 || $received_timestamp === 0) {
             $mail->setReceivedDate($mail->getSentDate());
         } else {
             $mail->setReceivedDate(new DateTimeValue($received_timestamp));
             if ($state == 5 && $mail->getSentDate()->getTimestamp() > $received_timestamp) {
                 $mail->setReceivedDate($mail->getSentDate());
             }
         }
         $mail->setSize(strlen($content));
         $mail->setCreatedOn(new DateTimeValue(time()));
         $mail->setCreatedById($account->getContactId());
         $mail->setAccountEmail($account->getEmail());
         $mail->setMessageId($message_id);
         $mail->setInReplyToId($in_reply_to_id);
         // set hasAttachments=true onlu if there is any attachment with FileDisposition='attachment'
         $has_attachments = false;
         foreach (array_var($parsedMail, "Attachments", array()) as $attachment) {
             if (array_var($attachment, 'FileDisposition') == 'attachment') {
                 $has_attachments = true;
             }
         }
         $mail->setHasAttachments($has_attachments);
         $mail->setUid($uid);
         $type = array_var($parsedMail, 'Type', 'text');
         switch ($type) {
             case 'html':
                 $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
                 //Solve bad syntax styles outlook if it exists
                 if (substr_count($utf8_body, "<style>") != substr_count($utf8_body, "</style>") && substr_count($utf8_body, "/* Font Definitions */") >= 1) {
                     $p1 = strpos($utf8_body, "/* Font Definitions */", 0);
                     $utf8_body1 = substr($utf8_body, 0, $p1);
                     $p0 = strrpos($utf8_body1, "</style>");
                     $html_content = ($p0 >= 0 ? substr($utf8_body1, 0, $p0) : $utf8_body1) . substr($utf8_body, $p1);
                     $utf8_body = str_replace_first("/* Font Definitions */", "<style>", $utf8_body);
                 }
                 if ($enc_conv->hasError()) {
                     $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
                 }
                 $utf8_body = utf8_safe($utf8_body);
                 $mail->setBodyHtml($utf8_body);
                 break;
             case 'text':
                 $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', ''));
                 if ($enc_conv->hasError()) {
                     $utf8_body = utf8_encode(array_var($parsedMail, 'Data', ''));
                 }
                 $utf8_body = utf8_safe($utf8_body);
                 $mail->setBodyPlain($utf8_body);
                 break;
             case 'delivery-status':
                 $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Response', ''));
                 if ($enc_conv->hasError()) {
                     $utf8_body = utf8_encode(array_var($parsedMail, 'Response', ''));
                 }
                 $utf8_body = utf8_safe($utf8_body);
                 $mail->setBodyPlain($utf8_body);
                 break;
             default:
                 if (array_var($parsedMail, 'FileDisposition') == 'inline') {
                     $attachs = array_var($parsedMail, 'Attachments', array());
                     $attached_body = "";
                     foreach ($attachs as $k => $attach) {
                         if (array_var($attach, 'Type') == 'html' || array_var($attach, 'Type') == 'text') {
                             $attached_body .= $enc_conv->convert(array_var($attach, 'Encoding'), 'UTF-8', array_var($attach, 'Data'));
                         }
                     }
                     $mail->setBodyHtml($attached_body);
                 } else {
                     if (isset($parsedMail['FileName'])) {
                         // content-type is a file type => set as it has attachments, they will be parsed when viewing email
                         $mail->setHasAttachments(true);
                     }
                 }
                 break;
         }
         if (isset($parsedMail['Alternative'])) {
             foreach ($parsedMail['Alternative'] as $alt) {
                 if ($alt['Type'] == 'html' || $alt['Type'] == 'text') {
                     $body = $enc_conv->convert(array_var($alt, 'Encoding', 'UTF-8'), 'UTF-8', array_var($alt, 'Data', ''));
                     if ($enc_conv->hasError()) {
                         $body = utf8_encode(array_var($alt, 'Data', ''));
                     }
                     // remove large white spaces
                     //$exploded = preg_split("/[\s]+/", $body, -1, PREG_SPLIT_NO_EMPTY);
                     //$body = implode(" ", $exploded);
                     // remove html comments
                     $body = preg_replace('/<!--.*-->/i', '', $body);
                 }
                 $body = utf8_safe($body);
                 if ($alt['Type'] == 'html') {
                     $mail->setBodyHtml($body);
                 } else {
                     if ($alt['Type'] == 'text') {
                         $plain = html_to_text(html_entity_decode($body, null, "UTF-8"));
                         $mail->setBodyPlain($plain);
                     }
                 }
                 // other alternative parts (like images) are not saved in database.
             }
         }
         $repository_id = self::SaveContentToFilesystem($mail->getUid(), $content);
         $mail->setContentFileId($repository_id);
         // START TRANSACTION
         DB::beginWork();
         // Conversation
         //check if exists a conversation for this mail
         $conv_mail = "";
         if ($in_reply_to_id != "" && $message_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')"));
             //check if this mail is in two diferent conversations and fixit
             if ($conv_mail) {
                 $other_conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` != " . $conv_mail->getConversationId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')"));
                 if ($other_conv_mail) {
                     $other_conv = MailContents::findAll(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` = " . $other_conv_mail->getConversationId()));
                     if ($other_conv) {
                         foreach ($other_conv as $mail_con) {
                             $mail_con->setConversationId($conv_mail->getConversationId());
                             $mail_con->save();
                         }
                     }
                 }
             }
         } elseif ($in_reply_to_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'"));
         } elseif ($message_id != "") {
             $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `in_reply_to_id` = '{$message_id}'"));
         }
         if ($conv_mail instanceof MailContent) {
             $conv_id = $conv_mail->getConversationId();
         } else {
             $conv_id = MailContents::getNextConversationId($account->getId());
         }
         $mail->setConversationId($conv_id);
         $mail->save();
         // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION
         $classified_with_conversation = false;
         $member_ids = array();
         if (user_config_option('classify_mail_with_conversation', null, $account->getContactId()) && isset($conv_mail) && $conv_mail instanceof MailContent) {
             $member_ids = array_merge($member_ids, $conv_mail->getMemberIds());
             $classified_with_conversation = true;
         }
         // CLASSIFY MAILS IF THE ACCOUNT HAS A DIMENSION MEMBER AND NOT CLASSIFIED WITH CONVERSATION
         $account_owner = Contacts::findById($account->getContactId());
         if ($account->getMemberId() != '' && !$classified_with_conversation) {
             $acc_mem_ids = explode(',', $account->getMemberId());
             foreach ($acc_mem_ids as $acc_mem_id) {
                 $member_ids[] = $acc_mem_id;
             }
         }
         foreach ($member_ids as $k => &$mem_id) {
             if ($mem_id == "") {
                 unset($member_ids[$k]);
             }
         }
         if (count($member_ids) > 0) {
             $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')'));
             $mail->addToMembers($members, true);
             /*	$ctrl = new ObjectController();
             			$ctrl->add_to_members($mail, $member_ids, $account_owner);*/
             $mail_controller = new MailController();
             $mail_controller->do_classify_mail($mail, $member_ids, null, false, true);
         }
         $user = Contacts::findById($account->getContactId());
         if ($user instanceof Contact) {
             $mail->subscribeUser($user);
         }
         $mail->addToSharingTable();
         $mail->orderConversation();
         //if email is from an imap account copy the state (read/unread) from the server
         if (!is_null($read)) {
             $mail->setIsRead($account->getContactId(), $read);
         }
         // increase received count
         $received_count++;
         // to apply email rules
         $null = null;
         Hook::fire('after_mail_download', $mail, $null);
         DB::commit();
     } catch (Exception $e) {
         $ret = null;
         Hook::fire('on_save_mail_error', array('content' => $content, 'account' => $account, 'exception' => $e), $ret);
         Logger::log($e->__toString());
         DB::rollback();
         if (FileRepository::isInRepository($repository_id)) {
             FileRepository::deleteFile($repository_id);
         }
         if (strpos($e->getMessage(), "Query failed with message 'Got a packet bigger than 'max_allowed_packet' bytes'") === false) {
             throw $e;
         }
     }
     unset($parsedMail);
     return false;
 }
Пример #20
0
 private function list_latest_active_members($request)
 {
     $service = $request['srv'];
     $members = array();
     $type = ObjectTypes::instance()->findByName($service);
     $typeId = $type->getId();
     if ($service == "workspace") {
         $dimension_id = Dimensions::findByCode('workspaces')->getId();
     } else {
         $dimension_id = Dimensions::findByCode('customer_project')->getId();
     }
     $ids = array();
     $dimensionController = new DimensionController();
     foreach ($dimensionController->latest_active_dimension_members($dimension_id, $typeId, null, user_config_option("mobile_logs_amount_to_search"), user_config_option("mobile_minimum_display_dimension_members"), user_config_option("mobile_maximum_display_dimension_members")) as $member) {
         $ids[] = $member['object_id'];
     }
     if (count($ids)) {
         $args['conditions'] = " `object_id` IN (" . implode(",", $ids) . ") AND object_type_id = {$typeId}";
         $args['order'] = " name ASC";
         foreach (Members::instance()->findAll($args) as $member) {
             /* @var $member Member */
             $memberInfo = array('id' => $member->getId(), 'name' => $member->getName(), 'type' => $service, 'path' => $member->getPath());
             $members[] = $memberInfo;
         }
     }
     return $this->response('json', $members);
 }
Пример #21
0
function save_permissions($pg_id, $is_guest = false, $permissions_data = null, $save_cmps = true, $update_sharing_table = true, $fire_hook = true, $update_contact_member_cache = true, $users_ids_to_check = array(), $only_member_permissions = false)
{
    if (is_null($permissions_data)) {
        // system permissions
        $sys_permissions_data = array_var($_POST, 'sys_perm');
        // module permissions
        $mod_permissions_data = array_var($_POST, 'mod_perm');
        // root permissions
        if ($rp_genid = array_var($_POST, 'root_perm_genid')) {
            $rp_permissions_data = array();
            foreach ($_POST as $name => $value) {
                if (str_starts_with($name, $rp_genid . 'rg_root_')) {
                    $rp_permissions_data[$name] = $value;
                }
            }
        }
        // member permissions
        $permissionsString = array_var($_POST, 'permissions');
    } else {
        // system permissions
        $sys_permissions_data = array_var($permissions_data, 'sys_perm');
        // module permissions
        $mod_permissions_data = array_var($permissions_data, 'mod_perm');
        // root permissions
        $rp_genid = array_var($permissions_data, 'root_perm_genid');
        $rp_permissions_data = array_var($permissions_data, 'root_perm');
        // member permissions
        $permissionsString = array_var($permissions_data, 'permissions');
    }
    try {
        DB::beginWork();
        $changed_members = array();
        // save module permissions
        if (!$only_member_permissions) {
            try {
                TabPanelPermissions::clearByPermissionGroup($pg_id, true);
                if (!is_null($mod_permissions_data) && is_array($mod_permissions_data)) {
                    foreach ($mod_permissions_data as $tab_id => $val) {
                        DB::execute("INSERT INTO " . TABLE_PREFIX . "tab_panel_permissions (permission_group_id,tab_panel_id) VALUES ('{$pg_id}','{$tab_id}') ON DUPLICATE KEY UPDATE permission_group_id=permission_group_id");
                    }
                }
            } catch (Exception $e) {
                Logger::log("Error saving module permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                throw $e;
            }
        }
        $root_permissions_sharing_table_delete = array();
        $root_permissions_sharing_table_add = array();
        if (logged_user() instanceof Contact && can_manage_security(logged_user())) {
            try {
                if (!$only_member_permissions) {
                    // save system permissions
                    $system_permissions = SystemPermissions::findById($pg_id);
                    if (!$system_permissions instanceof SystemPermission) {
                        $system_permissions = new SystemPermission();
                        $system_permissions->setPermissionGroupId($pg_id);
                    }
                    $system_permissions->setAllPermissions(false);
                    $other_permissions = array();
                    Hook::fire('add_user_permissions', $pg_id, $other_permissions);
                    foreach ($other_permissions as $k => $v) {
                        $system_permissions->setColumnValue($k, false);
                    }
                    // check max permissions for role, in case of modifying user's permissions
                    $role_id = "-1";
                    $tmp_contact = Contacts::findOne(array('conditions' => 'permission_group_id = ' . $pg_id));
                    if ($tmp_contact instanceof Contact) {
                        $role_id = $tmp_contact->getUserType();
                    }
                    $max_role_system_permissions = MaxSystemPermissions::findOne(array('conditions' => 'permission_group_id = ' . $role_id));
                    if ($max_role_system_permissions instanceof MaxSystemPermission) {
                        foreach ($sys_permissions_data as $col => &$val) {
                            $max_val = $max_role_system_permissions->getColumnValue($col);
                            if (!$max_val) {
                                unset($sys_permissions_data[$col]);
                            }
                        }
                    }
                    // don't allow to write emails for collaborators and guests
                    if ($tmp_contact instanceof Contact) {
                        $user_type_name = $tmp_contact->getUserTypeName();
                        if (!in_array($user_type_name, array('Super Administrator', 'Administrator', 'Manager', 'Executive'))) {
                            $mail_ot = ObjectTypes::findByName('mail');
                            if ($mail_ot instanceof ObjectType) {
                                DB::executeAll("UPDATE " . TABLE_PREFIX . "contact_member_permissions SET can_write=0, can_delete=0 WHERE object_type_id=" . $mail_ot->getId() . " AND permission_group_id={$pg_id}");
                            }
                        }
                    }
                    $sys_permissions_data['can_task_assignee'] = !$is_guest;
                    $system_permissions->setFromAttributes($sys_permissions_data);
                    $system_permissions->setUseOnDuplicateKeyWhenInsert(true);
                    $system_permissions->save();
                    //object type root permissions
                    $can_have_root_permissions = config_option('let_users_create_objects_in_root') && in_array($user_type_name, array('Super Administrator', 'Administrator', 'Manager', 'Executive'));
                    if ($rp_genid && $can_have_root_permissions) {
                        ContactMemberPermissions::delete("permission_group_id = {$pg_id} AND member_id = 0");
                        foreach ($rp_permissions_data as $name => $value) {
                            if (str_starts_with($name, $rp_genid . 'rg_root_')) {
                                $rp_ot = substr($name, strrpos($name, '_') + 1);
                                if (is_numeric($rp_ot) && $rp_ot > 0 && $value == 0) {
                                    $root_permissions_sharing_table_delete[] = $rp_ot;
                                }
                                if (!is_numeric($rp_ot) || $rp_ot <= 0 || $value < 1) {
                                    continue;
                                }
                                $root_permissions_sharing_table_add[] = $rp_ot;
                                // save with member_id = 0
                                $root_perm_cmp = new ContactMemberPermission();
                                $root_perm_cmp->setPermissionGroupId($pg_id);
                                $root_perm_cmp->setMemberId('0');
                                $root_perm_cmp->setObjectTypeId($rp_ot);
                                $root_perm_cmp->setCanWrite($value >= 2);
                                $root_perm_cmp->setCanDelete($value >= 3);
                                $root_perm_cmp->save();
                            }
                        }
                    }
                    if (!$can_have_root_permissions) {
                        ContactMemberPermissions::delete("permission_group_id = {$pg_id} AND member_id = 0");
                        $sh_controller = new SharingTableController();
                        $all_object_type_ids = ObjectTypes::findAll(array('id' => true));
                        $sh_controller->adjust_root_permissions($pg_id, array('root_permissions_sharing_table_delete' => $all_object_type_ids));
                    }
                }
            } catch (Exception $e) {
                Logger::log("Error saving system and root permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                throw $e;
            }
        }
        // set all permissions to read_only if user is guest
        if ($is_guest) {
            try {
                $all_saved_permissions = ContactMemberPermissions::findAll(array("conditions" => "`permission_group_id` = {$pg_id}"));
                foreach ($all_saved_permissions as $sp) {
                    /* @var $sp ContactMemberPermission */
                    if ($sp->getCanDelete() || $sp->getCanWrite()) {
                        $sp->setCanDelete(false);
                        $sp->setCanWrite(false);
                        $sp->save();
                    }
                }
                $cdps = ContactDimensionPermissions::findAll(array("conditions" => "`permission_type` = 'allow all'"));
                foreach ($cdps as $cdp) {
                    $cdp->setPermissionType('check');
                    $cdp->save();
                }
            } catch (Exception $e) {
                Logger::log("Error setting guest user permissions to read_only for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                throw $e;
            }
        }
        // check the status of the changed dimensions to set 'allow_all', 'deny_all' or 'check'
        try {
            $dimensions = Dimensions::findAll(array("conditions" => array("`id` IN (SELECT DISTINCT `dimension_id` FROM " . Members::instance()->getTableName(true) . " WHERE `id` IN (?))", $changed_members)));
            foreach ($dimensions as $dimension) {
                $dimension->setContactDimensionPermission($pg_id, 'check');
            }
        } catch (Exception $e) {
            Logger::log("Error setting dimension permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
            throw $e;
        }
        //member permissions
        if ($permissionsString && $permissionsString != '') {
            $permissions = json_decode($permissionsString);
        }
        if (isset($permissions) && !is_null($permissions) && is_array($permissions)) {
            try {
                $tmp_contact = Contacts::findOne(array('conditions' => 'permission_group_id = ' . $pg_id));
                if ($tmp_contact instanceof Contact) {
                    $user_type_name = $tmp_contact->getUserTypeName();
                    $role_id = $tmp_contact->getUserType();
                    $max_role_ot_perms = MaxRoleObjectTypePermissions::instance()->findAll(array('conditions' => "role_id = '{$role_id}'"));
                }
                $mail_ot = ObjectTypes::findByName('mail');
                $sql_insert_values = "";
                $member_object_types_to_delete = array();
                $allowed_members_ids = array();
                foreach ($permissions as &$perm) {
                    if (!isset($all_perm_deleted[$perm->m])) {
                        $all_perm_deleted[$perm->m] = true;
                    }
                    $allowed_members_ids[$perm->m] = array();
                    $allowed_members_ids[$perm->m]['pg'] = $pg_id;
                    if ($perm->r) {
                        if (isset($allowed_members_ids[$perm->m]['w'])) {
                            if ($allowed_members_ids[$perm->m]['w'] != 1) {
                                $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w;
                            }
                        } else {
                            $allowed_members_ids[$perm->m]['w'] = $is_guest ? false : $perm->w;
                        }
                        if (isset($allowed_members_ids[$perm->m]['d'])) {
                            if ($allowed_members_ids[$perm->m]['d'] != 1) {
                                $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d;
                            }
                        } else {
                            $allowed_members_ids[$perm->m]['d'] = $is_guest ? false : $perm->d;
                        }
                        // check max permissions for user type
                        if ($tmp_contact instanceof Contact) {
                            $max_perm = null;
                            foreach ($max_role_ot_perms as $max_role_ot_perm) {
                                if ($max_role_ot_perm->getObjectTypeId() == $perm->o) {
                                    $max_perm = $max_role_ot_perm;
                                }
                            }
                            if ($max_perm) {
                                if (!$max_perm->getCanDelete()) {
                                    $perm->d = 0;
                                }
                                if (!$max_perm->getCanWrite()) {
                                    $perm->w = 0;
                                }
                            } else {
                                $perm->d = 0;
                                $perm->w = 0;
                                $perm->r = 0;
                            }
                        }
                        if ($save_cmps) {
                            // don't allow to write emails for collaborators and guests
                            if ($tmp_contact instanceof Contact && !in_array($user_type_name, array('Super Administrator', 'Administrator', 'Manager', 'Executive'))) {
                                if ($mail_ot instanceof ObjectType && $perm->o == $mail_ot->getId()) {
                                    $perm->d = 0;
                                    $perm->w = 0;
                                }
                            }
                            $sql_insert_values .= ($sql_insert_values == "" ? "" : ",") . "('" . $pg_id . "','" . $perm->m . "','" . $perm->o . "','" . $perm->d . "','" . $perm->w . "')";
                            if (!isset($member_object_types_to_delete[$perm->m])) {
                                $member_object_types_to_delete[$perm->m] = array();
                            }
                            $member_object_types_to_delete[$perm->m][] = $perm->o;
                        }
                        $all_perm_deleted[$perm->m] = false;
                    } else {
                        if (is_numeric($perm->m) && is_numeric($perm->o)) {
                            DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id='" . $perm->m . "' AND object_type_id='" . $perm->o . "' AND permission_group_id={$pg_id}");
                        }
                    }
                    $changed_members[] = $perm->m;
                }
                if ($save_cmps) {
                    if (count($all_perm_deleted) > 0) {
                        $member_ids_to_delete = array();
                        foreach ($all_perm_deleted as $mid => $del) {
                            // also check in contact_member_permissions
                            $cmps = ContactMemberPermissions::findAll(array('conditions' => 'permission_group_id=' . $pg_id . " AND member_id={$mid}"));
                            if ($del && (!is_array($cmps) || count($cmps) == 0)) {
                                $member_ids_to_delete[] = $mid;
                            }
                        }
                        if (count($member_ids_to_delete) > 0) {
                            DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id IN (" . implode(',', $member_ids_to_delete) . ") AND permission_group_id={$pg_id}");
                        }
                    }
                    foreach ($member_object_types_to_delete as $mid => $obj_type_ids) {
                        if (count($obj_type_ids) > 0) {
                            DB::execute("DELETE FROM " . TABLE_PREFIX . "contact_member_permissions WHERE member_id={$mid} AND object_type_id IN (" . implode(',', $obj_type_ids) . ") AND permission_group_id={$pg_id}");
                        }
                    }
                    if ($sql_insert_values != "") {
                        DB::execute("INSERT INTO " . TABLE_PREFIX . "contact_member_permissions (permission_group_id, member_id, object_type_id, can_delete, can_write) VALUES {$sql_insert_values} ON DUPLICATE KEY UPDATE member_id=member_id");
                    }
                }
            } catch (Exception $e) {
                Logger::log("Error saving member permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                throw $e;
            }
        }
        DB::commit();
    } catch (Exception $e) {
        Logger::log("Error saving permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
        DB::rollback();
    }
    try {
        if (isset($permissions) && !is_null($permissions) && is_array($permissions)) {
            if ($update_sharing_table) {
                try {
                    $sharingTablecontroller = new SharingTableController();
                    $rp_info = array('root_permissions_sharing_table_delete' => $root_permissions_sharing_table_delete, 'root_permissions_sharing_table_add' => $root_permissions_sharing_table_add);
                    $sharingTablecontroller->afterPermissionChanged($pg_id, $permissions, $rp_info);
                } catch (Exception $e) {
                    Logger::log("Error saving permissions to sharing table for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                    throw $e;
                }
            }
            if ($update_contact_member_cache) {
                try {
                    $contactMemberCacheController = new ContactMemberCacheController();
                    $group = PermissionGroups::findById($pg_id);
                    $real_group = null;
                    if ($group->getType() == 'user_groups') {
                        $real_group = $group;
                    }
                    $users = $group->getUsers();
                    $users_ids_checked = array();
                    foreach ($users as $us) {
                        $users_ids_checked[] = $us->getId();
                        $contactMemberCacheController->afterUserPermissionChanged($us, $permissions, $real_group);
                    }
                    //check all users related to the group
                    foreach ($users_ids_to_check as $us_id) {
                        if (!in_array($us_id, $users_ids_checked)) {
                            $users_ids_checked[] = $us_id;
                            $us = Contacts::findById($us_id);
                            if ($us instanceof Contact) {
                                $contactMemberCacheController->afterUserPermissionChanged($us, $permissions, $real_group);
                            }
                        }
                    }
                } catch (Exception $e) {
                    Logger::log("Error saving permissions to contact member cache for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
                    throw $e;
                }
            }
        }
    } catch (Exception $e) {
        Logger::log("Error saving module permissions for permission group {$pg_id}: " . $e->getMessage() . "\n" . $e->getTraceAsString());
    }
    if ($fire_hook) {
        Hook::fire('after_save_contact_permissions', $pg_id, $pg_id);
    }
    // remove contact object from members where permissions were deleted
    $user = Contacts::findOne(array('conditions' => 'permission_group_id=' . $pg_id));
    if ($user instanceof Contact) {
        $to_remove = array();
        if (isset($all_perm_deleted) && is_array($all_perm_deleted)) {
            foreach ($all_perm_deleted as $m_id => $must_remove) {
                if ($must_remove) {
                    $to_remove[] = $m_id;
                }
            }
            ObjectMembers::removeObjectFromMembers($user, logged_user(), null, $to_remove);
        }
    }
}
Пример #22
0
 /**
  * Return manager instance
  *
  * @access protected
  * @param void
  * @return Members 
  */
 function manager()
 {
     if (!$this->manager instanceof Members) {
         $this->manager = Members::instance();
     }
     return $this->manager;
 }
Пример #23
0
	function getMember(){
		
		return Members::instance()->findById($this->getMemberId());
	}