function getMailAccountsEditByUser(Contact $user)
 {
     //return MailAccounts::findAll(array("conditions"=>"contact_id = ".logged_user()->getId()));
     $accounts = array();
     $accountUsers = MailAccountContacts::getByContact($user);
     foreach ($accountUsers as $au) {
         $account = $au->getAccount();
         if ($account instanceof MailAccount) {
             $accounts[] = $account;
         }
     }
     return $accounts;
 }
 /**
  * Returns a list of emails according to the requested parameters
  *
  * @param string $tag
  * @param array $attributes
  * @param Project $project
  * @return array
  */
 function getEmails($account_id = null, $state = null, $read_filter = "", $classif_filter = "", $context = null, $start = null, $limit = null, $order_by = 'received_date', $dir = 'ASC', $join_params = null, $archived = false, $conversation_list = null, $only_count_result = false)
 {
     $mailTablePrefix = "e";
     if (!$limit) {
         $limit = user_config_option('mails_per_page') ? user_config_option('mails_per_page') : config_option('files_per_page');
     }
     $accountConditions = "";
     // Check for accounts
     $accountConditions = '';
     if (isset($account_id) && $account_id > 0) {
         //Single account
         $accountConditions = " AND {$mailTablePrefix}.account_id = " . DB::escape($account_id);
     } else {
         // show mails for all visible accounts and classified mails where logged_user has permissions so we don't filter by account_id
         /*// show emails from other accounts
         		$macs = MailAccountContacts::instance()->getByContact(logged_user());
         		$acc_ids = array(0);
         		foreach ($macs as $mac) $acc_ids[] = $mac->getAccountId();
         		
         		// permission conditions
         		$pgs = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId());
         		if (trim($pgs == '')) $pgs = '0';
         		$perm_sql = "(SELECT count(*) FROM ".TABLE_PREFIX."sharing_table st WHERE st.object_id = $mailTablePrefix.object_id AND st.group_id IN ($pgs)) > 0";
         		
         		// show mails for all visible accounts and classified mails where logged_user has permissions
         		$accountConditions = " AND ($mailTablePrefix.account_id IN (" . implode(",", $acc_ids) . ") OR $perm_sql)";*/
     }
     // Check for unclassified emails
     $classified = '';
     if ($classif_filter != '' && $classif_filter != 'all') {
         $persons_dim = Dimensions::findByCode('feng_persons');
         $persons_dim_id = $persons_dim instanceof Dimension ? $persons_dim->getId() : "0";
         $classified = "AND " . ($classif_filter == 'unclassified' ? "NOT " : "");
         $classified .= "o.id IN (SELECT om.object_id FROM " . TABLE_PREFIX . "object_members om INNER JOIN " . TABLE_PREFIX . "members m ON m.id=om.member_id WHERE m.dimension_id<>{$persons_dim_id})";
     }
     // if not filtering by account or classification then check that emails are classified or from one of my accounts
     if ($classified == '' && $accountConditions == '') {
         $macs = MailAccountContacts::instance()->getByContact(logged_user());
         $acc_ids = array(0);
         foreach ($macs as $mac) {
             $acc_ids[] = $mac->getAccountId();
         }
         $accountConditions = " AND ({$mailTablePrefix}.account_id IN (" . implode(',', $acc_ids) . ") OR EXISTS (\r\n\t\t\t\t\tSELECT om1.object_id FROM " . TABLE_PREFIX . "object_members om1 \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m1 ON m1.id=om1.member_id \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d1 ON d1.id=m1.dimension_id \r\n\t\t\t\t\tWHERE om1.object_id={$mailTablePrefix}.object_id AND d1.is_manageable=1) ) ";
     }
     // Check for draft, junk, etc. emails
     if ($state == "draft") {
         $stateConditions = " {$mailTablePrefix}.state = '2'";
     } else {
         if ($state == "sent") {
             $stateConditions = " {$mailTablePrefix}.state IN ('1','3','5')";
         } else {
             if ($state == "received") {
                 $stateConditions = " {$mailTablePrefix}.state IN ('0','5')";
             } else {
                 if ($state == "junk") {
                     $stateConditions = " {$mailTablePrefix}.state = '4'";
                 } else {
                     if ($state == "outbox") {
                         $stateConditions = " {$mailTablePrefix}.state >= 200";
                     } else {
                         $stateConditions = "";
                     }
                 }
             }
         }
     }
     // Check read emails
     if ($read_filter != "" && $read_filter != "all") {
         if ($read_filter == "unread") {
             $read = "AND NOT ";
             $subread = "AND NOT mc.";
         } else {
             $read = "AND ";
             $subread = "AND mc.";
         }
         $read2 = "id IN (SELECT rel_object_id FROM " . TABLE_PREFIX . "read_objects t WHERE contact_id = " . logged_user()->getId() . " AND id = t.rel_object_id AND t.is_read = '1')";
         $read .= $read2;
         $subread .= $read2;
     } else {
         $read = "";
         $subread = "";
     }
     $conversation_cond = "";
     $box_cond = "AND {$stateConditions}";
     if (isset($conversation_list) && $conversation_list > 0) {
         $conversation_cond = "AND e.conversation_last = 1";
     }
     $extra_conditions = "{$accountConditions} {$classified} {$read} {$conversation_cond} {$box_cond}";
     Hook::fire("listing_extra_conditions", null, $extra_conditions);
     return self::instance()->listing(array('limit' => $limit, 'start' => $start, 'order' => $order_by, 'order_dir' => $dir, 'extra_conditions' => $extra_conditions, 'count_results' => false, 'only_count_results' => $only_count_result, 'join_params' => $join_params));
 }
	/**
	 * Override defaults. 
	 * Also adds mail to sharing table if is not categorized. 
	 * Only permissions for the account owner.  
	 * 
	 * @see ContentDataObject::addToSharingTable()
	 */
	function addToSharingTable() {	
		parent::addToSharingTable();
		$id = $this->getId();
		
		if(!$this->getAccount() instanceof MailAccount) return;
		
		$macs = MailAccountContacts::instance()->getByAccount($this->getAccount());
		foreach ($macs as $mac) {
		
			$contactId = $mac->getContactId();
			$contact = Contacts::instance()->findById($contactId);
			
			if (!$contact instanceof Contact) continue;
			
			$group_id = $contact->getPermissionGroupId();
			if ($group_id) {
				$sql = "INSERT INTO ".TABLE_PREFIX."sharing_table ( object_id, group_id ) VALUES ('$id','$group_id') ON DUPLICATE KEY UPDATE group_id = group_id ";
				DB::execute($sql);
			}
			
		}
	}
	/**
	 * Returns a list of emails according to the requested parameters
	 *
	 * @param string $tag
	 * @param array $attributes
	 * @param Project $project
	 * @return array
	 */
	function getEmails($account_id = null, $state = null, $read_filter = "", $classif_filter = "", $context = null, $start = null, $limit = null, $order_by = 'received_date', $dir = 'ASC', $join_params = null, $archived = false) {
		$mailTablePrefix = "e";
		if (!$limit) $limit = user_config_option('mails_per_page') ? user_config_option('mails_per_page') : config_option('files_per_page');
		$accountConditions = "";
		// Check for accounts
		$accountConditions = '';
		if (isset($account_id) && $account_id > 0) { //Single account
			$accountConditions = " AND $mailTablePrefix.account_id = " . DB::escape($account_id);
		} else {
			// show emails from other accounts
			$macs = MailAccountContacts::instance()->getByContact(logged_user());
			$acc_ids = array(0);
			foreach ($macs as $mac) $acc_ids[] = $mac->getAccountId();
			
			// permission conditions
			$pgs = ContactPermissionGroups::getPermissionGroupIdsByContactCSV(logged_user()->getId());
			if (trim($pgs == '')) $pgs = '0';
			$perm_sql = "(SELECT count(*) FROM ".TABLE_PREFIX."sharing_table st WHERE st.object_id = $mailTablePrefix.object_id AND st.group_id IN ($pgs)) > 0";
			
			// show mails for all visible accounts and classified mails where logged_user has permissions
			$accountConditions = " AND ($mailTablePrefix.account_id IN (" . implode(",", $acc_ids) . ") OR $perm_sql)";
		}
		
		// Check for unclassified emails
		$classified = '';
		if ($classif_filter != '' && $classif_filter != 'all') {
			$classified = "AND " . ($classif_filter == 'unclassified' ? "NOT " : "");
			$classified .= "o.id IN (SELECT object_id FROM ".TABLE_PREFIX."object_members)";
		}

		// Check for draft, junk, etc. emails
		if ($state == "draft") {
			$stateConditions = " $mailTablePrefix.state = '2'";
		} else if ($state == "sent") {
			$stateConditions = " $mailTablePrefix.state IN ('1','3','5')";
		} else if ($state == "received") {
			$stateConditions = " $mailTablePrefix.state IN ('0','5')";
		} else if ($state == "junk") {
			$stateConditions = " $mailTablePrefix.state = '4'";
		} else if ($state == "outbox") {
			$stateConditions = " $mailTablePrefix.state >= 200";
		} else {
			$stateConditions = "";
		}
		
		// Check read emails
		if ($read_filter != "" && $read_filter != "all") {
			if ($read_filter == "unread") {
				$read = "AND NOT ";
				$subread = "AND NOT mc.";
			} else {
				$read = "AND ";
				$subread = "AND mc."; 
			}
			$read2 = "id IN (SELECT rel_object_id FROM " . TABLE_PREFIX . "read_objects t WHERE contact_id = " . logged_user()->getId() . "  AND t.is_read = '1')";
			$read .= $read2;
			$subread .= $read2;
		} else {
			$read = "";
			$subread = "";
		}

		
		
		// Conversations not allowed yet
		//if (user_config_option('show_emails_as_conversations')) {
		//	$state_conv_cond_1 = $state != 'received' ? " $stateConditions AND " : " m.state <> '2' AND ";
		//	$state_conv_cond_2 = $state != 'received' ? " AND (mc.state = '1' OR mc.state = '3' OR mc.state = '5') " : " AND mc.state <> '2' ";
		//	$archived_by_id = $archived ? "AND o.archived_by_id != 0" : "AND o.archived_by_id = 0";
		//	$trashed_by_id = "AND o.trashed_by_id = 0";
		//	$conversation_cond = "AND IF(m.conversation_id = 0, $stateConditions, $state_conv_cond_1 NOT EXISTS (SELECT * FROM ".TABLE_PREFIX."mail_contents mc WHERE m.conversation_id = mc.conversation_id AND m.account_id = mc.account_id AND m.received_date < mc.received_date $archived_by_id AND mc.is_deleted = 0 $trashed_by_id $subread $state_conv_cond_2))";
		//	$box_cond = "AND IF(EXISTS(SELECT * FROM ".TABLE_PREFIX."mail_contents mc WHERE m.conversation_id = mc.conversation_id AND m.object_id <> o.id AND m.account_id = mc.account_id $archived_by_id AND mc.is_deleted = 0 $trashed_by_id AND $stateConditions), TRUE, $stateConditions)";
		//} else {
			$conversation_cond = "";
			$box_cond = "AND $stateConditions";
		//}

		/*return self::findByContext(array('limit' => $limit, 'offset' => $start, 'order' => "$order_by $dir",
			'extra_conditions' => "$accountConditions $classified $read $conversation_cond $box_cond")); */

		return self::instance()->listing(array(
			'limit' => $limit, 
			'start' => $start, 
			'order' => $order_by,
			'order_dir' => $dir,
			'extra_conditions' => "$accountConditions $classified $read $conversation_cond $box_cond",
			//'count_results' => false,
			'join_params' => $join_params
		));
		
		
		
	}
