2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42 * Reserved. Contributor(s): ______________________________________..
43 *********************************************************************************/
45 require_once("include/ytree/Tree.php");
46 require_once("include/ytree/ExtNode.php");
49 * Polymorphic buckets - place any item in a folder
57 var $has_child = 0; // flag node has child
60 var $dynamic_query = '';
70 var $new_with_id = false;
73 var $core = "SELECT f.id, f.name, f.has_child, f.is_group, f.is_dynamic, f.dynamic_query, f.folder_type, f.created_by, i.deleted FROM folders f left join inbound_email i on f.id = i.groupfolder_id ";
74 var $coreSubscribed = "SELECT f.id, f.name, f.has_child, f.is_group, f.is_dynamic, f.dynamic_query, f.folder_type, f.created_by, i.deleted FROM folders f LEFT JOIN folders_subscriptions fs ON f.id = fs.folder_id LEFT JOIN inbound_email i on i.groupfolder_id = f.id ";
75 var $coreWhere = "WHERE f.deleted = 0 ";
76 var $coreWhereSubscribed = "WHERE f.deleted = 0 AND fs.assigned_user_id = ";
77 var $coreOrderBy = " ORDER BY f.is_dynamic, f.is_group, f.name ASC ";
79 var $hrSortLocal = array(
81 'status' => 'reply_to_status',
82 'from' => 'emails_text.from_addr',
84 'date' => 'date_sent',
85 'AssignedTo' => 'assigned_user_id',
86 'flagged' => 'flagged'
88 var $defaultSort = 'date';
89 var $defaultDirection = "DESC";
97 function SugarFolder() {
98 $this->db = DBManagerFactory::getInstance();
101 function deleteEmailFromAllFolder($id) {
102 $q = "delete from folders_rel where polymorphic_module = 'Emails' AND polymorphic_id = '{$id}' ";
103 $r = $this->db->query($q);
106 function deleteEmailFromFolder($id) {
107 $q = "delete from folders_rel where polymorphic_module = 'Emails' AND polymorphic_id = '{$id}' AND folder_id = '{$this->id}'";
108 $r = $this->db->query($q);
111 function checkEmailExistForFolder($id) {
112 $q = "SELECT COUNT(*) c from folders_rel where polymorphic_module = 'Emails' AND polymorphic_id = '{$id}' AND folder_id = '{$this->id}'";
113 $r = $this->db->query($q);
114 $a = $this->db->fetchByAssoc($r);
122 * Moves beans from one folder to another folder
123 * @param string fromFolder GUID of source folder
124 * @param string toFolder GUID of destination folder
125 * @param string beanId GUID of SugarBean being moved
127 function move($fromFolder, $toFolder, $beanId) {
128 $q = "UPDATE folders_rel SET folder_id = '{$toFolder}' WHERE folder_id = '{$fromFolder}' AND polymorphic_id = '{$beanId}' AND deleted = 0";
129 $r = $this->db->query($q);
133 * Copies one bean from one folder to another
135 function copyBean($fromFolder, $toFolder, $beanId, $module) {
136 $q = "INSERT INTO folders_rel (id, folder_id, polymorphic_module, polymorphic_id, deleted)
137 VALUES('{$guid}', '{$toFolder}', '{$module}', '{$beanId}', 0)";
138 $r = $this->db->query($q);
142 * Creates a new group Folder from the passed fields
143 * @param array fields
145 function setFolder($fields) {
147 global $current_user;
148 if(empty($fields['groupFoldersUser'])) {
149 $fields['groupFoldersUser'] = $current_user->id;
152 $this->name = $fields['name'];
153 $this->parent_folder = $fields['parent_folder'];
154 $this->has_child = 0;
156 $this->assign_to_id = $fields['groupFoldersUser'];
162 * Returns GUIDs of folders that the user in focus is subscribed to
163 * @param object user User object in focus
166 function getSubscriptions($user) {
168 global $current_user;
169 $user = $current_user;
172 $q = "SELECT folder_id FROM folders_subscriptions WHERE assigned_user_id = '{$user->id}'";
173 $r = $this->db->query($q);
175 while($a = $this->db->fetchByAssoc($r)) {
176 $ret[] = $a['folder_id'];
182 * Sets a user's preferences for subscribe folders (Sugar only)
183 * @param array subs Array of IDs for subscribed folders
185 function setSubscriptions($subs) {
186 global $current_user;
188 if(empty($current_user->id)) {
189 $GLOBALS['log']->fatal("*** FOLDERS: tried to update folder subscriptions for a user with no ID");
193 $cleanSubscriptions = array();
195 // ensure parent folders are selected, regardless.
196 foreach($subs as $id) {
199 $cleanSubscriptions[] = $id;
200 $qChk = "SELECT parent_folder FROM folders WHERE id = '{$id}'";
201 $rChk = $this->db->query($qChk);
202 $aChk = $this->db->fetchByAssoc($rChk);
204 if(!empty($aChk['parent_folder'])) {
205 $cleanSubscriptions = $this->getParentIDRecursive($aChk['parent_folder'], $cleanSubscriptions);
210 $this->clearSubscriptions();
212 foreach($cleanSubscriptions as $id) {
213 $this->insertFolderSubscription($id, $current_user->id);
218 * Given a folder id and user id, create a folder subscription entry.
220 * @param String $folderId
221 * @param String $userID
222 * @return String The id of the newly created folder subscription.
224 function insertFolderSubscription($folderId, $userID)
226 $guid = create_guid();
227 $query = "INSERT INTO folders_subscriptions (id, folder_id, assigned_user_id) VALUES ('{$guid}', '{$folderId}', '{$userID}')";
228 $r = $this->db->query($query);
232 * Recursively finds parent node until it hits root
233 * @param string id Starting id to follow up
234 * @param array ret collected ids
235 * @return array of IDs
237 function getParentIDRecursive($id, $ret=array()) {
238 $q = "SELECT * FROM folders WHERE id = '{$id}' AND deleted = 0";
239 $r = $this->db->query($q);
240 $a = $this->db->fetchByAssoc($r);
242 if(!in_array($id, $ret)) {
246 if($a['parent_folder'] != '') {
247 $qChk = "SELECT parent_folder FROM folders WHERE id = '{$id}'";
248 $rChk = $this->db->query($qChk);
249 $aChk = $this->db->fetchByAssoc($rChk);
251 if(!empty($aChk['parent_folder'])) {
252 $ret = $this->getParentIDRecursive($aChk['parent_folder'], $ret);
260 * Deletes subscriptions to folders in preparation for reset
262 function clearSubscriptions() {
263 global $current_user;
265 if(!empty($current_user->id)) {
266 $q = "DELETE FROM folders_subscriptions WHERE assigned_user_id = '{$current_user->id}'";
267 $r = $this->db->query($q);
273 * Deletes all subscriptions for a particular folder id
277 function clearSubscriptionsForFolder($folderID)
279 $query = "DELETE FROM folders_subscriptions WHERE folder_id = '$folderID'";
280 $r = $this->db->query($query);
283 protected function generateArchiveFolderQuery()
285 global $current_user;
287 SELECT emails.id , emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status, emails_text.from_addr, emails_text.to_addrs, 'Emails' polymorphic_module FROM emails
288 JOIN emails_text on emails.id = emails_text.email_id
289 WHERE emails.deleted=0 AND emails.type NOT IN ('out', 'draft') AND emails.status NOT IN ('sent', 'draft') AND emails.id IN (
290 SELECT eear.email_id FROM emails_email_addr_rel eear
291 JOIN email_addr_bean_rel eabr ON eabr.email_address_id=eear.email_address_id AND eabr.bean_id = '{$current_user->id}' AND eabr.bean_module = 'Users'
298 function generateSugarsDynamicFolderQuery()
300 global $current_user;
301 $type = $this->folder_type;
302 if($type == 'archived') {
303 return $this->generateArchiveFolderQuery();
306 if($type == "sent") {
309 if($type == 'inbound') {
310 $ret = " AND emails.status NOT IN ('sent', 'archived', 'draft') AND emails.type NOT IN ('out', 'archived', 'draft')";
312 $ret = " AND emails.status NOT IN ('archived') AND emails.type NOT IN ('archived')";
314 $q = "SELECT emails.id , emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status, emails_text.from_addr, emails_text.to_addrs, 'Emails' polymorphic_module FROM emails" .
315 " JOIN emails_text on emails.id = emails_text.email_id
316 WHERE (type = '{$type}' OR status = '{$status}') AND assigned_user_id = '{$current_user->id}' AND emails.deleted=0";
322 * returns array of items for listView display in yui-ext Grid
324 function getListItemsForEmailXML($folderId, $page = 1, $pageSize = 10, $sort = '', $direction='') {
325 require_once('include/TimeDate.php');
327 global $current_user;
329 global $sugar_config;
332 $this->retrieve($folderId);
333 $start = ($page - 1) * $pageSize;
335 $sort = (empty($sort)) ? $this->defaultSort : $sort;
336 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
337 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
339 if($this->is_dynamic) {
340 $r = $this->db->limitQuery(from_html($this->generateSugarsDynamicFolderQuery() . $order), $start, $pageSize);
342 // get items and iterate through them
343 $q = "SELECT emails.id , emails.name, emails.date_sent, emails.status, emails.type, emails.flagged, emails.reply_to_status, emails_text.from_addr, emails_text.to_addrs, 'Emails' polymorphic_module FROM emails JOIN folders_rel ON emails.id = folders_rel.polymorphic_id" .
344 " JOIN emails_text on emails.id = emails_text.email_id
345 WHERE folders_rel.folder_id = '{$folderId}' AND folders_rel.deleted = 0 AND emails.deleted = 0";
346 if ($this->is_group) {
347 $q = $q . " AND (emails.assigned_user_id is null or emails.assigned_user_id = '')";
349 $r = $this->db->limitQuery($q . $order, $start, $pageSize);
354 $email = new Email(); //Needed for email specific functions.
356 while($a = $this->db->fetchByAssoc($r)) {
359 $temp['flagged'] = (is_null($a['flagged']) || $a['flagged'] == '0') ? '' : 1;
360 $temp['status'] = (is_null($a['reply_to_status']) || $a['reply_to_status'] == '0') ? '' : 1;
361 $temp['from'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['from_addr']);
362 $temp['subject'] = $a['name'];
363 $temp['date'] = $timedate->to_display_date_time($this->db->fromConvert($a['date_sent'], 'datetime'));
364 $temp['uid'] = $a['id'];
365 $temp['mbox'] = 'sugar::'.$a['polymorphic_module'];
366 $temp['ieId'] = $folderId;
367 $temp['site_url'] = $sugar_config['site_url'];
368 $temp['seen'] = ($a['status'] == 'unread') ? 0 : 1;
369 $temp['type'] = $a['type'];
370 $temp['hasAttach'] = $email->doesImportedEmailHaveAttachment($a['id']);
371 $temp['to_addrs'] = preg_replace('/[\x00-\x08\x0B-\x1F]/', '', $a['to_addrs']);
377 $metadata['mbox'] = $app_strings['LBL_EMAIL_SUGAR_FOLDER'].': '.$this->name;
378 $metadata['ieId'] = $folderId;
379 $metadata['name'] = $this->name;
380 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
381 $metadata['out'] = $return;
386 function getCountItems ( $folderId ) {
387 global $current_user ;
389 global $sugar_config ;
390 global $app_strings ;
392 $this->retrieve ( $folderId ) ;
393 if ($this->is_dynamic) {
394 $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is'; // ignores the case
395 $replacement = 'SELECT count(*) c FROM ';
396 $modified_select_query = preg_replace($pattern, $replacement, $this->generateSugarsDynamicFolderQuery(), 1);
397 $r = $this->db->query ( from_html ( $modified_select_query )) ;
399 // get items and iterate through them
400 $q = "SELECT count(*) c FROM folders_rel JOIN emails ON emails.id = folders_rel.polymorphic_id" .
401 " WHERE folder_id = '{$folderId}' AND folders_rel.deleted = 0 AND emails.deleted = 0" ;
402 if ($this->is_group) {
403 $q .= " AND (emails.assigned_user_id is null or emails.assigned_user_id = '')";
405 $r = $this->db->query ( $q ) ;
408 $a = $this->db->fetchByAssoc($r);
412 function getCountUnread ( $folderId ) {
413 global $current_user ;
415 global $sugar_config ;
416 global $app_strings ;
418 $this->retrieve ( $folderId ) ;
419 if ($this->is_dynamic) {
420 $pattern = '/SELECT(.*?)(\s){1}FROM(\s){1}/is'; // ignores the case
421 $replacement = 'SELECT count(*) c FROM ';
422 $modified_select_query = preg_replace($pattern, $replacement, $this->generateSugarsDynamicFolderQuery(), 1);
423 $r = $this->db->query (from_html($modified_select_query) . " AND emails.status = 'unread'") ;
425 // get items and iterate through them
426 $q = "SELECT count(*) c FROM folders_rel fr JOIN emails on fr.folder_id = '{$folderId}' AND fr.deleted = 0 " .
427 "AND fr.polymorphic_id = emails.id AND emails.status = 'unread' AND emails.deleted = 0" ;
428 if ($this->is_group) {
429 $q .= " AND (emails.assigned_user_id is null or emails.assigned_user_id = '')";
431 $r = $this->db->query ( $q ) ;
434 $a = $this->db->fetchByAssoc($r);
440 * Convenience method, pass a SugarBean and User to this to add anything to a given folder
442 function addBean($bean, $user=null) {
443 if(empty($bean->id) || empty($bean->module_dir)) {
444 $GLOBALS['log']->fatal("*** FOLDERS: addBean() got empty bean - not saving");
446 } elseif(empty($this->id)) {
447 $GLOBALS['log']->fatal("*** FOLDERS: addBean() is trying to save to a non-saved or non-existent folder");
451 global $current_user;
453 $user = $current_user;
456 $guid = create_guid();
458 $q = "INSERT INTO folders_rel (id, folder_id, polymorphic_module, polymorphic_id, deleted)
459 VALUES('{$guid}', '{$this->id}', '{$bean->module_dir}', '{$bean->id}', 0)";
460 $r = $this->db->query($q);
465 * Builds up a metacollection of user/group folders to be passed to processor methods
466 * @param object User object, defaults to $current_user
467 * @return array Array of abstract folder objects
469 function retrieveFoldersForProcessing($user, $subscribed=true) {
470 global $sugar_config;
471 global $current_language, $current_user;
473 $emails_mod_strings = return_module_language($current_language, "Emails");
474 $myEmailTypeString = 'inbound';
475 $myDraftsTypeString = 'draft';
476 $mySentEmailTypeString = 'sent';
479 global $current_user;
480 $user = $current_user;
483 $teamSecurityClause = '';
487 $rootWhere .= "AND (f.parent_folder IS NULL OR f.parent_folder = '')";
490 $q = $this->coreSubscribed.$teamSecurityClause.$this->coreWhereSubscribed."'{$user->id}' ".$rootWhere.$this->coreOrderBy;
492 $q = $this->core.$teamSecurityClause.$this->coreWhere.$rootWhere.$this->coreOrderBy;
494 $r = $this->db->query($q);
498 while($a = $this->db->fetchByAssoc($r)) {
499 if ((($a['folder_type'] == $myEmailTypeString) ||
500 ($a['folder_type'] == $myDraftsTypeString) ||
501 ($a['folder_type'] == $mySentEmailTypeString)) &&
502 ($a['created_by'] != $current_user->id)) {
506 if (!isset($found[$a['id']])) {
507 $found[$a['id']] = true;
514 * Preps object array for async call from user's Settings->Folders
516 function getGroupFoldersForSettings($focusUser=null) {
521 $folders = $this->retrieveFoldersForProcessing($focusUser, false);
522 $subscriptions = $this->getSubscriptions($focusUser);
524 foreach($folders as $a) {
525 $a['selected'] = (in_array($a['id'], $subscriptions)) ? true : false;
526 $a['origName'] = $a['name'];
528 if($a['is_group'] == 1)
529 if ($a['deleted'] != 1)
536 * Preps object array for async call from user's Settings->Folders
538 function getFoldersForSettings($focusUser=null) {
543 $user[] = array('id' => '', 'name' => $app_strings['LBL_NONE'], 'has_child' => 0, 'is_group' => 0, 'selected' => false);
544 $grp[] = array('id' => '', 'name' => $app_strings['LBL_NONE'], 'has_child' => 0, 'is_group' => 1, 'selected' => false, 'origName' => "");
546 $folders = $this->retrieveFoldersForProcessing($focusUser, false);
547 $subscriptions = $this->getSubscriptions($focusUser);
549 foreach($folders as $a) {
550 $a['selected'] = (in_array($a['id'], $subscriptions)) ? true : false;
551 $a['origName'] = $a['name'];
552 if( isset($a['dynamic_query']) )
553 unset($a['dynamic_query']);
554 if($a['is_group'] == 1) {
560 if($a['has_child'] == 1) {
561 $qGetChildren = $this->core.$this->coreWhere."AND parent_folder = '{$a['id']}'";
562 $rGetChildren = $this->db->query($qGetChildren);
564 while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
567 $grp = $this->getFoldersChildForSettings($aGetChildren, $grp, $subscriptions);
570 $user = $this->getFoldersChildForSettings($aGetChildren, $user, $subscriptions);
577 'userFolders' => $user,
578 'groupFolders' => $grp,
583 function getFoldersChildForSettings($a, $collection, $subscriptions) {
584 $a['selected'] = (in_array($a['id'], $subscriptions)) ? true : false;
585 $a['origName'] = $a['name'];
587 if(isset($a['dynamic_query']))
589 unset($a['dynamic_query']);
592 for($i=0; $i<$this->_depth; $i++)
594 $a['name'] = ".".$a['name'];
599 if($a['has_child'] == 1) {
601 $qGetChildren = $this->core.$this->coreWhere."AND parent_folder = '{$a['id']}'";
602 $rGetChildren = $this->db->query($qGetChildren);
603 while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
604 $collection = $this->getFoldersChildForSettings($aGetChildren, $collection, $subscriptions);
612 * Returns the number of "new" items (based on passed criteria)
613 * @param string id ID of folder
614 * @param array criteria
616 * array('field' => 'status',
617 * 'value' => 'unread');
621 function getCountNewItems($id, $criteria, $folder) {
622 global $current_user;
624 $sugarFolder = new SugarFolder();
625 return $sugarFolder->getCountUnread($id);
629 * Collects, sorts, and builds tree of user's folders
630 * @param objec $rootNode Reference to tree root node
631 * @param array $folderStates User pref folder open/closed states
632 * @param object $user Optional User in focus, default current_user
635 function getUserFolders(&$rootNode, $folderStates, $user=null, $forRefresh=false) {
637 global $current_user;
638 $user = $current_user;
641 $folders = $this->retrieveFoldersForProcessing($user, true);
642 $subscriptions = $this->getSubscriptions($user);
644 $refresh = ($forRefresh) ? array() : null;
646 if(!is_array($folderStates)) {
647 $folderStates = array();
650 foreach($folders as $a) {
651 if ($a['deleted'] == 1)
653 $label = ($a['name'] == 'My Email' ? $mod_strings['LNK_MY_INBOX'] : $a['name']);
655 $unseen = $this->getCountNewItems($a['id'], array('field' => 'status', 'value' => 'unread'), $a);
657 $folderNode = new ExtNode($a['id'], $label);
658 $folderNode->dynamicloadfunction = '';
659 $folderNode->expanded = false;
661 if(array_key_exists('Home::'.$a['id'], $folderStates)) {
662 if($folderStates['Home::'.$a['id']] == 'open') {
663 $folderNode->expanded = true;
666 $nodePath = "Home::".$folderNode->_properties['id'];
668 $folderNode->dynamic_load = true;
669 //$folderNode->set_property('click', " SUGAR.email2.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '{$a['id']}', 'false');");
670 $folderNode->set_property('ieId', 'folder');
671 $folderNode->set_property('is_group', ($a['is_group'] == 1) ? 'true' : 'false');
672 $folderNode->set_property('is_dynamic', ($a['is_dynamic'] == 1) ? 'true' : 'false');
673 $folderNode->set_property('mbox', $folderNode->_properties['id']);
674 $folderNode->set_property('unseen', $unseen);
675 $folderNode->set_property('id', $a['id']);
676 $folderNode->set_property('folder_type', $a['folder_type']);
677 $folderNode->set_property('children', array());
679 if(in_array($a['id'], $subscriptions) && $a['has_child'] == 1) {
680 $qGetChildren = $this->core.$this->coreWhere."AND parent_folder = '{$a['id']}'";
681 $rGetChildren = $this->db->query($qGetChildren);
683 while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
684 if(in_array($aGetChildren['id'], $subscriptions)) {
685 $folderNode->add_node($this->buildTreeNodeFolders($aGetChildren, $nodePath, $folderStates, $subscriptions));
689 $rootNode->add_node($folderNode);
692 /* the code below is called only by Settings->Folders when selecting folders to subscribe to */
696 if(!empty($rootNode->nodes)) {
697 foreach($rootNode->nodes as $node) {
698 $metaNode[] = $this->buildTreeNodeRefresh($node, $subscriptions);
706 * Builds up a metanode for folder refresh (Sugar folders only)
708 function buildTreeNodeRefresh($folderNode, $subscriptions) {
709 $metaNode = $folderNode->_properties;
710 $metaNode['expanded'] = $folderNode->expanded;
711 $metaNode['text'] = $folderNode->_label;
712 if($metaNode['is_group'] == 'true') {
713 $metaNode['cls'] = 'groupFolder';
715 $metaNode['cls'] = 'sugarFolder';
717 $metaNode['id'] = $folderNode->_properties['id'];
718 $metaNode['children'] = array();
719 $metaNode['type'] = 1;
720 $metaNode['leaf'] = false;
721 $metaNode['isTarget'] = true;
722 $metaNode['allowChildren'] = true;
724 if(!empty($folderNode->nodes)) {
725 foreach($folderNode->nodes as $node) {
726 if(in_array($node->_properties['id'], $subscriptions))
727 $metaNode['children'][] = $this->buildTreeNodeRefresh($node, $subscriptions);
734 * Builds children nodes for folders for TreeView
735 * @return $folderNode TreeView node
737 function buildTreeNodeFolders($a, $nodePath, $folderStates, $subscriptions) {
740 if($a['name'] == 'My Drafts') {
741 $label = $mod_strings['LBL_LIST_TITLE_MY_DRAFTS'];
743 if($a['name'] == 'Sent Emails') {
744 $label = $mod_strings['LBL_LIST_TITLE_MY_SENT'];
746 $unseen = $this->getCountNewItems($a['id'], array('field' => 'status', 'value' => 'unread'), $a);
748 $folderNode = new ExtNode($a['id'], $label);
749 $folderNode->dynamicloadfunction = '';
750 $folderNode->expanded = false;
752 $nodePath .= "::{$a['id']}";
754 if(array_key_exists($nodePath, $folderStates)) {
755 if($folderStates[$nodePath] == 'open') {
756 $folderNode->expanded = true;
760 $folderNode->dynamic_load = true;
761 $folderNode->set_property('click', "SUGAR.email2.listView.populateListFrameSugarFolder(YAHOO.namespace('frameFolders').selectednode, '{$a['id']}', 'false');");
762 $folderNode->set_property('ieId', 'folder');
763 $folderNode->set_property('mbox', $a['id']);
764 $folderNode->set_property('is_group', ($a['is_group'] == 1) ? 'true' : 'false');
765 $folderNode->set_property('is_dynamic', ($a['is_dynamic'] == 1) ? 'true' : 'false');
766 $folderNode->set_property('unseen', $unseen);
767 $folderNode->set_property('folder_type', $a['folder_type']);
769 if(in_array($a['id'], $subscriptions) && $a['has_child'] == 1) {
770 $qGetChildren = $this->core.$this->coreWhere."AND parent_folder = '{$a['id']}' ".$this->coreOrderBy;
771 $rGetChildren = $this->db->query($qGetChildren);
773 while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
774 $folderNode->add_node($this->buildTreeNodeFolders($aGetChildren, $nodePath, $folderStates, $subscriptions));
781 * Flags a folder as deleted
782 * @return bool True on success
785 global $current_user;
787 if(!empty($this->id)) {
788 if($this->has_child) {
789 $this->deleteChildrenCascade($this->id);
792 $ownerCheck = ($current_user->is_admin == 0) ? " AND created_by = '{$current_user->id}'" : "";
793 $q = "UPDATE folders SET deleted = 1 WHERE id = '{$this->id}'{$ownerCheck}";
794 $r = $this->db->query($q);
801 * Deletes all children in a cascade
802 * @param string $id ID of parent
803 * @return bool True on success
805 function deleteChildrenCascade($id) {
806 global $current_user;
809 $checkInboundQuery = "SELECT count(*) c FROM inbound_email WHERE groupfolder_id = '{$id}' and deleted = 0";
810 $resultSet = $this->db->query($checkInboundQuery);
811 $a = $this->db->fetchByAssoc($resultSet);
816 $q = "SELECT COUNT(*) c from folders_rel where polymorphic_module = 'Emails' AND polymorphic_id = '{$id}' AND folder_id = '{$this->id}'";
818 $checkEmailQuery = "SELECT count(*) c FROM folders_rel where polymorphic_module = 'Emails' and folder_id = '{$id}' and deleted = 0";
819 $resultSet = $this->db->query($checkEmailQuery);
820 $a = $this->db->fetchByAssoc($resultSet);
825 $q = "SELECT * FROM folders WHERE id = '{$id}'";
826 $r = $this->db->query($q);
827 $a = $this->db->fetchByAssoc($r);
829 if($a['has_child'] == 1) {
830 $q2 = "SELECT id FROM folders WHERE parent_folder = '{$id}'";
831 $r2 = $this->db->query($q2);
833 while($a2 = $this->db->fetchByAssoc($r2)) {
834 $canContinue = $this->deleteChildrenCascade($a2['id']);
840 $ownerCheck = ($current_user->is_admin == 0) ? " AND created_by = '{$current_user->id}'" : "";
841 $q3 = "UPDATE folders SET deleted = 1 WHERE id = '{$id}'{$ownerCheck}";
842 $r3 = $this->db->query($q3);
845 $qRel = "UPDATE folders_rel SET deleted = 1 WHERE folder_id = '{$id}'";
846 $rRel = $this->db->query($qRel);
848 // delete subscriptions
849 $qSub = "DELETE FROM folders_subscriptions WHERE folder_id = '{$id}'";
850 $rSub = $this->db->query($qSub);
853 //_pp($q3);_pp($qRel);_pp($qSub);
861 function save($addSubscriptions = TRUE) {
862 global $current_user;
864 $this->dynamic_query = $this->db->quote($this->dynamic_query);
866 if((empty($this->id) && $this->new_with_id == false) || (!empty($this->id) && $this->new_with_id == true))
869 if( empty($this->id) )
871 $guid = create_guid();
875 $q = "INSERT INTO folders(id, name, folder_type, parent_folder, has_child, is_group, is_dynamic, dynamic_query, assign_to_id, ".
876 "created_by, modified_by, deleted)".
878 " VALUES('{$this->id}', '{$this->name}', '{$this->folder_type}', '{$this->parent_folder}', {$this->has_child}, {$this->is_group}, {$this->is_dynamic}, '{$this->dynamic_query}', '{$this->assign_to_id}', " .
879 "'{$current_user->id}', '{$current_user->id}', 0)";
882 if($addSubscriptions)
884 // create default subscription
885 $this->addSubscriptionsToGroupFolder();
888 // if parent_id is set, update parent's has_child flag
889 $q3 = "UPDATE folders SET has_child = 1 WHERE id = '{$this->parent_folder}'";
890 $r3 = $this->db->query($q3);
893 $q = "UPDATE folders SET name = '{$this->name}', parent_folder = '{$this->parent_folder}', dynamic_query = '{$this->dynamic_query}', assign_to_id = '{$this->assign_to_id}', " .
894 "modified_by = '{$current_user->id}' WHERE id = '{$this->id}'";
897 $this->db->query($q, true);
903 * Add subscriptions to this group folder.
906 function addSubscriptionsToGroupFolder()
908 global $current_user;
910 $this->createSubscriptionForUser($current_user->id);
917 * Add subscriptions to this group folder.
920 function createSubscriptionForUser($user_id)
922 $guid2 = create_guid();
923 $query = "INSERT INTO folders_subscriptions VALUES('{$guid2}', '{$this->id}', '{$user_id}')";
924 $this->db->query($query);
928 function updateFolder($fields) {
929 global $current_user;
931 $this->dynamic_query = $this->db->quote($this->dynamic_query);
932 $id = $fields['record'];
933 $name = $fields['name'];
934 $parent_folder = $fields['parent_folder'];
935 // first do the retrieve
936 $this->retrieve($id);
937 if ($this->has_child) {
938 $childrenArray = array();
939 $this->findAllChildren($id, $childrenArray);
940 if (in_array($parent_folder, $childrenArray)) {
941 return array('status' => "failed", 'message' => "Can not add this folder to its children");
944 // update has_child to 0 for this parent folder if this is the only child it has
945 $q1 = "select count(*) count from folders where deleted = 0 AND parent_folder = '{$this->parent_folder}'";
946 $r1 = $this->db->query($q1);
947 $a1 = $this->db->fetchByAssoc($r1);
948 if ($a1['count'] == 1) {
949 $q1 = "UPDATE folders SET has_child = 0 WHERE id = '{$this->parent_folder}'";
950 $r1 = $this->db->query($q1);
955 $this->parent_folder = $parent_folder;
956 $q2 = "UPDATE folders SET name = '{$this->name}', parent_folder = '{$this->parent_folder}', dynamic_query = '{$this->dynamic_query}', " .
957 "modified_by = '{$current_user->id}' WHERE id = '{$this->id}'";
958 $r2 = $this->db->query($q2);
959 if (!empty($this->parent_folder)) {
960 $q3 = "UPDATE folders SET has_child = 1 WHERE id = '{$this->parent_folder}'";
961 $r3 = $this->db->query($q3);
963 return array('status' => "done");
967 function findAllChildren($folderId, &$childrenArray) {
968 $q = "SELECT * FROM folders WHERE id = '{$folderId}'";
969 $r = $this->db->query($q);
970 $a = $this->db->fetchByAssoc($r);
972 if($a['has_child'] == 1) {
973 $q2 = "SELECT id FROM folders WHERE deleted = 0 AND parent_folder = '{$folderId}'";
974 $r2 = $this->db->query($q2);
976 while($a2 = $this->db->fetchByAssoc($r2)) {
977 $childrenArray[] = $a2['id'];
978 $this->findAllChildren($a2['id'], $childrenArray);
985 * Retrieves and populates object
986 * @param string $id ID of folder
987 * @return bool True on success
989 function retrieve($id) {
990 $q = "SELECT * FROM folders WHERE id = '{$id}' AND deleted = 0";
991 $r = $this->db->query($q);
992 $a = $this->db->fetchByAssoc($r);
995 foreach($a as $k => $v) {
996 if($k == 'dynamic_query') {