Esempio n. 1
0
 function countAllowedContacts()
 {
     $conditions = "";
     if (!can_manage_contacts(logged_user())) {
         $conditions .= "e.user_type>0 OR e.object_id IN (\r\n\t\t\t\tSELECT st.object_id FROM " . TABLE_PREFIX . "sharing_table st WHERE st.group_id IN (\r\n\t\t\t\t\tSELECT pg.id FROM " . TABLE_PREFIX . "permission_groups pg WHERE pg.type='permission_groups' AND pg.contact_id = " . logged_user()->getId() . "\r\n\t\t\t\t)\r\n\t\t\t)";
     }
     return Contacts::instance()->count($conditions);
 }
Esempio n. 2
0
 static function getVisibleCompanies(User $user, $additional_conditions = null)
 {
     if (can_manage_contacts($user)) {
         if ($additional_conditions) {
             return self::findAll(array('conditions' => $additional_conditions));
         } else {
             return self::getAll();
         }
     } else {
         return self::getCompaniesByProjects($user->getWorkspacesQuery(true), $additional_conditions);
     }
 }
	function import_from_vcard() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		@set_time_limit(0);
		ini_set('auto_detect_line_endings', '1');
		if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) unset($_SESSION['go_back']);
		if (isset($_SESSION['go_back'])) {
			unset($_SESSION['go_back']);
			ajx_current("start");
		} else {
                
                    if(!Contact::canAdd(logged_user(), active_context())) {
                            flash_error(lang('no access permissions'));
                            ajx_current("empty");
                            return;
                    } 

                    $this->setTemplate('vcard_import');
                    tpl_assign('import_type', 'contact');                

                    $filedata = array_var($_FILES, 'vcard_file');
                    if (is_array($filedata)) {
                            $filename = ROOT.'/tmp/'.logged_user()->getId().'temp.vcf';
                            copy($filedata['tmp_name'], $filename);
                            $result = $this->read_vcard_file($filename);
                            unlink($filename);
                            $import_result = array('import_ok' => array(), 'import_fail' => array());

                            foreach ($result as $contact_data) {
                                    try {
                                            DB::beginWork();
                                            if (isset($contact_data['photo_tmp_filename'])) {
                                                $file_id = FileRepository::addFile($contact_data['photo_tmp_filename'], array('public' => true));
                                                $contact_data['picture_file'] = $file_id;
                                                unlink($contact_data['photo_tmp_filename']);
                                                unset($contact_data['photo_tmp_filename']);
                                            }
                                            if (isset($contact_data['company_name'])) {
                                                $company = Contacts::findOne(array("conditions" => "`first_name` = '".mysql_real_escape_string($contact_data['company_name'])."'"));
                                                if ($company == null) {                                                        
                                                        $company = new Contact();
                                                        $company->setObjectName($contact_data['company_name']);
                                                        $company->setIsCompany(1);
                                                        $company->save();                                                        
                                                        ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                                                }
                                                $contact_data['company_id'] = $company->getObjectId();
                                                unset($contact_data['company_name']);
                                            }

                                            $contact_data['import_status'] = '('.lang('updated').')';
                                            $fname = DB::escape(array_var($contact_data, "first_name"));
                                            $lname = DB::escape(array_var($contact_data, "surname"));
                                            $email_cond = array_var($contact_data, "email") != '' ? " OR email_address = '".array_var($contact_data, "email")."'" : "";
                                            $contact = Contacts::findOne(array(
                                                "conditions" => "first_name = ".$fname." AND surname = ".$lname." $email_cond",
                                                'join' => array(
                                                        'table' => ContactEmails::instance()->getTableName(),
                                                        'jt_field' => 'contact_id',
                                                        'e_field' => 'object_id',
                                                )));                                                        
                                            $log_action = ApplicationLogs::ACTION_EDIT;
                                            if (!$contact) {
                                                    $contact = new Contact();
                                                    $contact_data['import_status'] = '('.lang('new').')';
                                                    $log_action = ApplicationLogs::ACTION_ADD;
                                                    $can_import = active_project() != null ? $contact->canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user());
                                            } else {
                                                    $can_import = $contact->canEdit(logged_user());
                                            }

                                            if ($can_import) {
                                                    $comp_name = DB::escape(array_var($contact_data, "company_id"));
                                                    if ($comp_name != '') {
                                                            $company = Contacts::findOne(array("conditions" => "first_name = $comp_name AND is_company = 1"));
                                                            if ($company) {
                                                                    $contact_data['company_id'] = $company->getId();
                                                            } 
                                                            $contact_data['import_status'] .= " " . lang("company") . " $comp_name";
                                                    } else {
                                                            $contact_data['company_id'] = 0;
                                                    }
                                                    $contact_data['birthday'] = $contact_data["o_birthday"];
                                                    $contact_data['name'] = $contact_data['first_name']." ".$contact_data['surname'];
                                                    $contact->setFromAttributes($contact_data);
                                                    $contact->save();

                                                    //Home form
                                                    if($contact_data['h_address'] != "")
                                                        $contact->addAddress($contact_data['h_address'], $contact_data['h_city'], $contact_data['h_state'], $contact_data['h_country'], $contact_data['h_zipcode'], 'home');
                                                    if($contact_data['h_phone_number'] != "") $contact->addPhone($contact_data['h_phone_number'], 'home', true);
                                                    if($contact_data['h_phone_number2'] != "") $contact->addPhone($contact_data['h_phone_number2'], 'home');
                                                    if($contact_data['h_mobile_number'] != "") $contact->addPhone($contact_data['h_mobile_number'], 'mobile');
                                                    if($contact_data['h_fax_number'] != "") $contact->addPhone($contact_data['h_fax_number'], 'fax');
                                                    if($contact_data['h_pager_number'] != "") $contact->addPhone($contact_data['h_pager_number'], 'pager');
                                                    if($contact_data['h_web_page'] != "") $contact->addWebpage($contact_data['h_web_page'], 'personal');

                                                    //Work form
                                                    if($contact_data['w_address'] != "")
                                                        $contact->addAddress($contact_data['w_address'], $contact_data['w_city'], $contact_data['w_state'], $contact_data['w_country'], $contact_data['w_zipcode'], 'work');
                                                    if($contact_data['w_phone_number'] != "") $contact->addPhone($contact_data['w_phone_number'], 'work', true);
                                                    if($contact_data['w_phone_number2'] != "") $contact->addPhone($contact_data['w_phone_number2'], 'work');
                                                    if($contact_data['w_assistant_number'] != "") $contact->addPhone($contact_data['w_assistant_number'], 'assistant');
                                                    if($contact_data['w_callback_number'] != "") $contact->addPhone($contact_data['w_callback_number'], 'callback');
                                                    if($contact_data['w_fax_number'] != "") $contact->addPhone($contact_data['w_fax_number'], 'fax', true);
                                                    if($contact_data['w_web_page'] != "") $contact->addWebpage($contact_data['w_web_page'], 'work');

                                                    //Other form
                                                    if($contact_data['o_address'] != "")
                                                        $contact->addAddress($contact_data['o_address'], $contact_data['o_city'], $contact_data['o_state'], $contact_data['o_country'], $contact_data['o_zipcode'], 'other');
                                                    if($contact_data['o_phone_number'] != "") $contact->addPhone($contact_data['o_phone_number'], 'other', true);
                                                    if($contact_data['o_phone_number2'] != "") $contact->addPhone($contact_data['o_phone_number2'], 'other');
                                                    if($contact_data['o_web_page'] != "") $contact->addWebpage($contact_data['o_web_page'], 'other');

                                                    //Emails and instant messaging form
                                                    if($contact_data['email'] != "") $contact->addEmail($contact_data['email'], 'personal', true);
                                                    if($contact_data['email2'] != "") $contact->addEmail($contact_data['email2'], 'personal');
                                                    if($contact_data['email3'] != "") $contact->addEmail($contact_data['email3'], 'personal');

                                                    ApplicationLogs::createLog($contact, null, $log_action);
                                                    $import_result['import_ok'][] = $contact_data;
                                            } else {
                                                    throw new Exception(lang('no access permissions'));
                                            }
                                            DB::commit();					
                                    } catch (Exception $e) {
                                            DB::rollback();
                                            $fail_msg = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n"));
                                            $import_result['import_fail'][] = array('first_name' => $fname, 'surname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status'], 'fail_message' => $fail_msg);
                                    }
                            }
                            $_SESSION['go_back'] = true;
                            tpl_assign('import_result', $import_result);
                        }
                    }
                        
	}
 /**
  * Fermormance FIX: getContentObjects replacement
  * @param array $args 
  *		order = null  -  may be performance killer depending on the order criteria  
  * 		order_dir = null 
  * 		extra_conditions = null : extra sql 'inyection' - may be performance killer depending on the injected query  
  * 		join_params = null : extra join table
  * 		trashed = false 
  *	 	archived = false
  * 		start = 0 
  * 		limit = null	
  * 		ignore_context
  *		include_deleted 
  *		count_results : if true calc found rows else show 'many'	 
  *      extra_member_ids : Search also objects in this slist of members 
  *      member_ids : force to search objects in this list of members (strinct)
  *  	 
  */
 public function listing($args = array())
 {
     $result = new stdClass();
     $result->objects = array();
     $result->total = array();
     $type_id = self::getObjectTypeId();
     $SQL_BASE_JOIN = '';
     $SQL_EXTRA_JOINS = '';
     $SQL_TYPE_CONDITION = 'true';
     $SQL_FOUND_ROWS = '';
     if (isset($args['count_results'])) {
         $count_results = $args['count_results'];
     } else {
         $count_results = defined('INFINITE_PAGING') ? !INFINITE_PAGING : false;
     }
     //get only the number of results without limit not data
     if (isset($args['only_count_results'])) {
         $only_count_results = $args['only_count_results'];
     } else {
         $only_count_results = false;
     }
     $return_raw_data = array_var($args, 'raw_data');
     $start = array_var($args, 'start');
     $limit = array_var($args, 'limit');
     $member_ids = array_var($args, 'member_ids');
     $extra_member_ids = array_var($args, 'extra_member_ids');
     $ignore_context = array_var($args, 'ignore_context');
     $include_deleted = (bool) array_var($args, 'include_deleted');
     $select_columns = array_var($args, 'select_columns');
     if (empty($select_columns)) {
         $select_columns = array('*');
     }
     //template objects
     $template_objects = (bool) array_var($args, 'template_objects', false);
     $handler_class = "Objects";
     if ($type_id) {
         // If isset type, is a concrete instance linsting. Otherwise is a generic listing of objects
         $type = ObjectTypes::findById($type_id);
         /* @var $object_type ObjectType */
         $handler_class = $type->getHandlerClass();
         $table_name = self::getTableName();
         // Extra Join statements
         if ($this instanceof ContentDataObjects && $this->object_type_name == 'timeslot') {
             // if object is a timeslot and is related to a content object => check for members of the related content object.
             $SQL_BASE_JOIN = " INNER JOIN  {$table_name} e ON IF(e.rel_object_id > 0, e.rel_object_id, e.object_id) = o.id ";
             $SQL_TYPE_CONDITION = "o.object_type_id = IF(e.rel_object_id > 0, (SELECT z.object_type_id FROM " . TABLE_PREFIX . "objects z WHERE z.id = e.rel_object_id), {$type_id})";
         } else {
             $SQL_BASE_JOIN = " INNER JOIN  {$table_name} e ON e.object_id = o.id ";
             $SQL_TYPE_CONDITION = "o.object_type_id = {$type_id}";
         }
         $SQL_EXTRA_JOINS = self::prepareJoinConditions(array_var($args, 'join_params'));
     }
     if (!$ignore_context && !$member_ids) {
         $members = active_context_members(false);
         // Context Members Ids
     } elseif (count($member_ids)) {
         $members = $member_ids;
     }
     if (is_array($extra_member_ids)) {
         if (isset($members)) {
             $members = array_merge($members, $extra_member_ids);
         } else {
             $members = $extra_member_ids;
         }
     }
     // Order statement
     $SQL_ORDER = self::prepareOrderConditions(array_var($args, 'order'), array_var($args, 'order_dir'));
     // Prepare Limit SQL
     if (is_numeric(array_var($args, 'limit')) && array_var($args, 'limit') > 0) {
         $SQL_LIMIT = "LIMIT " . array_var($args, 'start', 0) . " , " . array_var($args, 'limit');
     } else {
         $SQL_LIMIT = '';
     }
     // Prepare Group By SQL $group_by = array_var($args,'group_by');
     if (array_var($args, 'group_by')) {
         $SQL_GROUP_BY = "GROUP BY " . array_var($args, 'group_by');
     } else {
         $SQL_GROUP_BY = '';
     }
     $SQL_CONTEXT_CONDITION = " true ";
     //show only objects that are on this members by classification not by hierarchy
     $show_only_member_objects = array_var($args, 'show_only_member_objects', false);
     $exclusive_in_member = '';
     if ($show_only_member_objects) {
         $exclusive_in_member = " AND om.`is_optimization` = 0";
     }
     if (!empty($members) && count($members)) {
         $SQL_CONTEXT_CONDITION = "(EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM  " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE\tom.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id {$exclusive_in_member}\r\n\t\t\t\t\tGROUP BY object_id\r\n\t\t\t\t\tHAVING count(member_id) = " . count($members) . "\r\n\t\t\t))";
     } else {
         //show only objects that are on root
         if ($show_only_member_objects) {
             if (is_array(active_context())) {
                 $active_dims_ids = array();
                 foreach (active_context() as $ctx) {
                     if ($ctx instanceof Dimension) {
                         $active_dims_ids[] = $ctx->getId();
                     }
                 }
                 if (count($active_dims_ids) > 0) {
                     $SQL_CONTEXT_CONDITION = "(NOT EXISTS (SELECT om.object_id\r\n\t\t\t\t\t\t\tFROM  " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\t\t\tINNER JOIN  " . TABLE_PREFIX . "members mem ON mem.id = om.member_id AND mem.dimension_id IN (" . implode(",", $active_dims_ids) . ")\r\n\t\t\t\t\t\t\tWHERE\to.id = om.object_id\r\n\t\t\t\t\t\t\t))";
                 }
             }
         }
     }
     // Trash && Archived CONDITIONS
     $trashed_archived_conditions = self::prepareTrashandArchivedConditions(array_var($args, 'trashed'), array_var($args, 'archived'));
     $SQL_TRASHED_CONDITION = $include_deleted ? ' TRUE ' : $trashed_archived_conditions[0];
     $SQL_ARCHIVED_CONDITION = $include_deleted ? ' AND TRUE ' : $trashed_archived_conditions[1];
     // Extra CONDITIONS
     if (array_var($args, 'extra_conditions')) {
         $SQL_EXTRA_CONDITIONS = array_var($args, 'extra_conditions');
     } else {
         $SQL_EXTRA_CONDITIONS = '';
     }
     $SQL_COLUMNS = implode(',', $select_columns);
     if (logged_user() instanceof Contact) {
         $uid = logged_user()->getId();
         // Build Main SQL
         $logged_user_pgs = implode(',', logged_user()->getPermissionGroupIds());
         $permissions_condition = "o.id IN (\r\n\t\t\t\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\tWHERE o.id = sh.object_id\r\n\t\t\t\t\tAND sh.group_id  IN ({$logged_user_pgs})\r\n\t\t\t)";
         /*
          * Check that the objects to list does not belong only to a non-manageable dimension that defines permissions
          * Object can be shown if:
          * 		1 - It belongs to at least a member in a dimension that defines permissions and is manageable
          * 		2 - Or it belongs to at least a member in a dimension that does not defines permissions
          * 		3 - Or user has permissions to read objects without classification 
          */
         if (!$type instanceof ObjectType || !$type->getName() == 'mail') {
             $without_perm_dim_ids = Dimensions::findAll(array('id' => true, 'conditions' => "defines_permissions=0"));
             $no_perm_dims_cond = "";
             if (count($without_perm_dim_ids) > 0) {
                 $no_perm_dims_cond = " OR EXISTS (\r\n\t\t\t\t\tselect * from " . TABLE_PREFIX . "object_members omems\r\n\t\t\t\t\t  inner join " . TABLE_PREFIX . "members mems on mems.id = omems.member_id\r\n\t\t\t\t\t  WHERE omems.object_id=o.id AND mems.dimension_id IN (" . implode(',', $without_perm_dim_ids) . ")\r\n\t\t\t\t)";
             }
             $permissions_condition .= " AND (\r\n\t\t\t\tEXISTS (\r\n\t\t\t\t\tSELECT cmp.permission_group_id FROM " . TABLE_PREFIX . "contact_member_permissions cmp \r\n\t\t\t\t\tWHERE cmp.member_id=0 AND cmp.permission_group_id=" . logged_user()->getPermissionGroupId() . " AND cmp.object_type_id = o.object_type_id\r\n\t\t\t\t)\r\n\t\t\t\tOR\r\n\t\t\t\tEXISTS (\r\n\t\t\t\t\tselect * from " . TABLE_PREFIX . "object_members omems\r\n\t\t\t\t\t\tinner join " . TABLE_PREFIX . "members mems on mems.id = omems.member_id\r\n\t\t\t\t\t\tinner join " . TABLE_PREFIX . "dimensions dims on dims.id = mems.dimension_id\r\n\t\t\t\t\tWHERE omems.object_id=o.id and dims.defines_permissions=1 and dims.is_manageable=1\r\n\t\t\t\t) {$no_perm_dims_cond}\r\n\t\t\t)";
         }
         /********************************************************************************************************/
         if (!$this instanceof MailContents && logged_user()->isAdministrator() || $this instanceof Contacts && $this->object_type_name == 'contact' && can_manage_contacts(logged_user())) {
             $permissions_condition = "true";
         }
         if ($this instanceof ProjectFiles && logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) {
             $permissions_condition = "IF(e.mail_id > 0,\r\n\t\t\t\t\t  e.mail_id IN (\r\n\t\t\t\t\t\t\t\t\t\tSELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh\r\n\t\t\t\t\t\t\t\t\t\tWHERE e.mail_id = sh.object_id\r\n\t\t\t\t\t\t\t\t\t\tAND sh.group_id  IN ({$logged_user_pgs})\r\n\t\t\t\t\t  ),\r\n\t\t\t\t\t  true\r\n\t\t\t\t\t)";
         }
         if ($template_objects) {
             $permissions_condition = "true";
             $SQL_BASE_JOIN .= " INNER JOIN  " . TABLE_PREFIX . "template_tasks temob ON temob.object_id = o.id ";
         }
         $sql = "\r\n\t\t\t\tSELECT {$SQL_FOUND_ROWS} {$SQL_COLUMNS} FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t{$SQL_BASE_JOIN}\r\n\t\t\t\t{$SQL_EXTRA_JOINS}\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t{$permissions_condition}\r\n\t\t\t\t\tAND\t{$SQL_CONTEXT_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TYPE_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TRASHED_CONDITION} {$SQL_ARCHIVED_CONDITION} {$SQL_EXTRA_CONDITIONS}\r\n\t\t\t\t{$SQL_GROUP_BY}\r\n\t\t\t\t{$SQL_ORDER}\r\n\t\t\t\t{$SQL_LIMIT}";
         if (isset($args['query_wraper_start'])) {
             $query_wraper_start = $args['query_wraper_start'];
             $query_wraper_end = $args['query_wraper_end'];
             $sql = $query_wraper_start . $sql . $query_wraper_end;
         }
         $sql_total = "\r\n\t\t\t\tSELECT count(o.id) as total FROM " . TABLE_PREFIX . "objects o\r\n\t\t\t\t{$SQL_BASE_JOIN}\r\n\t\t\t\t{$SQL_EXTRA_JOINS}\r\n\t\t\t\tWHERE\r\n\t\t\t\t\t{$permissions_condition}\r\n\t\t\t\t\tAND\t{$SQL_CONTEXT_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TYPE_CONDITION}\r\n\t\t\t\t\tAND {$SQL_TRASHED_CONDITION} {$SQL_ARCHIVED_CONDITION} {$SQL_EXTRA_CONDITIONS}\r\n\t\t\t\t{$SQL_GROUP_BY}\t\t\t\r\n\t\t\t";
         if (!$only_count_results) {
             // Execute query and build the resultset
             $rows = DB::executeAll($sql);
             if ($return_raw_data) {
                 $result->objects = $rows;
             } else {
                 if ($rows && is_array($rows)) {
                     foreach ($rows as $row) {
                         if ($handler_class) {
                             $phpCode = '$co = ' . $handler_class . '::instance()->loadFromRow($row);';
                             eval($phpCode);
                         }
                         if ($co) {
                             $result->objects[] = $co;
                         }
                     }
                 }
             }
             if ($count_results) {
                 $total = DB::executeOne($sql_total);
                 $result->total = $total['total'];
             } else {
                 if (count($result->objects) >= $limit) {
                     $result->total = 10000000;
                 } else {
                     $result->total = $start + count($result->objects);
                 }
             }
         } else {
             $total = DB::executeOne($sql_total);
             $result->total = $total['total'];
         }
     } else {
         $result->objects = array();
         $result->total = 0;
     }
     return $result;
 }
 /**
  * Edit project
  *
  * @param void
  * @return null
  */
 function edit()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     $this->setTemplate('add_project');
     $project = Projects::findById(get_id());
     if (!$project instanceof Project) {
         flash_error(lang('project dnx'));
         ajx_current("empty");
         return;
     }
     // if
     if (!$project->canEdit(logged_user())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $project_data = array_var($_POST, 'project');
     if (!is_array($project_data)) {
         $project_data = array('name' => $project->getName(), 'description' => $project->getDescription(), 'show_description_in_overview' => $project->getShowDescriptionInOverview(), 'color' => 0);
         // array
     }
     // if
     $projects = logged_user()->getActiveProjects();
     tpl_assign('project', $project);
     tpl_assign('projects', $projects);
     tpl_assign('project_data', $project_data);
     tpl_assign('billing_amounts', $project->getBillingAmounts());
     tpl_assign('subject_matter_experts', ProjectContacts::getContactsByProject($project));
     if (is_array(array_var($_POST, 'project'))) {
         if (array_var($project_data, 'parent_id') == $project->getId()) {
             flash_error(lang("workspace own parent error"));
             ajx_current("empty");
             return;
         }
         if (!isset($project_data['parent_id'])) {
             $project_data['parent_id'] = $project->getParentId();
         }
         $project->setFromAttributes($project_data);
         try {
             DB::beginWork();
             if (array_var($project_data, 'parent_id') != $project->getParentId()) {
                 if ($project->getParentWorkspace() instanceof Project && !logged_user()->isProjectUser($project->getParentWorkspace())) {
                     flash_error(lang('no access permissions'));
                     ajx_current("empty");
                     return;
                 }
                 // if
                 $parent = Projects::findById(array_var($project_data, 'parent_id'));
                 if ($parent) {
                     if (!$project->canSetAsParentWorkspace($parent)) {
                         flash_error(lang('error cannot set workspace as parent', $parent->getName()));
                         ajx_current("empty");
                         return;
                     }
                 }
                 $project->setParentWorkspace($parent);
             }
             $project->save();
             /* Billing */
             WorkspaceBillings::clearByProject($project);
             $billings = array_var($project_data, 'billing', null);
             if ($billings) {
                 foreach ($billings as $billing_id => $billing) {
                     if ($billing['update'] && $billing['value'] && $billing['value'] != 0) {
                         $wb = new WorkspaceBilling();
                         $wb->setProjectId($project->getId());
                         $wb->setBillingId($billing_id);
                         $value = $billing['value'];
                         if (strpos($value, ',') && !strpos($value, '.')) {
                             $value = str_replace(',', '.', $value);
                         }
                         $wb->setValue($value);
                         $wb->save();
                     }
                 }
             }
             /* Project contacts */
             if (can_manage_contacts(logged_user())) {
                 ProjectContacts::clearByProject($project);
                 $contacts = array_var($project_data, 'contacts', null);
                 if ($contacts) {
                     foreach ($contacts as $contact_data) {
                         $contact = Contacts::findById($contact_data['contact_id']);
                         if ($contact instanceof Contact) {
                             $pc = new ProjectContact();
                             $pc->setProjectId($project->getId());
                             $pc->setContactId($contact_data['contact_id']);
                             $pc->setRole($contact_data['role']);
                             $pc->save();
                         }
                     }
                 }
             }
             /* <permissions> */
             $permissions = null;
             $permissionsString = array_var($_POST, 'permissions');
             if ($permissionsString && $permissionsString != '') {
                 $permissions = json_decode($permissionsString);
             }
             if (is_array($permissions) && count($permissions) > 0) {
                 //Clear old modified permissions
                 $ids = array();
                 foreach ($permissions as $perm) {
                     $ids[] = $perm->wsid;
                 }
                 ProjectUsers::clearByProject($project, implode(',', $ids));
                 //Add new permissions
                 //TODO - Make batch update of these permissions
                 foreach ($permissions as $perm) {
                     if (ProjectUser::hasAnyPermissions($perm->pr, $perm->pc)) {
                         $relation = new ProjectUser();
                         $relation->setProjectId($project->getId());
                         $relation->setUserId($perm->wsid);
                         $relation->setCheckboxPermissions($perm->pc, $relation->getUserOrGroup()->isGuest() ? false : true);
                         $relation->setRadioPermissions($perm->pr, $relation->getUserOrGroup()->isGuest() ? false : true);
                         $relation->save();
                     }
                     //endif
                     //else if the user has no permissions at all, he is not a project_user. ProjectUser is not created
                 }
                 //end foreach
             }
             // if
             /* </permissions> */
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($project);
             ApplicationLogs::createLog($project, null, ApplicationLogs::ACTION_EDIT, false, true);
             DB::commit();
             if (logged_user()->isProjectUser($project)) {
                 $workspace_info = $this->get_workspace_info($project);
                 evt_add("workspace edited", $workspace_info);
             }
             flash_success(lang('success edit project', $project->getName()));
             ajx_current("back");
             return;
         } catch (Exception $e) {
             DB::rollback();
             flash_error($e->getMessage());
             ajx_current("empty");
         }
         // try
     }
     // if
 }
 /**
  * Check if specific user can delete this contact
  *
  * @access public
  * @param User $user
  * @return boolean
  */
 function canDelete(Contact $user)
 {
     // dont delete account owner
     if ($this->isAccountOwner() || $this->isOwnerCompany()) {
         return false;
     }
     if ($this->getUserType() != 0) {
         return can_manage_security($user) && $this->getUserType() > $user->getUserType();
     } else {
         return can_manage_contacts($user) || can_delete($user, $this->getMembers(), $this->getObjectTypeId());
     }
 }
 private static function getPersonLinkFromEmailAddress($email, $addr_name, $clean = true, $add_contact_link = true)
 {
     $name = $email;
     $url = "";
     $user = Users::getByEmail($email);
     if ($user instanceof User && $user->canSeeUser(logged_user())) {
         $name = $clean ? clean($user->getDisplayName()) : $user->getDisplayName();
         $url = $user->getCardUrl();
     } else {
         $contact = Contacts::getByEmail($email);
         if ($contact instanceof Contact && $contact->canView(logged_user())) {
             $name = $clean ? clean($contact->getDisplayName()) : $contact->getDisplayName();
             $url = $contact->getCardUrl();
         }
     }
     if ($url != "") {
         return '<a class="internalLink" href="' . $url . '" title="' . $email . '">' . $name . " &lt;{$email}&gt;</a>";
     } else {
         if (!(active_project() instanceof Project ? Contact::canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user()))) {
             return $email;
         } else {
             $url = get_url('contact', 'add', array('ce' => $email));
             $to_show = $addr_name == '' ? $email : $addr_name . " &lt;{$email}&gt;";
             return $to_show . ($add_contact_link ? '&nbsp;<a class="internalLink link-ico ico-add" style="padding-left:12px;" href="' . $url . '" title="' . lang('add contact') . '">&nbsp;</a>' : '');
         }
     }
 }
 /**
  * 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');
     $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 = $this->getDefaultAccountId();
     if ($def_acc > 0) {
         tpl_assign('default_account', $def_acc);
     }
     tpl_assign('mail', $mail);
     tpl_assign('mail_data', $mail_data);
     tpl_assign('mail_accounts', $mail_accounts);
     // 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 = MailAccountUsers::getByAccountAndUser($account, logged_user());
         if (!$accountUser instanceof MailAccountUser) {
             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:Arial,Verdana,sans-serif;font-size:12px;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();
         $objects = array_var($_POST, 'linked_objects');
         $attach_contents = array_var($_POST, 'attach_contents', array());
         if (is_array($objects)) {
             $err = 0;
             $count = -1;
             foreach ($objects as $objid) {
                 $count++;
                 $split = explode(":", $objid);
                 if (count($split) == 2) {
                     $object = get_object_by_manager_and_id($split[1], $split[0]);
                 } else {
                     if (count($split) == 4) {
                         if ($split[0] == 'FwdMailAttach') {
                             $tmp_filename = ROOT . "/tmp/" . logged_user()->getId() . "_" . $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
                             $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()), "manager" => $object->getObjectManagerName(), "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 {
             if (count($linked_attachments)) {
                 $linked_users = array();
                 foreach ($to as $to_user) {
                     $linked_user = Users::getByEmail($to_user[1]);
                     if (!$linked_user instanceof User) {
                         try {
                             $linked_user = create_user_from_email($to_user[1], $to_user[0]);
                         } catch (Exception $e) {
                             //Logger::log($e->getMessage());
                         }
                     }
                     if ($linked_user instanceof User) {
                         $linked_users[] = $linked_user;
                     }
                 }
                 $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(get_object_by_manager_and_id($att['id'], $att['manager']));
                         } 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']);
                     $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 ? 2 : 200);
             $mail->setIsPrivate(false);
             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') {
                 $mail->setBodyHtml($body);
                 $mail->setBodyPlain(utf8_safe(html_to_text($body)));
             } else {
                 $mail->setBodyPlain($body);
                 $mail->setBodyHtml('');
             }
             $mail->setFrom($account->getEmailAddress());
             $mail->setFromName(logged_user()->getDisplayName());
             $mail->save();
             $mail->setIsRead(logged_user()->getId(), true);
             $mail->setTagsFromCSV(array_var($mail_data, 'tags'));
             // autoclassify sent email
             // if replying a classified email classify on same workspace
             $classified = 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) {
                     $workspaces = $in_reply_to->getWorkspaces();
                     foreach ($workspaces as $w) {
                         if ($mail->canAdd(logged_user(), $w)) {
                             $mail->addToWorkspace($w);
                             $classified = true;
                         }
                     }
                 }
             }
             if (!$classified && $account->getWorkspace() instanceof Project) {
                 $mail->addToWorkspace($account->getWorkspace());
             }
             if (!$classified && active_project() instanceof Project) {
                 $mail->addToWorkspace(active_project());
             }
             $object_controller = new ObjectController();
             $object_controller->add_custom_properties($mail);
             $object_controller->link_to_new_object($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 = get_object_by_manager_and_id($split_object[1], $split_object[0]);
                     if ($object instanceof ProjectDataObject) {
                         $mail->linkObject($object);
                     }
                 }
             }
             ApplicationLogs::createLog($mail, $mail->getWorkspaces(), ApplicationLogs::ACTION_ADD);
             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->setEmail($recipient_address);
                             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) {
                             // TODO: show error message?
                         }
                     }
                 }
             }
             DB::commit();
             if (!$autosave) {
                 if ($isDraft) {
                     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
 }
Esempio n. 9
0
 function canLinkObject(User $user)
 {
     return can_manage_contacts($user, true) || can_read($user, $this);
 }
Esempio n. 10
0
/**
 * Enter description here...
 * assumes manager has one field as PK
 *
 * @param DataManager $manager
 * @param $access_level ACCESS_LEVEL_XX objects that defines which permission is being checked
 * @param string $project_id string that will be compared to the project id while searching project_user table
 * @param int $user_id user whose permissions are being checked
 * @return unknown
 */