Beispiel #5
0
		<th><?php echo lang('outgoing server') ?></th>
		<th><?php echo lang('users') ?></th>
		<th><?php echo lang('options') ?></th>
	</tr>
	<?php
	$isAlt = true;
	foreach($all_accounts as $account) {
		$isAlt = !$isAlt;
		?>
	<tr class="<?php echo $isAlt? 'altRow' : ''?>">
		<td><?php echo clean($account->getName()) ?></td>
		<td><?php echo $account->getEmailAddress() ?></td>
		<td><?php echo $account->getOwner() instanceof Contact ? $account->getOwner()->getObjectName() : lang("n/a") ?></td>
		<td><?php echo $account->getServer() ?></td>
		<td><?php echo $account->getSmtpServer() ?></td>
		<td><?php echo MailAccountContacts::countByAccount($account) ?></td>
		<?php
		$options = array();
		if (($account->canDelete(logged_user()) && $account->getContactId() == logged_user()->getId()) || $account->canEdit(logged_user())) {
			$options[] = '<a class="internalLink" href="'.get_url('mail', 'edit_account', array('id' => $account->getId())).'">' . lang('edit') . '</a>';
		}
		if ($account->canDelete(logged_user())) {
			$options[] = '<a class="internalLink" href="javascript:og.promptDeleteAccount(' . $account->getId() . ', true)">' . lang('delete') . '</a>';
		} // if
		if ($account->canDelete(logged_user()) && config_option("sent_mails_sync")) {		
			$options[] = '<a class="internalLink" href="'.get_url('mail', 'sync_old_sent_mails', array('id' => $account->getId())).'">' . lang('sync') . '</a>';
		}		
		?>
		<td style="font-size: 80%;"><?php echo implode(' | ', $options) ?></td>
	</tr>
	<?php } // foreach ?>
 function hasEmailAccounts()
 {
     $mail_plugin_enabled = Plugins::instance()->isActivePlugin('mail');
     if ($mail_plugin_enabled) {
         $accounts = MailAccountContacts::find(array('conditions' => '`contact_id` = ' . $this->getId()));
         return is_array($accounts) && count($accounts) > 0;
     }
 }
