Code

removing the dummy array caused no data to be displayed.
[gosa.git] / gosa-plugins / groupware / personal / groupware / class_groupware.inc
1 <?php
2 /*
3  * This code is part of GOsa (https://gosa.gonicus.de)
4  * Copyright (C) 2008 Cajus Pollmeier
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 class groupware extends plugin
21 {
22     var $plHeadline     = "Mail";
23     var $plDescription  = "GOsa mail extension.";
24     var $view_logged = FALSE;
26     var $accountInitialized = FALSE;
27     var $rpcError = FALSE;
28     var $rpcErrorMessage = "";
30     
31     var $attributes = array(
32             "mailAddress",
33             "mailLocation",
34             "quotaUsage",
35             "quotaSize",
36             "alternateAddresses",
37             "forwardingAddresses",
38             "vacationEnabled",
39             "vacationStart",
40             "vacationStop",
41             "vacationMessage",
42             "mailBoxWarnLimitEnabled",
43             "mailBoxWarnLimitValue",
44             "mailBoxSendSizelimitEnabled",
45             "mailBoxSendSizelimitValue",
46             "mailBoxHardSizelimitEnabled",
47             "mailBoxHardSizelimitValue",
48             "mailBoxAutomaticRemovalEnabled",
49             "mailBoxAutomaticRemovalValue",
50             "localDeliveryOnly",
51             "dropOwnMails"
52             );
53             
55     var $enabledFeatures = array();
57     var $flagAttributes = array("vacationEnabled","mailBoxWarnLimitEnabled","mailBoxSendSizelimitEnabled",
58             "mailBoxHardSizelimitEnabled","mailBoxAutomaticRemovalEnabled","localDeliveryOnly","dropOwnMails");
60     var $mailAddressSelectDialog = NULL;
61     var $filterManager = NULL;
62     var $filterRules = array();
63     var $vacationTemplates = array();
65     //the dropdown
66     var $mailLocations = array();
67     
68     var $mailAddress = "";
69     var $mailLocation = "";
70     var $quotaUsage = 0;
71     var $quotaSize = 0;
72     var $alternateAddresses = array();
73     var $forwardingAddresses = array();
74     var $vacationEnabled = FALSE;
75     var $vacationStart = 0;
76     var $vacationStop = 0;
77     var $vacationMessage = "";
78     var $mailBoxWarnLimitEnabled = FALSE;
79     var $mailBoxWarnLimitValue = 100;
80     var $mailBoxSendSizelimitEnabled = FALSE;
81     var $mailBoxSendSizelimitValue = 100;
82     var $mailBoxHardSizelimitEnabled = FALSE;
83     var $mailBoxHardSizelimitValue = 100;
84     var $mailBoxAutomaticRemovalEnabled = FALSE;
85     var $mailBoxAutomaticRemovalValue = 100;
86     var $localDeliveryOnly = FALSE;
87     var $dropOwnMails = FALSE;
89     var $groupwareDao = FALSE;
90     function __construct ($config, $dn= NULL)
91     {
92         plugin::plugin($config,$dn); 
94         // Get attributes from parent object 
95         foreach(array("uid","cn") as $attr){
96             if(isset($this->parent->by_object['group']) && isset($this->parent->by_object['group']->$attr)){
97                 $this->$attr = &$this->parent->by_object['group']->$attr;
98             }elseif(isset($this->attrs[$attr])){
99                 $this->$attr = $this->attrs[$attr][0];
100             }
101         }
102         // Initialize the plugin using rpc.
103         $this->init();
104     }
106     /*! \brief  Try to execute a function on the gosa backend using json-rpc.
107      *          This method also takes care about errors and sets the required
108      *           class members, such as rpcError and rpcErrorMessage. 
109      *  @param  String  function    The name of the function to call.
110      *  @param  Mixed   args[0-n]   The parameter to use.
111      *  @return Mixed   The result of the function call on success else NULL.
112      */
113     function rpcExec($function)
114     {
115         $params = func_get_args();
116         unset($params[0]);
117         //echo "------<br>Calling function:".$function." Params".var_dump($params)."<br>";
118      
119         $rpc = $this->config->getRpcHandle();
120         
121         $res = call_user_func_array(array($rpc,$function),array_values($params));
122         $this->rpcError = !$rpc->success();
123         if($this->rpcError){
124             $this->rpcErrorMessage = $rpc->get_error();
125             return(NULL);
126         }
127         return($res);
128     }
129         public function isFeatureEnabled($featureName){
130                 if(isset($this->enabledFeatures[$featureName]) &&  $this->enabledFeatures[$featureName]){
131                         return TRUE;
132                 }
133                 return FALSE;
134         }
136     /*! \brief  Try initialize the groupware account.
137      *          This method fetches all required information to manage the
138      *           account using the GOsa gui.
139      */
140     function init()
141     {
142         // Detect feature availability and enable/disable services correspondingly.
143         $this->groupwareDao = new groupware_dao($this);
145         $features = array();
146         
147         /*
148          * feature names with a list of groupware function that must be availabele
149          * these groupware functions are not the rpc functions, because they are asked from the groupware server
150          */
151         $featureReq = array(
152                         "primaryMail"                           => array(
153                                 'acctGetPrimaryMailAddress'),
154                     "quotaUsage"                => array(
155                         'acctGetQuota'),
156                 "quotaSize"                 => array(
157                     'acctSetQuota','acctGetQuota'),
158                         "mailLocations"                         => array(
159                                 'getMailboxLocations'),
160                 "mailFilter"                => array("_off",
161                     'acctDelFilter','acctGetFilters','acctSetFilters','acctSetFilters'),
162                 "alternateAddresses"        => array(
163                     'acctDelAlternateMailAddress','acctSetAlternateMailAddresses',
164                     'acctAddAlternateMailAddress','acctGetAlternateMailAddresses'),
165                 "forwardingAddresses"       => array(
166                     'acctAddMailForwardAddress','acctDelMailForwardAddress',
167                     'acctGetMailForwardAddresses','acctSetMailForwardAddresses'),
168                 "vacationMessage"           => array("_off",
169                     'acctDelFilter','acctGetFilters','acctSetFilters','acctSetFilters'),
170                 "mailBoxWarnLimit"          => array(
171                     'acctSetQuota','acctGetQuota'),
172                 "mailBoxSendSizelimit"      => array(
173                     'acctSetQuota','acctGetQuota'),
174                 "mailBoxHardSizelimit"      => array(
175                     'acctSetQuota','acctGetQuota'),
176                 "mailBoxAutomaticRemoval"   => array("_off",
177                         'acctSetQuota','acctGetQuota'),
178                 "localDeliveryOnly"         => array( "_off",
179                         'acctDelFilter','acctGetFilters','acctSetFilters','acctSetFilters'),
180                 "dropOwnMails"              => array( "_off",
181                         'acctDelFilter','acctGetFilters','acctSetFilters','acctSetFilters'));
182       
183         // Check if all required methods cann be called! 
184         foreach($featureReq as $name => $requires){
185             $active = TRUE;
186             foreach($requires as $methodName){
187                 $active &= $this->groupwareDao->gwFeatureAvailable($methodName);
188             }
189             $this->enabledFeatures[$name] = $active;
190         }
191         // Get rpc handle to fetch account info and feature availability.
192         $status = $this->rpcExec('gwAcctExists', $this->uid);
193         if($status !== NULL){
194                                 
195                 
196                 $response = $this->groupwareDao->getComprehensiverUser($this->uid);
197                 /*
198                         $response = array("mailAddress"=>"hape@exdom.de",
199             "mailLocation"=>"mailbox 1",
200                         "mailLocations"=>array("hape","mailbox 1"),
201             "quotaUsage"=>10,
202             "quotaSize"=>100,
203             "alternateAddresses"=>"alternateAddresses@exdom.de",
204             "forwardingAddresses"=>"forwardingAddresses@exdom.de",
205             "vacationEnabled"=>1,
206             "vacationStart"=>"09.09.2010",
207             "vacationStop"=>"08.09.2010",
208             "vacationMessage"=>"bin in Urlaub message",
209             "mailBoxWarnLimitEnabled"=>1,
210             "mailBoxWarnLimitValue"=>99,
211             "mailBoxSendSizelimitEnabled"=>1,
212             "mailBoxSendSizelimitValue"=>100,
213             "mailBoxHardSizelimitEnabled"=>1,
214             "mailBoxHardSizelimitValue"=>105,
215             "mailBoxAutomaticRemovalEnabled"=>0,
216             "mailBoxAutomaticRemovalValue"=>"mailBoxAutomaticRemovalValue",
217             "localDeliveryOnly"=>0,
218             "dropOwnMails"=>0 );
219                         
220                         $response = array_merge( $response, $compResponse);
221                         */
222                         
223                         $this->mapComprehensiveUserData($response);
224             $this->initially_was_account = $this->is_account = $status;
225         
226                 $this->accountInitialized = TRUE;
227         }
228         // Set vacation start/stop if not set alreasy
229         $this->vacationStart = time();
230         $this->vacationStop = time() + (14 * 60*60*24);
232         // Prepare vacation start/stop time to be initially valid.  
233         $this->vacationStart= date('d.m.Y', $this->vacationStart);
234         $this->vacationStop= date('d.m.Y', $this->vacationStop);
235     }
238     /*! \brief  Generates the HTML user interface for the groupware plugin
239      *           and take of several ui actions like adding or removing 
240      *           forward addresses, filters and the account itself.
241      */
242     function execute()
243     {
244         // Register plugin execution 
245         $display = plugin::execute();
247         // Log plugin execution.
248         if($this->is_account && !$this->view_logged){
249             $this->view_logged = TRUE;
250             new log("view","users/".get_class($this),$this->dn);
251         }
253         // Check if we were able to initialize the account already.
254         if(!$this->accountInitialized){
255             $this->init();
256             if(!$this->accountInitialized){
257                 $smarty = get_smarty();
258                 $smarty->assign("initFailed", !$this->accountInitialized);
259                 return($smarty->fetch(get_template_path("generic.tpl",TRUE,dirname(__FILE__))));
260             }
261         }
263         // Check if we were able to initialize the account already.
264         if($this->rpcError){
265             $smarty = get_smarty();
266             $smarty->assign("initFailed", !$this->accountInitialized);
267             $smarty->assign("rpcError", $this->rpcError);
268             return($smarty->fetch(get_template_path("generic.tpl",TRUE,dirname(__FILE__))));
269         }
271         /****************
272           Filter editor
273          ****************/
275         if(isset($_POST['filterManager_cancel'])) $this->filterManager = NULL;
276         if(isset($_POST['filterManager_ok'])){
277             $this->filterManager->save_object();
278             $msgs = $this->filterManager->check();
279             if(count($msgs)){
280                 msg_dialog::displayChecks($msgs);
281             }else{
282                 $this->filterRules = $this->filterManager->save();
283                 $this->filterManager = NULL;
284             }
285         }
286         if(isset($_POST['configureFilter'])){
287             $this->filterManager = new filterManager($this->config, $this,$this->filterRules);
288             $this->filterManager->acl_base = $this->acl_base;
289             $this->filterManager->acl_category = $this->acl_category;
290         }
291         $this->dialog = FALSE;
292         if($this->filterManager instanceOf filterManager){
293             $this->filterManager->save_object();
294             $this->dialog = TRUE;
295             return($this->filterManager->execute());
296         }
298         /****************
299           Account status
300          ****************/
302         if(isset($_POST['modify_state'])){
303             if($this->is_account && $this->acl_is_removeable()){
304                 $this->is_account= FALSE;
305             }elseif(!$this->is_account && $this->acl_is_createable()){
306                 $this->is_account= TRUE;
307             }
308         }
309         if(!$this->multiple_support_active){
310             if (!$this->is_account && $this->parent === NULL){
311                 $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
312                     msgPool::noValidExtension(_("Mail"))."</b>";
313                 $display.= back_to_main();
314                 return ($display);
315             }
316             if ($this->parent !== NULL){
317                 if ($this->is_account){ 
318                     $display= $this->show_disable_header(msgPool::removeFeaturesButton(_("Mail")),msgPool::featuresEnabled(_("Mail")));
319                 } else {
320                     $display= $this->show_enable_header(msgPool::addFeaturesButton(_("Mail")),msgPool::featuresDisabled(_("Mail")));
321                     return ($display);
322                 }
323             }
324         }
325                 
326         /****************
327           Forward addresses 
328          ****************/
330         // Display dialog to select a local fowarder 
331         if (isset($_POST['addLocalForwardingAddress'])){
332             $this->mailAddressSelectDialog=  new mailAddressSelect($this->config, get_userinfo());
333             $this->dialog= TRUE;
334         }
336         // Close dialogs, action was canceled 
337         if (isset($_POST['mailAddressSelect_cancel'])){
338             $this->mailAddressSelectDialog= FALSE;
339             $this->dialog= FALSE;
340         }
342         // Append selected forwarding addresses now.
343         if (isset($_POST['mailAddressSelect_save']) && $this->mailAddressSelectDialog instanceOf mailAddressSelect){
344             if($this->acl_is_writeable("forwardingAddresses")){
345                 $list = $this->mailAddressSelectDialog->save();
346                 foreach ($list as $entry){
347                     $val = $entry['mail'][0];
348                     if (!in_array ($val, $this->alternateAddresses) && $val != $this->mailAddress){
349                         $this->addForwarder($val);
350                         $this->is_modified= TRUE;
351                     }
352                 }
353                 $this->mailAddressSelectDialog= FALSE;
354                 $this->dialog= FALSE;
355             } else {
356                 msg_dialog::display(_("Error"), _("Please select an entry!"), ERROR_DIALOG);
357             }
358         }
360         // Display the address selection dialog.
361         if($this->mailAddressSelectDialog instanceOf mailAddressSelect){
362             $used  = array();
363             $used['mail'] = array_values($this->alternateAddresses);  
364             $used['mail'] = array_merge($used['mail'], array_values($this->forwardingAddresses));  
365             $used['mail'][] = $this->mailAddress;
367             // Build up blocklist
368             session::set('filterBlacklist', $used);
369             return($this->mailAddressSelectDialog->execute());
370         }
372         // Add manually inserted forwarding address.
373         if (isset($_POST['addForwardingAddress'])){
374             if ($_POST['forwardingAddressInput'] != ""){
375                 $address= get_post('forwardingAddressInput');
376                 $valid= FALSE;
377                 if (!tests::is_email($address)){
378                     if (!tests::is_email($address, TRUE)){
379                         if ($this->is_template){
380                             $valid= TRUE;
381                         } else {
382                             msg_dialog::display(_("Error"), msgPool::invalid(_("Mail address"),
383                                         "","","your-address@your-domain.com"),ERROR_DIALOG);
384                         }
385                     }
386                 } elseif ($address == $this->mailAddress || in_array($address, $this->alternateAddresses)) {
387                     msg_dialog::display(_("Error"),_("Cannot add primary address to the list of forwarders!") , ERROR_DIALOG);
388                 } else {
389                     $valid= TRUE;
390                 }
391                 if ($valid){
392                     if($this->acl_is_writeable("forwardingAddresses")){
393                         $this->addForwarder ($address);
394                         $this->is_modified= TRUE;
395                     }
396                 }
397             }
398         }
399         if (isset($_POST['deleteForwardingAddress'])){
400             $this->delForwarder ($_POST['forwardingAddressList']);
401         }
403         /****************
404           Alternate addresses 
405          ****************/
406         // Add manually inserted alternate mail address.
407         if (isset($_POST['addAlternateAddress'])){
408             $valid= FALSE;
409             if (!tests::is_email($_POST['alternateAddressInput'])){
410                 if ($this->is_template){
411                     if (!(tests::is_email($_POST['alternateAddressInput'], TRUE))){
412                         msg_dialog::display(_("Error"),msgPool::invalid(_("Mail address"),
413                                     "","","your-domain@your-domain.com"),ERROR_DIALOG);
414                     } else {
415                         $valid= TRUE;
416                     }
417                 } else {
418                     msg_dialog::display(_("Error"),msgPool::invalid(_("Mail address"),
419                                 "","","your-domain@your-domain.com"),ERROR_DIALOG);
420                 }
421             } else {
422                 $valid= TRUE;
423             }
424             if ($valid && ($user= $this->addAlternate (get_post('alternateAddressInput'))) != ""){
425                 $ui= get_userinfo();
426                 $addon= "";
427                 if ($user[0] == "!") {
428                     $addon= sprintf(_("Address is already in use by group '%s'."), mb_substr($user, 1));
429                 } else {
430                     $addon= sprintf(_("Address is already in use by user '%s'."), $user);
431                 }
432                 msg_dialog::display(_("Error"), msgPool::duplicated(_("Mail address"))."<br><br><i>".
433                         "$addon</i>", ERROR_DIALOG);
434             }
435         }
437         // Remove alternate mail address.
438         if (isset($_POST['deleteAlternateAddress']) && isset($_POST['alternateAddressList'])){
439             $this->delAlternate ($_POST['alternateAddressList']);
440         }
443         /****************
444           SMARTY- Assign smarty variables 
445          ****************/
447         $smarty = get_smarty();
448         foreach($this->attributes as $attr){
449                 
450             $smarty->assign($attr, $this->$attr);
451         }
453         $plInfo = $this->plInfo();
454         foreach($plInfo['plProvidedAcls'] as $acl => $name){
455             $smarty->assign($acl."ACL", $this->getacl($acl));
456         }
457         foreach($this->enabledFeatures as $feature => $state){
458             $smarty->assign($feature."_isActive", $state);
459         }
461      
462         $smarty->assign("mailLocations", $this->mailLocations);
463         if (count($this->vacationTemplates)){
464             $smarty->assign("displayTemplateSelector", "true");
465             $smarty->assign("vacationTemplate", set_post($this->vacationTemplate));
466             $smarty->assign("vacationTemplates", set_post($this->vacationTemplates));
467             $smarty->assign("template", set_post(get_post('vacation_template')));
468         } else {
469             $smarty->assign("displayTemplateSelector", "false");
470         }
472         $smarty->assign("initFailed", !$this->accountInitialized);
473         $smarty->assign("rpcError", $this->rpcError);
474         $smarty->assign("rpcErrorMessage", $this->rpcErrorMessage);
475         
476        
477         return($display.$smarty->fetch(get_template_path("generic.tpl",TRUE,dirname(__FILE__))));
478     }
481     /*! \brief      This method handles potential _POST and _GET values.
482      *              It captures modifcations from the ui, like changing 
483      *               the mailAddress.
484      *              This method respects the attribute permissions.
485      */    
486     function save_object()
487     {
488         if(isset($_POST['groupwarePluginPosted'])){
490             // We ran into a communication error with the backend. 
491             // Try a simple communication operation with the backend 
492             //  again and let us see if it works.
493             if(isset($_POST['retry'])){
494                 $this->rpcExec('gwGetCapabilities');
495             }
497             // Get ui modifications and store them in the class.
498             $testAttrs = array("mailAddress","mailLocation","quotaUsage","quotaSize",
499                     "alternateAddresses","forwardingAddresses","vacationEnabled","vacationStart",
500                     "vacationStop","vacationMessage");
501             foreach($testAttrs as $attr){
502                 if(isset($_POST[$attr]) && $this->acl_is_writeable($attr)){
503                     $this->$attr = get_post($attr);
504                 }
505             }
507             // Detect checkbox states 
508             $checkAttrs = array("mailBoxWarnLimit","mailBoxSendSizelimit",
509                     "mailBoxHardSizelimit","mailBoxAutomaticRemoval");
510             foreach($checkAttrs as $boxname){
511                 if($this->acl_is_writeable($boxname)){
512                     $v = $boxname."Value"; 
513                     $e = $boxname."Enabled"; 
514                     $this->$e = isset($_POST[$e]);
515                     if($this->$e){
516                         $this->$v = get_post($v);
517                     }
518                 }
519             }
521             // Get posted flag changes 
522             $flagAttrs = array("localDeliveryOnly","dropOwnMails");
523             foreach($flagAttrs as $attr){
524                 $this->$attr = isset($_POST[$attr]);
525             }
526         }
527     }
530     /*! \brief  Parse vacation templates and build up an array
531       containing 'filename' => 'description'. 
532       Used to fill vacation dropdown box.
533       @return Array   All useable vacation templates.
534      */ 
535     function get_vacation_templates()
536     {
537         $vct = array();
538         if ($this->config->get_cfg_value("core","vacationTemplateDirectory") != ""){
539             $dir= $this->config->get_cfg_value("core","vacationTemplateDirectory");
540             if (is_dir($dir) && is_readable($dir)){
541                 $dh = opendir($dir);
542                 while($file = readdir($dh)){
543                     $description= "";
544                     if (is_file($dir."/".$file)){
545                         $fh = fopen($dir."/".$file, "r");
546                         $line= fgets($fh, 256);
547                         if (!preg_match('/^DESC:/', $line)){
548                             msg_dialog::display(_("Configuration error"), sprintf(_("No DESC tag in vacation template '%s'!"), $file), ERROR_DIALOG);
549                         }else{
550                             $description= trim(preg_replace('/^DESC:\s*/', '', $line));
551                         }
552                         fclose ($fh);
553                     }
554                     if ($description != ""){
555                         $vct["$dir/$file"]= $description;
556                     }
557                 }
558                 closedir($dh);
559             }
560         }
561         return($vct); 
562     }
565     /*! \brief  Adds the given mail address to the list of mail forwarders 
566      */ 
567     function addForwarder($address)
568     {
569         if(empty($address)) return;
570         if($this->acl_is_writeable("forwardingAddresses")){
571             $this->forwardingAddresses[]= $address;
572             $this->forwardingAddresses= array_unique ($this->forwardingAddresses);
573             sort ($this->forwardingAddresses);
574             reset ($this->forwardingAddresses);
575             $this->is_modified= TRUE;
576         }else{
577             msg_dialog::display(_("Permission error"), _("You have no permission to modify these addresses!"), ERROR_DIALOG);
578         }
579     }
582     /*! \brief  Removes the given mail address from the list of mail forwarders 
583      */ 
584     function delForwarder($addresses)
585     {
586         if($this->acl_is_writeable("forwardingAddresses")){
587             $this->forwardingAddresses= array_remove_entries ($addresses, $this->forwardingAddresses);
588             $this->is_modified= TRUE;
589         }else{
590             msg_dialog::display(_("Permission error"), _("You have no permission to modify these addresses!"), ERROR_DIALOG);
591         }
592     }
595     /*! \brief  Add given mail address to the list of alternate adresses ,
596       .          check if this mal address is used, skip adding in this case 
597      */ 
598     function addAlternate($address)
599     {
600         if(empty($address)) return;
601         if($this->acl_is_writeable("alternateAddresses")){
602             $ldap= $this->config->get_ldap_link();
603             $address= strtolower($address);
605             /* Is this address already assigned in LDAP? */
606             $ldap->cd ($this->config->current['BASE']);
607             $ldap->search ("(&(!(objectClass=gosaUserTemplate))(objectClass=gosaMailAccount)(|(mail=$address)".
608                     "(alias=$address)(gosaMailAlternateAddress=$address)))", array("uid", "cn"));
609             if ($ldap->count() > 0){
610                 $attrs= $ldap->fetch ();
611                 if (!isset($attrs["uid"])) {
612                     return ("!".$attrs["cn"][0]);
613                 }
614                 return ($attrs["uid"][0]);
615             }
616             if (!in_array($address, $this->alternateAddresses)){
617                 $this->alternateAddresses[]= $address;
618                 $this->is_modified= TRUE;
619             }
620             sort ($this->alternateAddresses);
621             reset ($this->alternateAddresses);
622             return ("");
623         }else{
624             msg_dialog::display(_("Permission error"), _("You have no permission to modify these addresses!"), ERROR_DIALOG);
625         }
626     }
629     /*! \brief  Removes the given mail address from the alternate addresses list 
630      */ 
631     function delAlternate($addresses)
632     {
633         if($this->acl_is_writeable("alternateAddresses")){
634             $this->alternateAddresses= array_remove_entries ($addresses,$this->alternateAddresses);
635             $this->is_modified= TRUE;
636         }else{
637             msg_dialog::display(_("Permission error"), _("You have no permission to modify these addresses!"), ERROR_DIALOG);
638         }
639     }
642     /*! \brief  Prepare importet vacation string. \
643       .         Replace placeholder like %givenName a.s.o.
644       @param  string  Vacation string
645       @return string  Completed vacation string
646      */
647     private function prepare_vacation_template($contents)
648     {
649         /* Replace attributes */
650         $attrs = array();
651         $obj   = NULL;
652         if(isset($this->parent->by_object['user'])){
653             $attrs  = $this->parent->by_object['user']->attributes;
654             $obj    = $this->parent->by_object['user'];
655         }else{
656             $obj    = new user($this->config,$this->dn);
657             $attrs  = $obj->attributes;
658         }
659         if($obj){
661             /* Replace vacation start and end time */
662             if($this->enabledFeatures['vacationMessage']){
663                 if(preg_match("/%start/",$contents)){
664                     $contents = preg_replace("/%start/",$this->vacationStart,$contents);
665                 }
666                 if(preg_match("/%end/",$contents)){
667                     $contents = preg_replace("/%end/",$this->vacationStop,$contents);
668                 }
669             }else{
670                 if(preg_match("/%start/",$contents)){
671                     $contents = preg_replace("/%start/", _("unknown"),$contents);
672                 }
673                 if(preg_match("/%end/",$contents)){
674                     $contents = preg_replace("/%end/", _("unknown"), $contents);
675                 }
676             }
678             foreach ($attrs as $val){
680                 // We can only replace strings here
681                 if(!is_string($obj->$val)) continue;
683                 if(preg_match("/dateOfBirth/",$val)){
684                     if($obj->use_dob){
685                         $contents= preg_replace("/%$val/",date("Y-d-m",$obj->dateOfBirth),$contents);
686                     }
687                 }else {
688                     $contents= preg_replace("/%$val/",
689                             $obj->$val, $contents);
690                 }
692             }
693         }
694         $contents = ltrim(preg_replace("/^DESC:.*$/m","",$contents),"\n ");
695         return($contents);
696     }
698     
699         /*
700          * remove the account form the groupware server completely. 
701          */
702     function remove_from_parent()
703     {
704         // Get rpc handle to remove the account
705         if($this->initially_was_account){
706             if($this->rpcExec('gwAcctDel', $this->uid) === NULL){
707                 msg_dialog::display(_("Error"), _("Groupware account removal failed!"), ERROR_DIALOG);
708             }
709         }
710     }
712     
713         /*
714          * Persists the values of this plugin to the groupware server
715          * Save method ist called on "apply" and "ok" in the Gosa Frontend 
716          * All other actions will update values in the form or 
717          * cancel and therefore discard the changes so far.
718          */
719     function save()
720     {
721         // Get rpc handle to create or update the account
722         if(!$this->initially_was_account){
723             if($this->rpcExec('gwAcctAdd', $this->uid, $this->mailAddress) === NULL){
724                 msg_dialog::display(_("Error"), _("Groupware account creation failed!"), ERROR_DIALOG);
725             }
726         }
727          
728         /*
729          *save the primary Email Address.
730          */
731         if(!empty($this->mailAddress)){
732                 $this->groupwareDao->save("primaryMail", $this->uid, $this->mailAddress);
733         }
734         
735         /*
736          *  save alternateAddresses and forwarding. 
737          */
738         if(isset($this->alternateAddresses) && is_array($this->alternateAddresses)){
739                         $this->groupwareDao->save("alternateAddresses", $this->uid, $this->alternateAddresses);
740         }
741         if(isset($this->forwardingAddresses) && is_array($this->forwardingAddresses)){
742                         $this->groupwareDao->save("forwardingAddresses", $this->uid, $this->forwardingAddresses);
743         }
744         /*
745          * save the quota
746          */
747          if(true){
748                 $quota = array( "warn_limit" => $this->mailBoxWarnLimitValue,
749                                                         "send_limit" => $this->mailBoxSendSizelimitValue,
750                                                         "hard_limit" => $this->mailBoxHardSizelimitValue,
751                                                         "hold" => $this->quotaSize,
752                                                         "usage" => $this->quotaUsage);
753                 $this->groupwareDao->save("quotaSize", $this->uid, $quota);
754          }
755          
756          /*
757           * TODO: save Mailbox location
758           */
759       
760     }
763     /*! \brief  Check given values 
764      */
765     function check()
766     {
767         /*
768          * TODO: Remove all echo Messages
769          */
770         $messages = plugin::check();
771         /*
772          * Check the dates 
773          */
774         
775         /*
776          * TODO: check only if features are enabled.
777          */
778         //required vacationEnabled
779                 if($this->vacationEnabled){
780                 if(!tests::is_date($this->vacationStart)){
781                         $messages[] = msgPool::invalid(_("Vacation start date"),$this->vacationStart , "", _("Example of date : 01.03.2010"));
782                 }
783                 if(!tests::is_date($this->vacationStop)){
784                         $messages[] = msgPool::invalid(_("Vacation stop date"),$this->vacationStop , "", _("Example of date : 01.03.2010"));
785                 }
786                 $diff = tests::compareDate($this->vacationStart, $this->vacationStop);
787                
788                 if($diff>=0){
789                         $messages[] = msgPool::invalid(_("Vacation dates"), $this->vacationStart." - ".$this->vacationStop, "", _("Enddate before Start or the same."));
790                 }
791                 }
792                 if(!tests::is_email ($this->mailAddress)){
793                         $messages[] = msgPool::invalid(_("Mail address"),$this->mailAddress , "", _("Example: user@excom.intranet.gonicus.de"));
794                 }
795                 /*
796                  * forwarding Addresses
797                  * $alternateAddresses 
798          * $forwardingAddresses
799                  */
800                 if(isset($this->forwardingAddresses) && is_array($this->forwardingAddresses)){
801                         foreach($this->forwardingAddresses as $fAddress){
802                                 if(!tests::is_email ($fAddress)){
803                                         $messages[] = msgPool::invalid(_("Mail address"),$fAddress, "", 
804                                                 _("Example: user@excom.intranet.gonicus.de"));
805                                 }
806                                 if($fAddress == $this->mailAddress){
807                                         $messages[] = msgPool::invalid(_("Mail address same as primary Email Address"),$fAddress, "",
808                                                  _("Forward Address and primary Email Address must not be the same (cirle reference)"));
809                                 }
810                         }
811                 }
812                 if(isset($this->alternateAddresses) && is_array($this->alternateAddresses)){
813                         foreach($this->alternateAddresses as $fAddress){
814                                 if(!tests::is_email ($fAddress)){
815                                         $messages[] = msgPool::invalid(_("Mail address"),$fAddress, "", _("Example: user@excom.intranet.gonicus.de"));
816                                 }
817                                 if($fAddress == $this->mailAddress){
818                                         $messages[] = msgPool::invalid(_("Mail address same as primary Email Address"),$fAddress, "",
819                                                  _("Alternative Address and primary Email Address must not be the same (cirle reference)"));
820                                 }
821                         }
822                 }
823                 //TODO: Checks for quota and Locations?
824                 
825         return($messages);
826     }
828     
829     /*! \brief  Adapt from template, using 'dn' 
830      */
831     function adapt_from_template($dn, $skip= array())
832     {
833         plugin::adapt_from_template($dn, $skip);
835     }
837     
838     /*! \brief  ACL settings 
839      */
840     static function plInfo()
841     {
842         return (array(
843                     "plShortName"     => _("Groupware"),
844                     "plDescription"   => _("Groupware settings"),
845                     "plSelfModify"    => TRUE,
846                     "plDepends"       => array("user"),                     // This plugin depends on
847                     "plPriority"      => 4,                                 // Position in tabs
848                     "plSection"     => array("personal" => _("My account")),
849                     "plCategory"    => array("users"),
850                     "plOptions"       => array(),
851                     "plProvidedAcls"  => array(
852                         "mailAddress"                   => _("Mail address"),
853                         "mailLocation"                  => _("Mail location"),
854                         "quotaUsage"                    => _("Quota usage"),
855                         "mailFilter"                    => _("Mail filter"),
856                         "quotaSize"                     => _("Quota size"),
857                         "alternateAddresses"            => _("Alternate mail addresses"),
858                         "forwardingAddresses"           => _("Forwarding mail addresses"),
859                         "vacationEnabled"               => _("Vaction switch"),
860                         "vacationStart"                 => _("Vacation start time"),
861                         "vacationStop"                  => _("Vacation stop time"),
862                         "vacationMessage"               => _("Vacation message"),
863                         "mailBoxWarnLimit"              => _("Warn sizelimit"),
864                         "mailBoxSendSizelimit"          => _("Send sizelimit"),
865                         "mailBoxHardSizelimit"          => _("Hard sizelimit"),
866                         "mailBoxAutomaticRemoval"       => _("Automatic mail removal"),
867                         "localDeliveryOnly"             => _("Local delivery only"),
868                         "dropOwnMails"                  => _("Drop own mails")
869                         )
870                     ));
871     }
872     
873     
874     /*
875      * maps the resultset fetched from the Dao to the class variables 
876      * of the plugin.
877      */
878     function mapComprehensiveUserData($callBackMap)
879     {
880             $this->mailLocations = $callBackMap["mailLocations"];
881         
882             $this->mailAddress = $callBackMap["primaryMail"];
883             $this->mailLocation = $callBackMap["mailLocation"];
884             $this->quotaUsage = $callBackMap["quotaUsage"];
885             $this->quotaSize = $callBackMap["quotaSize"];
886             $this->alternateAddresses = $callBackMap["alternateAddresses"];
887             $this->forwardingAddresses = $callBackMap["forwardingAddresses"];
888             $this->vacationEnabled = $callBackMap["vacationEnabled"];
889             $this->vacationStart = $callBackMap["vacationStart"];
890             $this->vacationStop = $callBackMap["vacationStop"];
891             $this->vacationMessage = $callBackMap["vacationMessage"];
892             $this->mailBoxWarnLimitEnabled = $callBackMap["mailBoxWarnLimitEnabled"];
893             $this->mailBoxWarnLimitValue = $callBackMap["mailBoxWarnLimitValue"];
894             $this->mailBoxSendSizelimitEnabled = $callBackMap["mailBoxSendSizelimitEnabled"];
895             $this->mailBoxSendSizelimitValue = $callBackMap["mailBoxSendSizelimitValue"];
896             $this->mailBoxHardSizelimitEnabled = $callBackMap["mailBoxHardSizelimitEnabled"];
897             $this->mailBoxHardSizelimitValue = $callBackMap["mailBoxHardSizelimitValue"];
898             $this->mailBoxAutomaticRemovalEnabled = $callBackMap["mailBoxAutomaticRemovalEnabled"];
899             $this->mailBoxAutomaticRemovalValue = $callBackMap["mailBoxAutomaticRemovalValue"];
900             $this->localDeliveryOnly = $callBackMap["localDeliveryOnly"];
901             $this->dropOwnMails = $callBackMap["dropOwnMails"];
902             
903     }
907 /*
908  * Data Access Object for groupwares 
909  */
910 class groupware_dao{
911         /*
912          * TODO: Remove the debug 
913          * use the debug functions fo the Gosa installation instead.
914          * function_debug
915          * (got ot remove the following variable, the function debug and all calls to it)
916          */
917         private $debug = true;
918         
919         private $availableMethods;
920         private $availableProperties;
921         private $accountLocations;
922         
923         private static $gwFeatures  = array(
924                 "primaryMail" => array( "get"=>"gwAcctGetPrimaryMailAddress", 
925                                                                 "save"=>"gwAcctSetPrimaryMailAddress"),
926                 "mailLocations" => array("get"=>"gwGetMailboxLocations"),
927                 "quotaSize"  =>array(  "get"=>"gwAcctGetQuota", 
928                                                                 "save"=>"gwAcctSetQuota",
929                                                                 "delete"=>"gwAcctSetQuota"),
930                 "mailFilter"  =>array(  "get"=>"gwAcctGetFilters", 
931                                                                 "save"=>"gwAcctSetFilters",
932                                                                 "delete"=>"gwAcctDelFilter"),
933         "alternateAddresses"  =>array(  "get"=>"gwAcctGetAlternateMailAddresses", 
934                                                                 "save"=>"gwAcctSetAlternateMailAddresses",
935                                                                 "delete"=>"gwAcctDelAlternateMailAddress"),
936         "forwardingAddresses"  =>array( "get"=>"gwAcctGetMailForwardAddresses", 
937                                                                                 "save"=>"gwAcctSetMailForwardAddresses",
938                                                                                 "delete"=>"gwAcctDelMailForwardAddress"),
939         "vacationMessage"  =>array(     "get"=>"gwAcctGetOutOfOfficeReply", 
940                                                                                 "save"=>"gwAcctSetOutOfOfficeReply",
941                                                                                 "delete"=>"gwAcctDelOutOfOfficeReply"),
942         "mailBoxWarnLimit"  =>array(    "get"=>"", 
943                                                                                 "save"=>"",
944                                                                                 "delete"=>""),
945         "mailBoxSendSizelimit"  =>array(  "get"=>"gwAcctGetQuota", 
946                                                                 "save"=>"gwAcctSetQuota",
947                                                                 "delete"=>"gwAcctDelQuota"),
948         "mailBoxHardSizelimit"  =>array(  "get"=>"gwAcctGetMailLimit", 
949                                                                 "save"=>"gwAcctSetMailLimit",
950                                                                 "delete"=>"gwAcctDelMailLimit"),
951                 "mailBoxAutomaticRemoval"  =>array(  "get"=>"", 
952                                                                 "save"=>"",
953                                                                 "delete"=>""),
954                 "localDeliveryOnly"  =>array(  "get"=>"", 
955                                                                 "save"=>"",
956                                                                 "delete"=>""),
957                 "dropOwnMails"  =>array(  "get"=>"",
958                                                                 "save"=>"",
959                                                                 "delete"=>""),
960                 "accountProperties" => array("get"=>"gwAcctGetProperties",
961                                                                 "save"=>"gwAcctSetProperties",
962                                                                 "delete"=>"gwAcctDelProperties")
963         
964         );
965         private $groupwarePluginRef = False;
966         
967         
968         /*
969          * Constructor sets the connection to the rpc service 
970          * initializes the class
971          */
972         function __construct(&$pluginRef)
973         {
975                 $this->groupwarePluginRef = &$pluginRef;
976                 
977                 /*
978                  * TODO:
979                  * Remove all echos 
980                  */
981         
982                 $this->init();
983         }
984         
985         
986         /*
987          * gets the capabilities of the server
988          * builds an array with availbale features and knows how to call get, save, delete functions of 
989          * groupware rpc. 
990          */
991         public function init()
992         {
993                 
994                 $this->availableMethods = $this->groupwarePluginRef->rpcExec('gwGetCapabilities');
995                 //$this->availableProperties = $this->groupwarePluginRef->rpcExec('gwGetSupportedProperties');
996                 //$this->debug("availableProperties on init:", $this->availableProperties);
998         }
999         
1000         
1001         /*
1002          * generic saving method for all features defined in $gwFeatures
1003          * which are the available features.
1004          */
1005         public function save($feature, $uid, $valueArray)
1006         {
1007                 $function = groupware_dao::$gwFeatures[$feature]["save"];
1008                 
1009                 if(is_array($valueArray)){
1010                         $valueArray = array_merge(array($function, $uid), $valueArray);
1011                 }
1012                 else{
1013                         $valueArray = array($function, $uid, $valueArray);
1014                 }
1015                 $this->debug("SAVING (feature, value)", $valueArray);
1016                 $result =  call_user_func_array(array($this->groupwarePluginRef, 'rpcExec'), $valueArray);
1017                 
1018                 return $result;
1019         }
1020         
1021         
1022         /*
1023          * generic get method for all features defined in $gwFeatures
1024          * which are the available features.
1025          */
1026         public function get($feature, $valueArray)
1027         {
1028                 /*
1029                  * TODO: 
1030                  * check if feture available ? 
1031                  * get and return the result.
1032                  */
1033                 $function = groupware_dao::$gwFeatures[$feature]["get"];
1034                 if(is_array($valueArray)){
1035                         $valueArray = array_merge(array($function), $valueArray);
1036                 }
1037                 else{
1038                         $valueArray = array($function, $valueArray);
1039                 }
1040                 
1041                 $result =  call_user_func_array(array($this->groupwarePluginRef, 'rpcExec'), $valueArray);
1042                 
1043                 return $result;
1044         }
1045         
1046         
1047         /*
1048          * generic delete function for all features defined in $gwFeatures
1049          * which are the available features.
1050          * 
1051          * NOT YET IMPLEMENTED
1052          */
1053         public function del($feature, $valueArray)
1054         {
1055                 /*
1056                  * TODO: 
1057                  * check if feture available
1058                  * del and return the result.
1059                  */
1060                 echo "deletion of values is not implemented yet";
1061                 /*
1062                 $function = groupware_dao::$gwFeatures[$feature]["delete"];
1064                 $valueArray = array_merge(array($function), $valueArray);
1065                 
1066                 $result =  call_user_func_array(array($this->groupwarePluginRef, 'rpcExec'), $valueArray);
1067                 
1068                 return $result;
1069                 */
1070         }
1071         
1072         
1073         /*
1074          * determine availability of features.
1075          * @param methodName
1076          * @return boolean
1077          */
1078         public function gwFeatureAvailable($methodName)
1079         {
1081                 return $this->availableMethods[$methodName];
1082         }
1083         
1084         
1085         /*
1086          * comprehensive user info will dessolve into one groupware call later
1087          * right now it will get all data of the features that are available in the plugin.
1088          * @param int $uid
1089          * @return assoc array "feature" => "gwValue";   
1090          */
1091         public function getComprehensiverUser( $uid)
1092         {
1093                 //$hi = $this->groupwarePluginRef->rpcExec('gwGetCapabilities');
1094                 $resultArr = array();
1095                 
1096                 if($this->groupwarePluginRef->isFeatureEnabled("primaryMail")){
1097                         $resultArr["primaryMail"] = $this->get("primaryMail", array($uid));
1098                 }
1099                 
1100                 if($this->groupwarePluginRef->isFeatureEnabled("alternateAddresses")){
1101                         $resultArr["alternateAddresses"] = $this->get("alternateAddresses", array($uid));
1102                 }
1103                 
1104                 if($this->groupwarePluginRef->isFeatureEnabled("forwardingAddresses")){
1105                         $resultArr["forwardingAddresses"] = $this->get("forwardingAddresses", array($uid));
1106                 }
1107                 
1108                 if($this->groupwarePluginRef->isFeatureEnabled("forwardingAddresses")){
1109                         $resultArr["forwardingAddresses"] = $this->get("forwardingAddresses", array($uid));
1110                 }
1111                 
1112                 //location dropdownlist - only readable
1113                 if($this->groupwarePluginRef->isFeatureEnabled("mailLocations")){
1114                         $resultArr["mailLocations"] = $this->groupwarePluginRef->rpcExec('gwGetMailboxLocations');
1115                         $resultArr["mailLocation"] = $this->groupwarePluginRef->rpcExec(array('gwAcctGetLocation',$uid));
1116                 }
1117                 /*
1118                  * TODO:
1119                  * getLocation muss ebenfalls geholt werden
1120                  */
1121                 
1122                 //Quota quotaUsage, quotaSize
1123                 if($this->groupwarePluginRef->isFeatureEnabled("quotaSize") || 
1124                         $this->groupwarePluginRef->isFeatureEnabled("quotaUsage") || 
1125                         $this->groupwarePluginRef->isFeatureEnabled("mailBoxWarnLimit") || 
1126                         $this->groupwarePluginRef->isFeatureEnabled("mailBoxSendSizelimit") || 
1127                         $this->groupwarePluginRef->isFeatureEnabled("mailBoxHardSizelimit")){
1128                         
1129                         /*
1130                          * Usage is a Mapi function which is not yet 
1131                          */
1132                         /*
1133                          * TODO:
1134                          * remove the following dummy and enable the qota fetch from groupware
1135                          */ 
1136                         echo "Quota function not yet implemented on server side!!";
1137                         //$quota = $this->get("quotaSize", array($uid));
1138                         $quota = array( "warn_limit" => 1008,
1139                                                         "send_limit" => 108,
1140                                                         "hard_limit" => 1108,
1141                                                         "hold" => 508,
1142                                                         "usage" => 1108);
1143                             $resultArr["quotaSize"] = $quota["usage"];
1144                             $resultArr["quotaSize"] = $quota["hold"];
1145                             if($quota["warn_limit"] > 0){
1146                                     $resultArr["mailBoxWarnLimitEnabled"] = true;
1147                                     $resultArr["mailBoxWarnLimitValue"] = $quota["warn_limit"];
1148                             }
1149                             else{
1150                                 $resultArr["mailBoxWarnLimitEnabled"] = false;
1151                                     $resultArr["mailBoxWarnLimitValue"] = 0;
1152                             }
1153                             if($quota["send_limit"] > 0){
1154                                  $resultArr["mailBoxSendSizelimitEnabled"] = True;
1155                                 $resultArr["mailBoxSendSizelimitValue"] = $quota["send_limit"];
1156                             }
1157                             else{
1158                                          $resultArr["mailBoxSendSizelimitEnabled"] = FALSE;
1159                                 $resultArr["mailBoxSendSizelimitValue"] = 0;    
1160                             }
1161                                 if($quota["hard_limit"] > 0){
1162                                         $resultArr["mailBoxHardSizelimitEnabled"] = True;
1163                                 $resultArr["mailBoxHardSizelimitValue"] = $quota["hard_limit"]; 
1164                                 }
1165                                 else{
1166                                         $resultArr["mailBoxHardSizelimitEnabled"] = FALSE;
1167                                 $resultArr["mailBoxHardSizelimitValue"] = 0;
1168                                 }
1169                 }
1171                 /*
1172                  * this function seems to be broken on the server.
1173                  * addding dummy
1174                  */
1175                 if($this->groupwarePluginRef->isFeatureEnabled("vacationMessage")){
1176                         
1177                         $vacMessage = $this->get("vacationMessage", array($uid));
1178                         //$resultArr["vacationMessage"] = "dummy Vacation message - (getOutOfOfficeReply currently throws errors )";
1179                 }
1180                 
1181                 $this->debug("getComprehensiverUser:", $resultArr);
1182                 return $resultArr;
1183         }
1184         
1185         
1186         /*
1187          * TODO: remove all debug functions.
1188          */
1189         public function debug($name, $message)
1190         {
1191                 if($this->debug){
1192                         echo"<b>".$name."</b>";
1193                         if(is_array($message)){
1194                                 echo "<pre>";
1195                                 print_r($message);
1196                                 echo "</pre>";
1197                         }
1198                         else{
1199                                 echo "$message";
1200                         }
1201                 }
1202         }
1204 ?>