function permissions_sql_for_listings(DataManager $manager, $access_level, User $user, $project_id = '`project_id`', $table_alias = null)
{
    if (!$manager instanceof DataManager) {
        throw new Exception("Invalid manager '{$manager}' in permissions helper", -1);
        return '';
    }
    $user_id = $user->getId();
    $oup_tablename = ObjectUserPermissions::instance()->getTableName(true);
    $wo_tablename = WorkspaceObjects::instance()->getTableName(true);
    $users_table_name = Users::instance()->getTableName(true);
    $pu_table_name = ProjectUsers::instance()->getTableName(true);
    if ($user->isGuest() && $access_level == ACCESS_LEVEL_WRITE) {
        return 'false';
    }
    if (isset($table_alias) && $table_alias && $table_alias != '') {
        $object_table_name = $table_alias;
    } else {
        $object_table_name = $manager->getTableName();
    }
    if (!is_numeric($project_id)) {
        $project_id = "{$object_table_name}.{$project_id}";
    }
    $object_id_field = $manager->getPkColumns();
    $object_id = $object_table_name . '.' . $object_id_field;
    $object_manager = get_class($manager);
    $access_level_text = access_level_field_name($access_level);
    $item_class = $manager->getItemClass();
    $is_project_data_object = new $item_class() instanceof ProjectDataObject;
    // permissions for contacts
    if ($manager instanceof Contacts && can_manage_contacts($user)) {
        return 'true';
    }
    if ($manager instanceof Companies && can_manage_contacts($user)) {
        return 'true';
    }
    // permissions for file revisions
    if ($manager instanceof ProjectFileRevisions) {
        $pfTableName = "`" . TABLE_PREFIX . "project_files`";
        return "{$object_table_name}.`file_id` IN (SELECT `id` FROM {$pfTableName} WHERE " . permissions_sql_for_listings(ProjectFiles::instance(), $access_level, $user) . ")";
    }
    // permissions for projects
    if ($manager instanceof Projects) {
        $pcTableName = "`" . TABLE_PREFIX . 'project_users`';
        return "{$object_table_name}.`id` IN (SELECT `project_id` FROM {$pcTableName} `pc` WHERE `user_id` = {$user_id})";
    }
    // permissions for users
    if ($manager instanceof Users) {
        if (logged_user()->isMemberOfOwnerCompany()) {
            return "true";
        } else {
            return "{$object_table_name}.`company_id` = " . owner_company()->getId() . " OR {$object_table_name}.`company_id` = " . logged_user()->getCompanyId();
        }
    }
    $can_manage_object = manager_class_field_name($object_manager, $access_level);
    // user is creator
    $str = " ( `created_by_id` = {$user_id}) ";
    // element belongs to personal project
    /*if($is_project_data_object) // TODO: type of element belongs to a project
    			if (!in_array('project_id', $manager->getColumns())) {
    				$str .= "\n OR ( EXISTS(SELECT * FROM $users_table_name `xx_u`, $wo_tablename `xx_wo`
    				WHERE `xx_u`.`id` = $user_id
    					AND `xx_u`.`personal_project_id` = `xx_wo`.`workspace_id`
    					AND `xx_wo`.`object_id` = $object_id 
    					AND `xx_wo`.`object_manager` = '$object_manager' )) ";
    			} else {
    				$str .= "\n OR ( $project_id = (SELECT `personal_project_id` FROM $users_table_name `xx_u` WHERE `xx_u`.`id` = $user_id)) ";
    			}
    		*/
    // user or group has specific permissions over object
    $group_ids = $user->getGroupsCSV();
    $all_ids = '(' . $user_id . ($group_ids != '' ? ',' . $group_ids : '') . ')';
    $str .= "\n OR ( EXISTS ( SELECT * FROM {$oup_tablename} `xx_oup` \n\t\t\t\tWHERE `xx_oup`.`rel_object_id` = {$object_id} \n\t\t\t\t\tAND `xx_oup`.`rel_object_manager` = '{$object_manager}' \n\t\t\t\t\tAND `xx_oup`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_oup`.{$access_level_text} = true) )";
    if ($is_project_data_object) {
        // TODO: type of element belongs to a project
        if (!in_array('project_id', $manager->getColumns())) {
            $str .= "\n OR ( EXISTS ( SELECT * FROM {$pu_table_name} `xx_pu`, {$wo_tablename} `xx_wo` \n\t\t\t\tWHERE `xx_pu`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_pu`.`project_id` = `xx_wo`.`workspace_id`\n\t\t\t\t\tAND `xx_wo`.`object_id` = {$object_id} \n\t\t\t\t\tAND `xx_wo`.`object_manager` = '{$object_manager}'\n\t\t\t\t\tAND `xx_pu`.{$can_manage_object} = true ) ) ";
        } else {
            $str .= "\n OR ( EXISTS ( SELECT * FROM {$pu_table_name} `xx_pu` \n\t\t\t\tWHERE `xx_pu`.`user_id` IN {$all_ids} \n\t\t\t\t\tAND `xx_pu`.`project_id` = {$project_id} \n\t\t\t\t\tAND `xx_pu`.{$can_manage_object} = true ) ) ";
        }
    }
    // check account permissions in case of emails
    if ($manager instanceof MailContents) {
        $maccTableName = MailAccountUsers::instance()->getTableName(true);
        $str .= "\n OR EXISTS(SELECT `id` FROM {$maccTableName} WHERE `account_id` = {$object_table_name}.`account_id` AND `user_id` = {$user_id})";
        if (user_config_option('view deleted accounts emails', null, $user_id)) {
            $str .= "\n OR ((SELECT count(*) FROM `" . TABLE_PREFIX . "mail_accounts` WHERE `id` = {$object_table_name}.`account_id`) = 0) AND `created_by_id` = {$user_id}";
        }
    }
    $hookargs = array('manager' => $manager, 'access_level' => $access_level, 'user' => $user, 'project_id' => $project_id, 'table_alias' => $table_alias);
    Hook::fire('permissions_sql', $hookargs, $str);
    return ' (' . $str . ') ';
}
Esempio n. 11
0
</div>
		</div>
			<?php 
    } else {
        echo select_project2('project[parent_id]', $project->isNew() ? active_project() ? active_project()->getId() : 0 : $project->getParentId(), $genid, true);
    }
    ?>
	</fieldset>
	<div id="trap1"><fieldset id="fs1" style="height:0px;border:0px;padding:0px;display:none"><span style="color:#FFFFFF;"></span></fieldset></div>
	<?php 
}
?>
	
	
	<?php 