<?php

$genid = gen_id();
set_page_title($mailAccount->isNew() ? lang('add mail account') : lang('edit mail account'));
if (!$mailAccount->isNew() && $mailAccount->canDelete(logged_user())) {
    add_page_action(lang('delete mail account'), "javascript:og.promptDeleteAccount(" . $mailAccount->getId() . ");", 'ico-delete');
}
$logged_user_settings = MailAccountContacts::getByAccountAndContact($mailAccount, logged_user());
if (!$logged_user_settings instanceof MailAccountContact) {
    $logged_user_can_edit = $mailAccount->isNew();
    $user_settings = array();
} else {
    $logged_user_can_edit = $logged_user_settings->getCanEdit();
    $user_settings = array('is_default' => $logged_user_settings->getIsDefault(), 'sender_name' => $logged_user_settings->getSenderName(), 'signature' => $logged_user_settings->getSignature());
}
/* @var $mailAccount MailAccount */
if ($mailAccount->getContactId() == logged_user()->getId() || logged_user()->isAdministrator()) {
    // the creator of the account and superadmins can always edit it
    $logged_user_can_edit = true;
}
if (!$mailAccount->isNew()) {
    $mail_acc_id = $mailAccount->getId();
}
$loc = user_config_option('localization');
if (strlen($loc) > 2) {
    $loc = substr($loc, 0, 2);
}
?>

