]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SugarFolders/SugarFolders.php
Release 6.5.0
[Github/sugarcrm.git] / include / SugarFolders / SugarFolders.php
1 <?php
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.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  *********************************************************************************/
44
45 require_once("include/ytree/Tree.php");
46 require_once("include/ytree/ExtNode.php");
47
48 /**
49  * Polymorphic buckets - place any item in a folder
50  */
51 class SugarFolder {
52
53         // public attributes
54         var $id;
55         var $name;
56         var $parent_folder;
57         var $has_child = 0; // flag node has child
58         var $is_group = 0;
59         var $is_dynamic = 0;
60         var $dynamic_query = '';
61         var $assign_to_id;
62         var $created_by;
63         var $modified_by;
64         var $date_created;
65         var $date_modified;
66         var $deleted;
67         var $folder_type;
68
69         var $db;
70         var $new_with_id = false;
71
72         // core queries
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 ";
78
79         var $hrSortLocal = array(
80             'flagged' => 'type',
81             'status'  => 'reply_to_status',
82             'from'    => 'emails_text.from_addr',
83             'subject' => 'name',
84             'date'    => 'date_sent',
85             'AssignedTo' => 'assigned_user_id',
86             'flagged' => 'flagged'
87         );
88     var $defaultSort = 'date';
89     var $defaultDirection = "DESC";
90
91         // private attributes
92         var $_depth;
93
94         /**
95          * Sole constructor
96          */
97         function SugarFolder() {
98                 $this->db = DBManagerFactory::getInstance();
99         }
100
101         function deleteEmailFromAllFolder($id) {
102                 $q = "delete from folders_rel where polymorphic_module = 'Emails' AND polymorphic_id = '{$id}' ";
103                 $r = $this->db->query($q);
104         }
105
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);
109         }
110
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);
115                 if ($a['c'] > 0) {
116                         return true;
117                 } else {
118                         return false;
119                 } // else
120         }
121         /**
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
126          */
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);
130         }
131
132         /**
133          * Copies one bean from one folder to another
134          */
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);
139         }
140
141         /**
142          * Creates a new group Folder from the passed fields
143          * @param array fields
144          */
145         function setFolder($fields) {
146
147                 global $current_user;
148                 if(empty($fields['groupFoldersUser'])) {
149                         $fields['groupFoldersUser'] = $current_user->id;
150                 }
151
152                 $this->name = $fields['name'];
153                 $this->parent_folder = $fields['parent_folder'];
154                 $this->has_child = 0;
155                 $this->is_group = 1;
156                 $this->assign_to_id = $fields['groupFoldersUser'];
157
158                 $this->save();
159         }
160
161         /**
162          * Returns GUIDs of folders that the user in focus is subscribed to
163          * @param object user User object in focus
164          * @return array
165          */
166         function getSubscriptions($user) {
167                 if(empty($user)) {
168                         global $current_user;
169                         $user = $current_user;
170                 }
171
172                 $q = "SELECT folder_id FROM folders_subscriptions WHERE assigned_user_id = '{$user->id}'";
173                 $r = $this->db->query($q);
174                 $ret = array();
175                 while($a = $this->db->fetchByAssoc($r)) {
176                         $ret[] = $a['folder_id'];
177                 }
178                 return $ret;
179         }
180
181         /**
182          * Sets a user's preferences for subscribe folders (Sugar only)
183          * @param array subs Array of IDs for subscribed folders
184          */
185         function setSubscriptions($subs) {
186                 global $current_user;
187
188                 if(empty($current_user->id)) {
189                         $GLOBALS['log']->fatal("*** FOLDERS: tried to update folder subscriptions for a user with no ID");
190                         return false;
191                 }
192
193                 $cleanSubscriptions = array();
194
195                 // ensure parent folders are selected, regardless.
196                 foreach($subs as $id) {
197                         $id = trim($id);
198                         if(!empty($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);
203
204                                 if(!empty($aChk['parent_folder'])) {
205                                         $cleanSubscriptions = $this->getParentIDRecursive($aChk['parent_folder'], $cleanSubscriptions);
206                                 }
207                         }
208                 }
209
210                 $this->clearSubscriptions();
211
212                 foreach($cleanSubscriptions as $id) {
213                     $this->insertFolderSubscription($id, $current_user->id);
214                 }
215         }
216
217         /**
218          * Given a folder id and user id, create a folder subscription entry.
219          *
220          * @param String $folderId
221          * @param String $userID
222          * @return String The id of the newly created folder subscription.
223          */
224         function insertFolderSubscription($folderId, $userID)
225         {
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);
229                 return $guid;
230         }
231         /**
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
236          */
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);
241
242                 if(!in_array($id, $ret)) {
243                         $ret[] = $id;
244                 }
245
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);
250
251                         if(!empty($aChk['parent_folder'])) {
252                                 $ret = $this->getParentIDRecursive($aChk['parent_folder'], $ret);
253                         }
254                 }
255
256                 return $ret;
257         }
258
259         /**
260          * Deletes subscriptions to folders in preparation for reset
261          */
262         function clearSubscriptions() {
263                 global $current_user;
264
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);
268                 }
269         }
270
271
272         /**
273          * Deletes all subscriptions for a particular folder id
274          *
275          * @return unknown
276          */
277         function clearSubscriptionsForFolder($folderID)
278         {
279             $query = "DELETE FROM folders_subscriptions WHERE folder_id = '$folderID'";
280             $r = $this->db->query($query);
281         }
282
283         protected function generateArchiveFolderQuery()
284         {
285                 global $current_user;
286             $q = <<<ENDQ
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'
292 WHERE eear.deleted=0
293 )
294 ENDQ;
295         return $q;
296         }
297
298         function generateSugarsDynamicFolderQuery()
299         {
300                 global $current_user;
301                 $type = $this->folder_type;
302                 if($type == 'archived') {
303                     return $this->generateArchiveFolderQuery();
304                 }
305                 $status = $type;
306                 if($type == "sent") {
307                         $type = "out";
308                 }
309                 if($type == 'inbound') {
310                         $ret = " AND emails.status NOT IN ('sent', 'archived', 'draft') AND emails.type NOT IN ('out', 'archived', 'draft')";
311                 } else {
312                         $ret = " AND emails.status NOT IN ('archived') AND emails.type NOT IN ('archived')";
313                 }
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";
317                 return $q . $ret;
318         } // fn
319
320
321         /**
322          * returns array of items for listView display in yui-ext Grid
323          */
324         function getListItemsForEmailXML($folderId, $page = 1, $pageSize = 10, $sort = '', $direction='') {
325                 require_once('include/TimeDate.php');
326                 global $timedate;
327                 global $current_user;
328                 global $beanList;
329                 global $sugar_config;
330                 global $app_strings;
331
332                 $this->retrieve($folderId);
333                 $start = ($page - 1) * $pageSize;
334
335                 $sort = (empty($sort)) ? $this->defaultSort : $sort;
336         $direction = (empty($direction)) ? $this->defaultDirection : $direction;
337         $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
338
339                 if($this->is_dynamic) {
340                         $r = $this->db->limitQuery(from_html($this->generateSugarsDynamicFolderQuery() . $order), $start, $pageSize);
341                 } else {
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";
348                         }
349                         $r = $this->db->limitQuery($q . $order, $start, $pageSize);
350                 }
351
352                 $return = array();
353
354                 $email = new Email(); //Needed for email specific functions.
355
356                 while($a = $this->db->fetchByAssoc($r)) {
357
358                         $temp = array();
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']);
372                         $return[] = $temp;
373                 }
374
375
376                 $metadata = array();
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;
382
383                 return $metadata;
384         }
385
386         function getCountItems ( $folderId ) {
387                 global $current_user ;
388                 global $beanList ;
389                 global $sugar_config ;
390                 global $app_strings ;
391
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 )) ;
398                 } else {
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";
404                         }
405                         $r = $this->db->query ( $q ) ;
406                 }
407
408                 $a = $this->db->fetchByAssoc($r);
409                 return $a['c'];
410         }
411
412     function getCountUnread ( $folderId ) {
413         global $current_user ;
414         global $beanList ;
415         global $sugar_config ;
416         global $app_strings ;
417
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'") ;
424         } else {
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";
430             }
431             $r = $this->db->query ( $q ) ;
432         }
433
434                 $a = $this->db->fetchByAssoc($r);
435         return $a['c'];
436     }
437
438
439         /**
440          * Convenience method, pass a SugarBean and User to this to add anything to a given folder
441          */
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");
445                         return false;
446                 } elseif(empty($this->id)) {
447                         $GLOBALS['log']->fatal("*** FOLDERS: addBean() is trying to save to a non-saved or non-existent folder");
448                         return false;
449                 }
450
451                 global $current_user;
452                 if($user == null) {
453                         $user = $current_user;
454                 }
455
456                 $guid = create_guid();
457
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);
461                 return true;
462         }
463
464         /**
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
468          */
469         function retrieveFoldersForProcessing($user, $subscribed=true) {
470                 global $sugar_config;
471                 global $current_language, $current_user;
472
473                 $emails_mod_strings = return_module_language($current_language, "Emails");
474                 $myEmailTypeString = 'inbound';
475                 $myDraftsTypeString = 'draft';
476                 $mySentEmailTypeString = 'sent';
477
478                 if(empty($user)) {
479                         global $current_user;
480                         $user = $current_user;
481                 }
482                 $rootWhere = '';
483         $teamSecurityClause = '';
484
485
486
487         $rootWhere .= "AND (f.parent_folder IS NULL OR f.parent_folder = '')";
488
489                 if($subscribed) {
490                         $q = $this->coreSubscribed.$teamSecurityClause.$this->coreWhereSubscribed."'{$user->id}' ".$rootWhere.$this->coreOrderBy;
491                 } else {
492                         $q = $this->core.$teamSecurityClause.$this->coreWhere.$rootWhere.$this->coreOrderBy;
493                 }
494                 $r = $this->db->query($q);
495                 $return = array();
496
497                 $found = array();
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)) {
503
504                                 continue;
505                         } // if
506                         if (!isset($found[$a['id']])) {
507                 $found[$a['id']] = true;
508                             $return[] = $a;
509                         }
510                 }
511                 return $return;
512         }
513     /**
514          * Preps object array for async call from user's Settings->Folders
515          */
516         function getGroupFoldersForSettings($focusUser=null) {
517                 global $app_strings;
518
519                 $grp = array();
520
521                 $folders = $this->retrieveFoldersForProcessing($focusUser, false);
522                 $subscriptions = $this->getSubscriptions($focusUser);
523
524                 foreach($folders as $a) {
525                         $a['selected'] = (in_array($a['id'], $subscriptions)) ? true : false;
526             $a['origName'] = $a['name'];
527
528                         if($a['is_group'] == 1)
529                                 if ($a['deleted'] != 1)
530                                         $grp[] = $a;
531                 }
532
533                 return $grp;
534         }
535         /**
536          * Preps object array for async call from user's Settings->Folders
537          */
538         function getFoldersForSettings($focusUser=null) {
539                 global $app_strings;
540
541                 $user = array();
542                 $grp = array();
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' => "");
545
546                 $folders = $this->retrieveFoldersForProcessing($focusUser, false);
547                 $subscriptions = $this->getSubscriptions($focusUser);
548
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) {
555                                 $grp[] = $a;
556                         } else {
557                                 $user[] = $a;
558                         }
559
560                         if($a['has_child'] == 1) {
561                                 $qGetChildren = $this->core.$this->coreWhere."AND parent_folder = '{$a['id']}'";
562                                 $rGetChildren = $this->db->query($qGetChildren);
563
564                                 while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
565                                         if($a['is_group']) {
566                                                 $this->_depth = 1;
567                                                 $grp = $this->getFoldersChildForSettings($aGetChildren, $grp, $subscriptions);
568                                         } else {
569                                                 $this->_depth = 1;
570                                                 $user = $this->getFoldersChildForSettings($aGetChildren, $user, $subscriptions);
571                                         }
572                                 }
573                         }
574                 }
575
576                 $ret = array(
577                         'userFolders'   => $user,
578                         'groupFolders'  => $grp,
579                 );
580                 return $ret;
581         }
582
583         function getFoldersChildForSettings($a, $collection, $subscriptions) {
584                 $a['selected'] = (in_array($a['id'], $subscriptions)) ? true : false;
585                 $a['origName'] = $a['name'];
586
587                 if(isset($a['dynamic_query']))
588                 {
589                    unset($a['dynamic_query']);
590                 }
591
592                 for($i=0; $i<$this->_depth; $i++)
593                 {
594                         $a['name'] = ".".$a['name'];
595                 }
596
597                 $collection[] = $a;
598
599                 if($a['has_child'] == 1) {
600                         $this->_depth++;
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);
605                         }
606                 }
607
608                 return $collection;
609         }
610
611         /**
612          * Returns the number of "new" items (based on passed criteria)
613          * @param string id ID of folder
614          * @param array criteria
615          *              expected:
616          *              array('field' => 'status',
617          *                              'value' => 'unread');
618          * @param array
619          * @return int
620          */
621         function getCountNewItems($id, $criteria, $folder) {
622                 global $current_user;
623
624                 $sugarFolder = new SugarFolder();
625                 return $sugarFolder->getCountUnread($id);
626         }
627
628         /**
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
633          * @return array
634          */
635         function getUserFolders(&$rootNode, $folderStates, $user=null, $forRefresh=false) {
636                 if(empty($user)) {
637                         global $current_user;
638                         $user = $current_user;
639                 }
640                 global $mod_strings;
641                 $folders = $this->retrieveFoldersForProcessing($user, true);
642                 $subscriptions = $this->getSubscriptions($user);
643
644                 $refresh = ($forRefresh) ? array() : null;
645
646                 if(!is_array($folderStates)) {
647                         $folderStates = array();
648                 }
649
650                 foreach($folders as $a) {
651                         if ($a['deleted'] == 1)
652                                 continue;
653                         $label = ($a['name'] == 'My Email' ? $mod_strings['LNK_MY_INBOX'] : $a['name']);
654
655                         $unseen = $this->getCountNewItems($a['id'], array('field' => 'status', 'value' => 'unread'), $a);
656
657                         $folderNode = new ExtNode($a['id'], $label);
658                         $folderNode->dynamicloadfunction = '';
659                         $folderNode->expanded = false;
660
661                         if(array_key_exists('Home::'.$a['id'], $folderStates)) {
662                                 if($folderStates['Home::'.$a['id']] == 'open') {
663                                         $folderNode->expanded = true;
664                                 }
665                         }
666                         $nodePath = "Home::".$folderNode->_properties['id'];
667
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());
678
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);
682
683                                 while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
684                                         if(in_array($aGetChildren['id'], $subscriptions)) {
685                                                 $folderNode->add_node($this->buildTreeNodeFolders($aGetChildren, $nodePath, $folderStates, $subscriptions));
686                                         }
687                                 }
688                         }
689                         $rootNode->add_node($folderNode);
690                 }
691
692                 /* the code below is called only by Settings->Folders when selecting folders to subscribe to */
693                 if($forRefresh) {
694                         $metaNode = array();
695
696                         if(!empty($rootNode->nodes)) {
697                                 foreach($rootNode->nodes as $node) {
698                                         $metaNode[] = $this->buildTreeNodeRefresh($node, $subscriptions);
699                                 }
700                         }
701                         return $metaNode;
702                 }
703         }
704
705         /**
706          * Builds up a metanode for folder refresh (Sugar folders only)
707          */
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';
714                 } else {
715                     $metaNode['cls'] = 'sugarFolder';
716                 }
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;
723
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);
728                         }
729                 }
730                 return $metaNode;
731         }
732
733         /**
734          * Builds children nodes for folders for TreeView
735          * @return $folderNode TreeView node
736          */
737         function buildTreeNodeFolders($a, $nodePath, $folderStates, $subscriptions) {
738                 $label = $a['name'];
739                 global $mod_strings;
740                 if($a['name'] == 'My Drafts') {
741                         $label = $mod_strings['LBL_LIST_TITLE_MY_DRAFTS'];
742                 }
743                 if($a['name'] == 'Sent Emails') {
744                         $label = $mod_strings['LBL_LIST_TITLE_MY_SENT'];
745                 }
746                 $unseen = $this->getCountNewItems($a['id'], array('field' => 'status', 'value' => 'unread'), $a);
747
748                 $folderNode = new ExtNode($a['id'], $label);
749                 $folderNode->dynamicloadfunction = '';
750                 $folderNode->expanded = false;
751
752                 $nodePath .= "::{$a['id']}";
753
754                 if(array_key_exists($nodePath, $folderStates)) {
755                         if($folderStates[$nodePath] == 'open') {
756                                 $folderNode->expanded = true;
757                         }
758                 }
759
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']);
768
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);
772
773                         while($aGetChildren = $this->db->fetchByAssoc($rGetChildren)) {
774                                 $folderNode->add_node($this->buildTreeNodeFolders($aGetChildren, $nodePath, $folderStates, $subscriptions));
775                         }
776                 }
777                 return $folderNode;
778         }
779
780         /**
781          * Flags a folder as deleted
782          * @return bool True on success
783          */
784         function delete() {
785                 global $current_user;
786
787                 if(!empty($this->id)) {
788                         if($this->has_child) {
789                                 $this->deleteChildrenCascade($this->id);
790                         }
791
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);
795                         return true;
796                 }
797                 return false;
798         }
799
800         /**
801          * Deletes all children in a cascade
802          * @param string $id ID of parent
803          * @return bool True on success
804          */
805         function deleteChildrenCascade($id) {
806                 global $current_user;
807
808                 $canContinue = true;
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);
812                 if ($a['c'] > 0) {
813                         return false;
814                 } // if
815
816                 $q = "SELECT COUNT(*) c from folders_rel where polymorphic_module = 'Emails' AND polymorphic_id = '{$id}' AND folder_id = '{$this->id}'";
817
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);
821                 if ($a['c'] > 0) {
822                         return false;
823                 } // if
824
825                 $q = "SELECT * FROM folders WHERE id = '{$id}'";
826                 $r = $this->db->query($q);
827                 $a = $this->db->fetchByAssoc($r);
828
829                 if($a['has_child'] == 1) {
830                         $q2 = "SELECT id FROM folders WHERE parent_folder = '{$id}'";
831                         $r2 = $this->db->query($q2);
832
833                         while($a2 = $this->db->fetchByAssoc($r2)) {
834                                 $canContinue = $this->deleteChildrenCascade($a2['id']);
835                         }
836                 }
837
838                 if ($canContinue) {
839                         // flag deleted
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);
843
844                         // flag rels
845                         $qRel = "UPDATE folders_rel SET deleted = 1 WHERE folder_id = '{$id}'";
846                         $rRel = $this->db->query($qRel);
847
848                         // delete subscriptions
849                         $qSub = "DELETE FROM folders_subscriptions WHERE folder_id = '{$id}'";
850                         $rSub = $this->db->query($qSub);
851                 }
852                 return $canContinue;
853                 //_pp($q3);_pp($qRel);_pp($qSub);
854         }
855
856
857         /**
858          * Saves folder
859          * @return bool
860          */
861         function save($addSubscriptions = TRUE) {
862                 global $current_user;
863
864                 $this->dynamic_query = $this->db->quote($this->dynamic_query);
865
866                 if((empty($this->id) && $this->new_with_id == false) || (!empty($this->id) && $this->new_with_id == true))
867                 {
868
869                     if( empty($this->id) )
870                     {
871                             $guid = create_guid();
872                             $this->id = $guid;
873                     }
874
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)".
877
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)";
880
881
882                         if($addSubscriptions)
883                         {
884                             // create default subscription
885                             $this->addSubscriptionsToGroupFolder();
886                         }
887
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);
891                 }
892                 else {
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}'";
895                 }
896
897                 $this->db->query($q, true);
898
899                 return true;
900         }
901
902         /**
903          * Add subscriptions to this group folder.
904          *
905          */
906         function addSubscriptionsToGroupFolder()
907         {
908             global $current_user;
909
910             $this->createSubscriptionForUser($current_user->id);
911
912         }
913
914
915
916     /**
917          * Add subscriptions to this group folder.
918          *
919          */
920         function createSubscriptionForUser($user_id)
921         {
922            $guid2 = create_guid();
923            $query = "INSERT INTO folders_subscriptions VALUES('{$guid2}', '{$this->id}', '{$user_id}')";
924            $this->db->query($query);
925         }
926
927
928         function updateFolder($fields) {
929                 global $current_user;
930
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");
942                         }
943                 }
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);
951                 } // if
952
953
954                 $this->name = $name;
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);
962                 } // if
963                 return array('status' => "done");
964
965         } // fn
966
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);
971
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);
975
976                         while($a2 = $this->db->fetchByAssoc($r2)) {
977                                 $childrenArray[] = $a2['id'];
978                                 $this->findAllChildren($a2['id'], $childrenArray);
979                         } // while
980                 } // if
981
982         } // fn
983
984         /**
985          * Retrieves and populates object
986          * @param string $id ID of folder
987          * @return bool True on success
988          */
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);
993
994                 if(!empty($a)) {
995                         foreach($a as $k => $v) {
996                                 if($k == 'dynamic_query') {
997                                         $v = from_html($v);
998                                 }
999                                 $this->$k = $v;
1000                         }
1001                         return true;
1002                 }
1003
1004                 return false;
1005         }
1006 } // end class def