if (can_manage_contacts(logged_user())) {
    ?>
	<div id="<?php 
    echo $genid;
    ?>
project_contacts" style="display:none">
	<fieldset>
	<legend><?php 
    echo lang('workspace contacts');
    ?>
</legend>
		<div id="<?php 
    echo $genid;
    ?>
contacts">
			<table id="<?php 
 function search()
 {
     ajx_current('empty');
     if (!can_manage_contacts(logged_user())) {
         flash_error(lang("no access permissions"));
         return;
     }
     $search_for = array_var($_POST, 'search_for', false);
     if ($search_for) {
         $search_results = SearchableObjects::searchByType($search_for, null, 'Companies', true, 50);
         $companies = $search_results[0];
         if ($companies && count($companies) > 0) {
             $result = array();
             foreach ($companies as $companyResult) {
                 $company = $companyResult['object'];
                 $result[] = array('name' => $company->getName(), 'id' => $company->getId(), 'phone' => $company->getPhoneNumber(), 'email' => $company->getEmail());
             }
             ajx_extra_data(array("results" => $result));
         }
     }
 }
Esempio n. 13
0
<?php

// Set page title and set crumbs to index
if ($user->canUpdateProfile(logged_user())) {
    add_page_action(lang('update profile'), $user->getEditProfileUrl(), 'ico-edit', null, null, true);
    add_page_action(lang('update avatar'), $user->getUpdateAvatarUrl(), 'ico-picture', null, null, true);
    add_page_action(lang('change password'), $user->getEditPasswordUrl(), 'ico-password', null, null, true);
    $contact = $user->getContact();
    if (can_manage_contacts(logged_user()) && !$contact instanceof Contact) {
        add_page_action(lang('create contact from user'), "javascript:if(confirm('" . lang('confirm create contact from user') . "')) og.openLink('" . $user->getCreateContactFromUserUrl() . "');", 'ico-add');
    }
}
// if
if ($user->getId() == logged_user()->getId()) {
    add_page_action(lang('edit preferences'), $user->getEditPreferencesUrl(), 'ico-administration', null, null, true);
}
if ($user->canUpdatePermissions(logged_user())) {
    add_page_action(lang('permissions'), $user->getUpdatePermissionsUrl(), 'ico-permissions', null, null, true);
}
// if
?>



<div style="padding: 7px">
<div class="user"><?php 
$description = "";
if (isset($contact)) {
    if ($contact) {
        if ($description != '') {
            $description .= '<br/>';
Esempio n. 14
0
 /**
  * Returns true if specific user can add client company
  *
  * @access public
  * @param User $user
  * @return boolean
  */
 function canAdd(User $user, Project $project)
 {
     return can_manage_contacts(logged_user()) || can_add($user, $project, get_class(Companies::instance()));
 }
 function import_from_vcard()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     @set_time_limit(0);
     ini_set('auto_detect_line_endings', '1');
     if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) {
         unset($_SESSION['go_back']);
     }
     if (isset($_SESSION['go_back'])) {
         unset($_SESSION['go_back']);
         ajx_current("start");
     }
     tpl_assign('import_type', 'contact');
     if (!Contact::canAdd(logged_user(), active_or_personal_project())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $this->setTemplate('vcard_import');
     $filedata = array_var($_FILES, 'vcard_file');
     if (is_array($filedata) && !array_var($_GET, 'step2')) {
         $filename = ROOT . '/tmp/' . logged_user()->getId() . 'temp.vcf';
         copy($filedata['tmp_name'], $filename);
         //ajx_current("empty");
     } else {
         if (array_var($_GET, 'step2')) {
             $filename = ROOT . '/tmp/' . logged_user()->getId() . 'temp.vcf';
             $result = $this->read_vcard_file($filename);
             unlink($filename);
             $import_result = array('import_ok' => array(), 'import_fail' => array());
             foreach ($result as $contact_data) {
                 try {
                     DB::beginWork();
                     if (isset($contact_data['photo_tmp_filename'])) {
                         $file_id = FileRepository::addFile($contact_data['photo_tmp_filename'], array('public' => true));
                         $contact_data['picture_file'] = $file_id;
                         unlink($contact_data['photo_tmp_filename']);
                         unset($contact_data['photo_tmp_filename']);
                     }
                     if (isset($contact_data['company_name'])) {
                         $company = Companies::findOne(array("conditions" => "`name` = '" . mysql_real_escape_string($contact_data['company_name']) . "'"));
                         if ($company == null) {
                             $company = new Company();
                             $company->setName($contact_data['company_name']);
                             $company->setClientOfId(logged_user()->getCompanyId());
                             $company->save();
                             ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                         }
                         $contact_data['company_id'] = $company->getId();
                         unset($contact_data['company_name']);
                     }
                     $contact_data['import_status'] = '(' . lang('updated') . ')';
                     $fname = mysql_real_escape_string(array_var($contact_data, "firstname"));
                     $lname = mysql_real_escape_string(array_var($contact_data, "lastname"));
                     $contact = Contacts::findOne(array("conditions" => "firstname = '" . $fname . "' AND lastname = '" . $lname . "' OR email <> '' AND email = '" . array_var($contact_data, "email") . "'"));
                     $log_action = ApplicationLogs::ACTION_EDIT;
                     if (!$contact) {
                         $contact = new Contact();
                         $contact_data['import_status'] = '(' . lang('new') . ')';
                         $log_action = ApplicationLogs::ACTION_ADD;
                         $can_import = active_project() != null ? $contact->canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user());
                     } else {
                         $can_import = $contact->canEdit(logged_user());
                     }
                     if ($can_import) {
                         $contact->setFromAttributes($contact_data);
                         $contact->save();
                         ApplicationLogs::createLog($contact, null, $log_action);
                         $contact->setTagsFromCSV(array_var($_GET, 'tags'));
                         if (active_project() instanceof Project) {
                             $pc = ProjectContacts::findOne(array("conditions" => "contact_id = " . $contact->getId() . " AND project_id = " . active_project()->getId()));
                             if (!$pc) {
                                 $pc = new ProjectContact();
                                 $pc->setContactId($contact->getId());
                                 $pc->setProjectId(active_project()->getId());
                                 $pc->setRole(array_var($contact_data, 'role'));
                                 $pc->save();
                             }
                             $contact->addToWorkspace(active_project());
                         }
                         $import_result['import_ok'][] = array('firstname' => $fname, 'lastname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status']);
                     } else {
                         throw new Exception(lang('no access permissions'));
                     }
                     DB::commit();
                 } catch (Exception $e) {
                     DB::rollback();
                     $fail_msg = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n"));
                     $import_result['import_fail'][] = array('firstname' => $fname, 'lastname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status'], 'fail_message' => $fail_msg);
                 }
             }
             $_SESSION['go_back'] = true;
             tpl_assign('import_result', $import_result);
         }
     }
 }