<form onsubmit="return og.setDescription();" style="height: 100%; background-color: white" class="internalForm"
	action="<?php 
 function countByAccount($account)
 {
     return MailAccountContacts::count(array('`account_id` = ?', $account->getId()));
 }
        ?>
</td>
		<td><?php 
        echo $account->getOwner() instanceof Contact ? $account->getOwner()->getObjectName() : lang("n/a");
        ?>
</td>
		<td><?php 
        echo $account->getServer();
        ?>
</td>
		<td><?php 
        echo $account->getSmtpServer();
        ?>
</td>
		<td><?php 
        echo MailAccountContacts::countByAccount($account);
        ?>
</td>
		<?php 
        $options = array();
        if ($account->canDelete(logged_user()) && $account->getContactId() == logged_user()->getId() || $account->canEdit(logged_user())) {
            $options[] = '<a class="internalLink" href="' . get_url('mail', 'edit_account', array('id' => $account->getId())) . '">' . lang('edit') . '</a>';
        }
        if ($account->canDelete(logged_user())) {
            $options[] = '<a class="internalLink" href="javascript:og.promptDeleteAccount(' . $account->getId() . ', true)">' . lang('delete') . '</a>';
        }
        // if
        if ($account->canDelete(logged_user()) && config_option("sent_mails_sync")) {
            $options[] = '<a class="internalLink" href="' . get_url('mail', 'sync_old_sent_mails', array('id' => $account->getId())) . '">' . lang('sync') . '</a>';
        }
        ?>
	/**
	 * Return manager instance
	 *
	 * @access protected
	 * @param void
	 * @return MailAccountContacts
	 */
	function manager() {
		if(!($this->manager instanceof MailAccountContacts)) $this->manager = MailAccountContacts::instance();
		return $this->manager;
	}
	function getFromName() {
		$user_settings = MailAccountContacts::getByAccountAndContact($this, logged_user());
		if ($user_settings instanceof MailAccountContact && $user_settings->getSenderName()) {
			return $user_settings->getSenderName();
		} else if ($this->getSenderName()) {
			return $this->getSenderName();
		} else if (logged_user() instanceof Contact) {
			return logged_user()->getObjectName();
		} else {
			return "";
		}
	}
 /**
  * 
  * 
  */
 function addToSharingTable()
 {
     // if classified or not belongs to an email
     $member_ids = array();
     $members = $this->getMembers();
     foreach ($members as $m) {
         $d = $m->getDimension();
         if ($d instanceof Dimension && $d->getIsManageable()) {
             $member_ids[] = $m->getId();
         }
     }
     if ($this->getMailId() == 0 || count($member_ids) > 0) {
         $revisions = $this->getRevisions();
         if (is_array($revisions)) {
             foreach ($revisions as $revision) {
                 $revision->addToSharingTable();
             }
         }
         parent::addToSharingTable();
     } else {
         // if not classified and belongs to an email
         $mail = MailContents::findById($this->getMailId());
         if ($mail instanceof MailContent) {
             DB::execute("DELETE FROM " . TABLE_PREFIX . "sharing_table WHERE object_id=" . $this->getId());
             $macs = MailAccountContacts::findAll(array('conditions' => array('`account_id` = ?', $mail->getAccountId())));
             foreach ($macs as $mac) {
                 $c = Contacts::findById($mac->getContactId());
                 if ($c instanceof Contact) {
                     $values = "(" . $c->getPermissionGroupId() . "," . $this->getId() . ")";
                     DB::execute("INSERT INTO " . TABLE_PREFIX . "sharing_table (group_id, object_id) VALUES {$values} ON DUPLICATE KEY UPDATE group_id=group_id;");
                 }
             }
         }
     }
 }
 function check_account_errors()
 {
     ajx_current("empty");
     $user = logged_user();
     if (!$user instanceof Contact) {
         return;
     }
     $acc_users = MailAccountContacts::instance()->getByContact(logged_user());
     foreach ($acc_users as $acc_user) {
         /* @var $acc_user MailAccountContact */
         if ($acc_user->getLastErrorState() == MailAccountContacts::MA_ERROR_UNREAD) {
             $account = $acc_user->getAccount();
             if (!$account instanceof MailAccount) {
                 continue;
             }
             flash_error($account->getLastErrorMsg());
             $acc_user->setLastErrorState(MailAccountContacts::MA_ERROR_READ);
             $acc_user->save();
         }
     }
 }
	/**
	 * 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, 'MailAccountContacts')) {
			return parent::paginate($arguments, $items_per_page, $current_page);
		} else {
			return MailAccountContacts::instance()->paginate($arguments, $items_per_page, $current_page);
			//$instance =& MailAccounts::instance();
			//return $instance->paginate($arguments, $items_per_page, $current_page);
		} // if
	} // paginate
 function list_objects()
 {
     /* get query parameters */
     $filesPerPage = config_option('files_per_page');
     $start = array_var($_GET, 'start') ? (int) array_var($_GET, 'start') : 0;
     $limit = array_var($_GET, 'limit') ? array_var($_GET, 'limit') : $filesPerPage;
     $order = array_var($_GET, 'sort');
     $id_no_select = array_var($_GET, 'id_no_select', "undefined");
     $ignore_context = (bool) array_var($_GET, 'ignore_context');
     $member_ids = json_decode(array_var($_GET, 'member_ids'));
     $extra_member_ids = json_decode(array_var($_GET, 'extra_member_ids'));
     $orderdir = array_var($_GET, 'dir');
     if (!in_array(strtoupper($orderdir), array('ASC', 'DESC'))) {
         $orderdir = 'ASC';
     }
     if ($order == "dateUpdated") {
         $order = "updated_on";
     } elseif ($order == "dateArchived") {
         $order = "archived_on";
     } elseif ($order == "dateDeleted") {
         $order = "trashed_on";
     } elseif ($order == "name") {
         $order = "name";
     } else {
         $order = "";
         $orderdir = "";
     }
     $extra_list_params = array_var($_GET, 'extra_list_params');
     $extra_list_params = json_decode($extra_list_params);
     $page = (int) ($start / $limit) + 1;
     $hide_private = !logged_user()->isMemberOfOwnerCompany();
     $typeCSV = array_var($_GET, 'type');
     $types = null;
     if ($typeCSV) {
         $types = explode(",", $typeCSV);
     }
     $name_filter = mysql_real_escape_string(array_var($_GET, 'name'));
     $linked_obj_filter = array_var($_GET, 'linkedobject');
     $object_ids_filter = '';
     $show_all_linked_objects = false;
     if (!is_null($linked_obj_filter)) {
         $show_all_linked_objects = true;
         $linkedObject = Objects::findObject($linked_obj_filter);
         $objs = $linkedObject->getLinkedObjects();
         foreach ($objs as $obj) {
             $object_ids_filter .= ($object_ids_filter == '' ? '' : ',') . $obj->getId();
         }
     }
     $filters = array();
     if (!is_null($types)) {
         $filters['types'] = $types;
     }
     if (!is_null($name_filter)) {
         $filters['name'] = $name_filter;
     }
     if ($object_ids_filter != '') {
         $filters['object_ids'] = $object_ids_filter;
     }
     $user = array_var($_GET, 'user');
     $trashed = array_var($_GET, 'trashed', false);
     $archived = array_var($_GET, 'archived', false);
     /* if there's an action to execute, do so */
     if (!$show_all_linked_objects) {
         $this->processListActions();
     }
     $filterName = array_var($_GET, 'name');
     $template_object_names = "";
     $template_extra_condition = "true";
     $template_objects = false;
     if (in_array("template_task", array_var($filters, 'types', array())) || in_array("template_milestone", array_var($filters, 'types', array()))) {
         $template_id = 0;
         $template_objects = true;
         if (isset($extra_list_params->template_id)) {
             $template_id = $extra_list_params->template_id;
         }
         $tmpl_task = TemplateTasks::findById(intval($id_no_select));
         if ($tmpl_task instanceof TemplateTask) {
             $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . $tmpl_task->getTemplateId() . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )";
         } else {
             $template_extra_condition = "o.id IN (SELECT object_id from " . TABLE_PREFIX . "template_tasks WHERE `template_id`=" . intval($template_id) . " OR `template_id`=0 AND `session_id`=" . logged_user()->getId() . " )";
         }
     } else {
         $template_object_names = "AND name <> 'template_task' AND name <> 'template_milestone'";
     }
     $result = null;
     $context = active_context();
     $obj_type_types = array('content_object', 'dimension_object');
     if (array_var($_GET, 'include_comments')) {
         $obj_type_types[] = 'comment';
     }
     $type_condition = "";
     if ($types) {
         $type_condition = " AND name IN ('" . implode("','", $types) . "')";
     }
     $extra_conditions = array();
     // user filter
     if (in_array("contact", array_var($filters, 'types', array())) && isset($extra_list_params->is_user)) {
         $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "contacts c on c.object_id=o.id";
         $extra_conditions[] = "\r\n\t\t\t\tc.user_type " . ($extra_list_params->is_user == 1 ? ">" : "=") . " 0";
         if (isset($extra_list_params->has_permissions) && $extra_list_params->has_permissions > 0) {
             $mem_id = $extra_list_params->has_permissions;
             $extra_conditions[] = " EXISTS (\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.permission_group_id IN (SELECT x.permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups x WHERE x.contact_id=o.id)\r\n\t\t\t\t\tAND cmp.member_id='{$mem_id}' \r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT tp.object_type_id FROM " . TABLE_PREFIX . "tab_panels tp WHERE tp.enabled=0)\r\n\t\t\t\t\tAND cmp.object_type_id NOT IN (SELECT oott.id FROM " . TABLE_PREFIX . "object_types oott WHERE oott.name IN ('comment','template'))\r\n\t\t\t\t\tAND cmp.object_type_id IN (SELECT oott2.id FROM " . TABLE_PREFIX . "object_types oott2 WHERE oott2.type IN ('content_object','dimension_object'))\r\n\t\t\t\t)";
         }
     }
     // Object type filter - exclude template types (if not template picker), filter by required type names (if specified) and match value with objects table
     $extra_object_type_conditions = "\r\n\t\t\tAND name <> 'file revision' {$template_object_names} {$type_condition} AND o.object_type_id = ot.id";
     $extra_conditions[] = ObjectTypes::getListableObjectsSqlCondition($extra_object_type_conditions);
     // --
     // logged user permission group ids
     $logged_user_pg_ids = implode(',', logged_user()->getPermissionGroupIds());
     // used in template object picker
     $extra_conditions[] = $template_extra_condition;
     // when filtering by name
     if ($name_filter) {
         $extra_conditions[] = "\r\n\t\t\t\tname LIKE '%{$name_filter}%'";
     }
     // when excluding some object in particular
     if ($id_no_select != "undefined") {
         $extra_conditions[] = "\r\n\t\t\t\tid <> '{$id_no_select}'";
     }
     // when filtering by some group of objects, for example in the linked objects view
     if ($object_ids_filter != "") {
         $extra_conditions[] = "\r\n\t\t\t\tid in ({$object_ids_filter})";
     }
     $joins[] = "\r\n\t\t\tLEFT JOIN " . TABLE_PREFIX . "project_tasks pt on pt.object_id=o.id";
     if (!SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
         // exclude other users' tasks if cannot see them
         $extra_conditions[] = "\r\n\t\t\t\t( pt.assigned_to_contact_id IS NULL OR pt.assigned_to_contact_id= " . logged_user()->getId() . ")";
     }
     // don't include tasks which have is_template=1
     $extra_conditions[] = "\r\n\t\t\t( pt.is_template IS NULL OR pt.is_template=0)";
     // trashed conditions
     $extra_conditions[] = "\r\n\t\t\to.trashed_on" . ($trashed ? "<>" : "=") . "0";
     // archived conditions
     $extra_conditions[] = "\r\n\t\t\to.archived_on" . ($archived ? "<>" : "=") . "0";
     // don't include unclassified mails from other accounts
     if (Plugins::instance()->isActivePlugin('mail')) {
         $accounts_of_loggued_user = MailAccountContacts::getByContact(logged_user());
         $account_ids = array(0);
         foreach ($accounts_of_loggued_user as $acc) {
             $account_ids[] = $acc->getAccountId();
         }
         $joins[] = "\r\n\t\t\t\tLEFT JOIN " . TABLE_PREFIX . "mail_contents mc on mc.object_id=o.id\r\n\t\t\t";
         $extra_conditions[] = "\r\n\t\t\t\tIF( mc.account_id IS NULL, true, mc.account_id IN (" . implode(',', $account_ids) . ") OR EXISTS (\r\n\t\t\t\t\tSELECT om1.object_id FROM " . TABLE_PREFIX . "object_members om1 \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "members m1 ON m1.id=om1.member_id \r\n\t\t\t\t\t\tINNER JOIN " . TABLE_PREFIX . "dimensions d1 ON d1.id=m1.dimension_id \r\n\t\t\t\t\tWHERE om1.object_id=o.id AND d1.is_manageable=1)\r\n\t\t\t\t)";
     }
     // don't show attached files of emails that cannot be viewed
     if (logged_user()->isAdministrator() && Plugins::instance()->isActivePlugin('mail')) {
         $joins[] = "LEFT JOIN " . TABLE_PREFIX . "project_files pf on pf.object_id=o.id";
         $extra_conditions[] = "IF(pf.mail_id IS NULL OR pf.mail_id = 0, true, \r\n\t\t\t\tpf.mail_id IN (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE pf.mail_id = sh.object_id AND sh.group_id  IN ({$logged_user_pg_ids})))";
     }
     $only_count_result = array_var($_GET, 'only_result', false);
     $count_results = array_var($_GET, 'count_results', false);
     // Members filter
     $sql_members = "";
     if (!$ignore_context && !$member_ids) {
         $members = active_context_members(false);
         // Context Members Ids
     } elseif (count($member_ids)) {
         $members = $member_ids;
     } else {
         // get members from context
         if (!$ignore_context) {
             $members = active_context_members(false);
         }
     }
     if (is_array($extra_member_ids)) {
         if (isset($members)) {
             $members = array_merge($members, $extra_member_ids);
         } else {
             $members = $extra_member_ids;
         }
     }
     if (isset($members) && is_array($members) && count($members) > 0 && !(isset($template_id) && $template_id > 0)) {
         $sql_members = "\r\n\t\t\t\tAND (EXISTS (SELECT om.object_id\r\n\t\t\t\t\tFROM  " . TABLE_PREFIX . "object_members om\r\n\t\t\t\t\tWHERE om.member_id IN (" . implode(',', $members) . ") AND o.id = om.object_id \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\t))\r\n\t\t\t";
     }
     // --
     // Permissions filter
     if (isset($template_id) && $template_id > 0) {
         // editing template items do not check permissions
         $sql_permissions = "";
     } else {
         $sql_permissions = "\r\n\t\t\t\tAND EXISTS (SELECT sh.object_id FROM " . TABLE_PREFIX . "sharing_table sh WHERE sh.object_id=o.id AND sh.group_id IN ({$logged_user_pg_ids}))\r\n\t\t\t";
     }
     // Main select
     $sql_select = "SELECT * FROM " . TABLE_PREFIX . "objects o ";
     // Joins
     $sql_joins = implode(" ", $joins);
     // Where
     $sql_where = "\r\n\t\t\tWHERE " . implode(" AND ", $extra_conditions) . $sql_permissions . $sql_members;
     // Order
     $sql_order = "";
     if ($order) {
         $sql_order = "\r\n\t\t\t\tORDER BY {$order} {$orderdir}\r\n\t\t\t";
     }
     // Limit
     $sql_limit = "";
     if ($start >= 0 && $limit > 0) {
         $sql_limit = " LIMIT {$start}, {$limit}";
     }
     // Full SQL
     $sql = "{$sql_select} {$sql_joins} {$sql_where} {$sql_order} {$sql_limit}";
     // Execute query
     if (!$only_count_result) {
         $rows = DB::executeAll($sql);
     }
     // get total items
     if ($count_results) {
         $sql_count = "SELECT count(o.id) as total_items FROM " . TABLE_PREFIX . "objects o {$sql_joins} {$sql_where}";
         $rows_count = DB::executeAll($sql_count);
         $total_items = $rows_count[0]['total_items'];
     } else {
         if (isset($rows) && is_array($rows)) {
             $total_items = count($rows) < $filesPerPage ? count($rows) : 1000000;
         } else {
             $total_items = 0;
         }
     }
     // prepare response object
     $info = array();
     // get objects
     if (isset($rows) && is_array($rows)) {
         foreach ($rows as $row) {
             $instance = Objects::findObject($row['id']);
             if (!$instance instanceof ContentDataObject) {
                 continue;
             }
             $info_elem = $instance->getObject()->getArrayInfo();
             $info_elem['url'] = $instance->getViewUrl();
             $info_elem['isRead'] = $instance->getIsRead(logged_user()->getId());
             $info_elem['manager'] = get_class($instance->manager());
             $info_elem['memPath'] = json_encode($instance->getMembersIdsToDisplayPath());
             if ($instance instanceof Contact) {
                 if ($instance->isCompany()) {
                     $info_elem['icon'] = 'ico-company';
                     $info_elem['type'] = 'company';
                 } else {
                     $info_elem['memPath'] = json_encode($instance->getUserType() ? "" : $instance->getMembersIdsToDisplayPath());
                 }
             } else {
                 if ($instance instanceof ProjectFile) {
                     $info_elem['mimeType'] = $instance->getTypeString();
                 }
             }
             $info[] = $info_elem;
         }
     }
     $listing = array("totalCount" => $total_items, "start" => $start, "objects" => $info);
     ajx_extra_data($listing);
     tpl_assign("listing", $listing);
     if (isset($reload) && $reload) {
         ajx_current("reload");
     } else {
         ajx_current("empty");
     }
 }
 /**
  * Returns a list of emails according to the requested parameters
  *
  * @param string $tag
  * @param array $attributes
  * @param Project $project
  * @return array
  */
 function getEmails($account_id = null, $state = null, $read_filter = "", $classif_filter = "", $context = null, $start = null, $limit = null, $order_by = 'received_date', $dir = 'ASC', $archived = false)
 {
     $mailTablePrefix = "e";
     $accountConditions = "";
     // Check for accounts
     $accountConditions = '';
     if (isset($account_id) && $account_id > 0) {
         //Single account
         $accountConditions = " AND {$mailTablePrefix}.account_id = " . DB::escape($account_id);
         /*		} else {
         			// show emails from other accounts
         			$macs = MailAccountContacts::instance()->getByContact(logged_user());
         			$acc_ids = array();
         			foreach ($macs as $mac) $acc_ids[] = $mac->getAccountId();
         			if (count($acc_ids) == 0) $acc_ids[] = 0;
         			$accountConditions = " AND $mailTablePrefix.account_id IN (" . implode(",", $acc_ids) . ")";
         */
     }
     // Check for unclassified emails
     $classified = '';
     if ($classif_filter != '' && $classif_filter != 'all') {
         if ($classif_filter == 'unclassified') {
             $classified = "AND NOT ";
         } else {
             $classified = "AND ";
         }
         $classified .= "o.id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members)";
     } else {
         if (isset($account_id) && $account_id > 0) {
             $acc_cond = "IN ({$account_id})";
         } else {
             $macs = MailAccountContacts::instance()->getByContact(logged_user());
             $acc_ids = array(0);
             foreach ($macs as $mac) {
                 $acc_ids[] = $mac->getAccountId();
             }
             $acc_cond = "IN (" . implode(",", $acc_ids) . ")";
         }
         $classified = "AND (e.account_id {$acc_cond} OR o.id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members))";
     }
     // Check for draft, junk, etc. emails
     if ($state == "draft") {
         $stateConditions = " {$mailTablePrefix}.state = '2'";
     } else {
         if ($state == "sent") {
             $stateConditions = " {$mailTablePrefix}.state IN ('1','3','5')";
         } else {
             if ($state == "received") {
                 $stateConditions = " {$mailTablePrefix}.state IN ('0','5')";
             } else {
                 if ($state == "junk") {
                     $stateConditions = " {$mailTablePrefix}.state = '4'";
                 } else {
                     if ($state == "outbox") {
                         $stateConditions = " {$mailTablePrefix}.state >= 200";
                     } else {
                         $stateConditions = "";
                     }
                 }
             }
         }
     }
     // Check read emails
     if ($read_filter != "" && $read_filter != "all") {
         if ($read_filter == "unread") {
             $read = "AND NOT ";
             $subread = "AND NOT mc.";
         } else {
             $read = "AND ";
             $subread = "AND mc.";
         }
         $read2 = "id IN (SELECT rel_object_id FROM " . TABLE_PREFIX . "read_objects t WHERE contact_id = " . logged_user()->getId() . "  AND t.is_read = '1')";
         $read .= $read2;
         $subread .= $read2;
     } else {
         $read = "";
         $subread = "";
     }
     // Conversations not allowed yet
     //if (user_config_option('show_emails_as_conversations')) {
     //	$state_conv_cond_1 = $state != 'received' ? " $stateConditions AND " : " m.state <> '2' AND ";
     //	$state_conv_cond_2 = $state != 'received' ? " AND (mc.state = '1' OR mc.state = '3' OR mc.state = '5') " : " AND mc.state <> '2' ";
     //	$archived_by_id = $archived ? "AND o.archived_by_id != 0" : "AND o.archived_by_id = 0";
     //	$trashed_by_id = "AND o.trashed_by_id = 0";
     //	$conversation_cond = "AND IF(m.conversation_id = 0, $stateConditions, $state_conv_cond_1 NOT EXISTS (SELECT * FROM ".TABLE_PREFIX."mail_contents mc WHERE m.conversation_id = mc.conversation_id AND m.account_id = mc.account_id AND m.received_date < mc.received_date $archived_by_id AND mc.is_deleted = 0 $trashed_by_id $subread $state_conv_cond_2))";
     //	$box_cond = "AND IF(EXISTS(SELECT * FROM ".TABLE_PREFIX."mail_contents mc WHERE m.conversation_id = mc.conversation_id AND m.object_id <> o.id AND m.account_id = mc.account_id $archived_by_id AND mc.is_deleted = 0 $trashed_by_id AND $stateConditions), TRUE, $stateConditions)";
     //} else {
     $conversation_cond = "";
     $box_cond = "AND {$stateConditions}";
     //}
     /*return self::findByContext(array('limit' => $limit, 'offset' => $start, 'order' => "$order_by $dir",
     		'extra_conditions' => "$accountConditions $classified $read $conversation_cond $box_cond")); */
     return self::instance()->listing(array('limit' => $limit, 'start' => $start, 'order' => $order_by, 'order_dir' => $dir, 'extra_conditions' => "{$accountConditions} {$classified} {$read} {$conversation_cond} {$box_cond}", 'count_results' => false));
 }