Code

Skip setting the voicemail context, only sip here.
[gosa.git] / plugins / gofon / phoneaccount / class_phoneAccount.inc
index 8f1f2869ab9bd54b7df0533593456fedeeb6815a..4edb5afc1c245703f08b2967620d8288dd5927e2 100644 (file)
@@ -13,7 +13,7 @@ class phoneAccount extends plugin
   var $goFonFormat            = "wav";
   var $goFonPIN               = "";
   var $goFonVoicemailPIN      = "";
-  var $goFonDeliveryMode      = "";
+  var $goFonDeliveryMode      = "[]";
   var $phoneNumbers           = array();
   var $mail                   = "";
   var $hardware_list          = array();
@@ -30,13 +30,9 @@ class phoneAccount extends plugin
   var $goFonHomeServer        = "0";            // Contains the dn of the server that manage this account 
   var $init_HomeServer        = "0";            // Contains the dn of the server that manage this account 
   var $goFonHomeServers       = array();        // Contains all available server configurations 
-    
-
-  /* CLI vars */
-  var $cli_summary            = "Manage users phone account";
-  var $cli_description        = "Some longer text\nfor help";
-  var $cli_parameters         = array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
 
+  var $context                = "default";
+    
   /* attribute list for save action */
   var $CopyPasteVars          = array("phoneNumbers","macroarray","macrostillavailable"/*"phoneNumbers" -Reset- */,
                                       "hardware_list","used_hardware");
@@ -66,22 +62,33 @@ class phoneAccount extends plugin
       }
     }
 
+    /* Set uid */
+    if((isset($this->parent->by_object['user']->uid))&&(!empty($this->parent->by_object['user']->uid))){
+      $this->uid = $this->parent->by_object['user']->uid;
+    }
+    if((isset($this->parent->by_object['user']->cn))&&(!empty($this->parent->by_object['user']->cn))){
+      $this->cn  = $this->parent->by_object['user']->cn;
+    }
 
     /* Check server configurations 
      * Load all server configuration in $this->goFonHomeServers if available
      *  and first server as default if necessary.
      * Check if connection is successfull for the selected server $this->goFonHomeServer
      */
+
+    /* Set available server */
+    if(isset($_SESSION['config']->data['SERVERS']['FON'])){
+      $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
+    }
+
     $a_SETUP= array();
-    if(array_key_exists('config',$_SESSION) &&
+    if($this->is_account &&
+       array_key_exists('config',$_SESSION) &&
        array_key_exists('SERVERS',$_SESSION['config']->data) &&
        array_key_exists('FON',$_SESSION['config']->data['SERVERS']) &&
        is_callable("mysql_connect")
        ) {
 
-      /* Set available server */
-      $this->goFonHomeServers = $_SESSION['config']->data['SERVERS']['FON'];
-
       /* Servers defined? Watch here... */
       if (count($this->goFonHomeServers)){
 
@@ -104,13 +111,13 @@ class phoneAccount extends plugin
 
         $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
         if(!$r_con){
-          print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
-                $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
+#          print_red( sprintf(_("The MySQL Server '%s' isn't reachable as user '%s', check GOsa log for mysql error."),
+#                $cur_cfg['SERVER'],$cur_cfg['LOGIN']));
           gosa_log(mysql_error());
         }
         $db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
         if(!$db){
-          print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
+#         print_red(sprintf(_("Can't select database %s on %s."),$cur_cfg['DB'],$cur_cfg['SERVER']));
           gosa_log(mysql_error());
         }
 
@@ -123,11 +130,6 @@ class phoneAccount extends plugin
       }
     }
 
-    /* Check if previously selected server is still available */
-    if($this->is_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
-      print_red(sprintf(_("The previously selected asterisk home server (%s) is no longer available."),preg_replace("/,/",", ",$this->goFonHomeServer)));
-    }
-
     /* Get available phone hardware  
      * Search for all available phone hardware  
      */
@@ -210,7 +212,7 @@ class phoneAccount extends plugin
       unset($tmp[0]);
 
       /* Check if makro has been removed */
-      if(!isset($this->macroarray[$this->macro])){
+      if(!isset($this->macros[$this->macro])){
         $this->macrostillavailable = false;
       }else{
         $this->macrostillavailable = true;
@@ -236,38 +238,42 @@ class phoneAccount extends plugin
      *  so we must detect which phones are currently in use.
      */
     $ldap->cd($this->config->current['BASE']);
-    foreach ($this->hardware_list as $cn => $desc){
-      $ldap->search("(goFonHardware=$cn)", array('cn'));
-      if ($ldap->count() > 0){
-        $ldap->fetch();
-        if ($ldap->getDN() != $this->dn){
-          $this->used_hardware[$cn]= $ldap->getDN();
+    $ldap->search("(goFonHardware=*)",array('cn','dn','goFonHardware'));
+    while($attrs = $ldap->fetch()){
+        $cn = $attrs['goFonHardware'][0];
+        if(isset($this->hardware_list[$cn])){
+          $this->used_hardware[$cn]= $cn;
         }
-      }
     }
     $this->hardware_list["automatic"]= _("automatic");
     ksort($this->hardware_list);
     $this->a_old_telenums = $this->phoneNumbers;
 
-    if($this->is_account){
-      $this->is_modified = true;
-    }
-
-
     /* Get voicemail PIN from MySQL DB 
      * Because every user can change his PIN directly from the phone
      *  without any update to the ldap
      * This means, the PIN in the DB is up to date
      */
-    // Connect to DB server
-    if((is_callable("mysql_pconnect"))&&(isset($cur_cfg))&&(isset($cur_cfg['SERVER']))&&(isset($cur_cfg['LOGIN']))&&(isset($cur_cfg['PASSWORD']))){
+    if( (is_callable("mysql_pconnect"))&&
+        (isset($cur_cfg))&&
+        (isset($cur_cfg['SERVER']))&&
+        (isset($cur_cfg['LOGIN']))&&
+        (isset($cur_cfg['PASSWORD']))){
       $r_con =  @mysql_pconnect($cur_cfg['SERVER'],$cur_cfg['LOGIN'],$cur_cfg['PASSWORD']);
       if($r_con){
+        restore_error_handler();
         $r_db  =  @mysql_select_db($cur_cfg['DB'],$r_con);
-        $vp = mysql_fetch_row(mysql_query("SELECT ".$cur_cfg['VOICE_TABLE'].".password FROM  ".$cur_cfg['VOICE_TABLE'].", ".$cur_cfg['SIP_TABLE']."  WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'"));
-
-        if((isset($vp[0]))&&(!empty($vp[0]))){
-          $this->goFonPINVoice = $vp[0];
+        $query_tmp = "SELECT ".$cur_cfg['SIP_TABLE'].".context,".$cur_cfg['VOICE_TABLE'].".password 
+                      FROM  ".$cur_cfg['VOICE_TABLE'].", ".$cur_cfg['SIP_TABLE']."  
+                      WHERE customer_id = sip_users.mailbox AND name='".$this->uid."'";
+        $res = mysql_query($query_tmp);
+        $vp  = mysql_fetch_assoc($res);
+        @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
+        if((isset($vp['password']))&&(!empty($vp['password']))){
+          $this->goFonPINVoice = $vp['password'];
+        }
+        if((isset($vp['context']))&&(!empty($vp['context']))){
+          $this->context = $vp['context'];
         }
       }
     }
@@ -342,9 +348,8 @@ class phoneAccount extends plugin
 
     $i_is_accounted = false;  // Ensure that extension entry, for name to number is only once in table
 
-    restore_error_handler();
-
     /* Prepare some basic attributes */
+    $oldnums= array();
     foreach($this->a_old_telenums as $tele){
       $oldnums[]= preg_replace("/[^0-9]/","",$tele);
     }
@@ -476,11 +481,12 @@ class phoneAccount extends plugin
        **********************/
 
       /* Check if there is an old entry 
-       * If there is en old entry, get callerid and remove voicemail and extensions too 
+       * If there is an old entry, get callerid and remove voicemail and extensions 
        */
       if($old_connection){
         $query  = "SELECT id,name,callerid FROM ".$a_Remove['SIP_TABLE']." WHERE name='".$this->uid."';";
         $rid    = mysql_query($query,$old_connection);
+        @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
 
         /* Old entry found, remove it */
         $query_a = array();
@@ -494,8 +500,8 @@ class phoneAccount extends plugin
           }
 
           foreach($query_a as $qry){
+                 @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
             if(!mysql_query($qry,$old_connection)){
-              echo $qry;
               echo mysql_error($old_connection);
             } 
           }
@@ -514,7 +520,9 @@ class phoneAccount extends plugin
 
       /* Check if there is already an entry in sip_users for this uid */
       $SQL_query_array = array();
-      $rid = mysql_query("SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n",$new_connection);
+      $query = "SELECT * FROM ".$a_New['SIP_TABLE']." WHERE name='".$this->uid."';\n"; 
+      $rid = mysql_query($query,$new_connection);
+      @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
       if(mysql_affected_rows($new_connection)){
 
         /********************** 
@@ -527,6 +535,7 @@ class phoneAccount extends plugin
         $sip_data_array['type']         = $s_type ;
         $sip_data_array['username']     = $this->uid;
         $sip_data_array['ipaddr']       = $s_ip;
+        $sip_data_array['context']      = $this->context;
 
         /* Remove not changed attributes, to avoid updating table with same values */
         foreach($sip_data_array as $name => $value){
@@ -556,7 +565,7 @@ class phoneAccount extends plugin
         $sip_data_array['amaflags']     = NULL;
         $sip_data_array['callgroup']    = NULL;
         $sip_data_array['canreinvite']  = "no";
-        $sip_data_array['context']      = "default";
+        $sip_data_array['context']      = $this->context;
         $sip_data_array['defaultip']    = NULL;
         $sip_data_array['fromuser']     = NULL;
         $sip_data_array['fromdomain']   = NULL;
@@ -613,10 +622,18 @@ class phoneAccount extends plugin
           "mailbox"     => $customer_id,
           "password"    => $this->goFonVoicemailPIN,
           "fullname"    => $CNname,
+          "context"     => "default"; //$this->context,
           "email"       => $s_mail);
 
+      /* Set pager number if available */
+      if(isset($this->parent->by_object['user']->pager)){
+        $voice_data_array['pager']   = $this->parent->by_object['user']->pager;
+      }
+
       /* Check if there is already an entry in sip_users for this uid */
-      $rid = mysql_query("SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n",$new_connection);
+      $query_tmp = "SELECT * FROM ".$a_New['VOICE_TABLE']." WHERE customer_id='".$customer_id."';\n";
+      $rid = mysql_query($query_tmp,$new_connection);
+      @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query_tmp, "Database query");
       if(mysql_affected_rows($new_connection)){
 
         /********************** 
@@ -645,8 +662,7 @@ class phoneAccount extends plugin
         /********************** 
          * Insert Voice mail entry  
          **********************/
-        $voice_data_array['context'] = "default";
-        $voice_data_array['pager']   = "";
+        $voice_data_array['context'] = "default";//$this->context;
   
         /* There is currently no voice mail entry for this user. 
          * We should create one 
@@ -672,10 +688,14 @@ class phoneAccount extends plugin
       /* Remove old entries */
       $query = array();
       $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$this->uid."\";";
+      foreach($oldnums as $s_telenums){
+        $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
+      }
       foreach($newnums as $s_telenums){
         $query[]= "DELETE FROM ".$a_New['EXT_TABLE']." WHERE exten=\"".$s_telenums."\";";
       }
       foreach($query as $qry){
+        @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$qry, "Database query");
         if(!mysql_query($qry,$new_connection)){
           echo mysql_error($new_connection);
         } 
@@ -695,24 +715,27 @@ class phoneAccount extends plugin
      
       $i = 0; 
       $EXT = array();
-      $EXT[$i]['context'] = 'GOsa';
-      $EXT[$i]['exten']   = $this->uid;
-      $EXT[$i]['priority']= 1;
-      $EXT[$i]['app']     = "Goto";
-      $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
-      $i ++;
+    
+      if(!is_numeric($this->uid)){
+        $EXT[$i]['context'] = "GOsa";//$this->context;
+        $EXT[$i]['exten']   = $this->uid;
+        $EXT[$i]['priority']= 1;
+        $EXT[$i]['app']     = "Goto";
+        $EXT[$i]['appdata'] = $newnums[$i_new_key]."|1";
+        $i ++;
+      }
 
       // Entension entries  Hint / Dial / Goto
       foreach($newnums as $s_telenums){
 
         /* Hint Entry */
-        $EXT[$i]['context'] = 'GOsa';
+        $EXT[$i]['context'] = "GOsa";//$this->context;
         $EXT[$i]['exten']   = $s_telenums;
         $EXT[$i]['priority']= "Hint";
         $EXT[$i]['app']     = 'SIP/'.$this->uid;
         $i ++;  
         /* SetCID */
-        //$EXT[$i]['context'] = 'GOsa';
+        //$EXT[$i]['context'] = "GOsa";//$this->context;
         //$EXT[$i]['exten']   = $s_telenums;
         //$EXT[$i]['priority']= 1;
         //$EXT[$i]['app']     = "SetCIDName";
@@ -730,7 +753,7 @@ class phoneAccount extends plugin
           $s_par = 'SIP/'.$this->uid."|20|r";
         }
 
-        $EXT[$i]['context'] = 'GOsa';
+        $EXT[$i]['context'] = "GOsa";//$this->context;
         $EXT[$i]['exten']   = $s_telenums;
         $EXT[$i]['priority']= 1;
         $EXT[$i]['app']     = $s_app;
@@ -759,6 +782,7 @@ class phoneAccount extends plugin
       // Perform queries ...
       if($this->goFonHardware != "automatic"){
         foreach($SQL_query_array as $query){
+          @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
           if(!@mysql_query($query,$new_connection)){
             print_red(_("Error while performing query:")." ".mysql_error());
             return false;
@@ -771,6 +795,27 @@ class phoneAccount extends plugin
   }
 
 
+  /* Return asterisk contexts 
+   * Additionaly read contexts from file.
+   */
+  function get_asterisk_contexts()
+  {
+    $contexts = array();
+    $contexts[] = "default";
+    $contexts[] = "parkedcalls";
+    $contexts[] = "from-sip";
+    $contexts[] = "from-capi";
+    $file = "/etc/gosa/asterisk_contexts.conf";
+    if(file_exists($file) && is_readable($file)){
+      foreach(file($file) as $context){
+        $contexts[] = trim($context);
+      }
+    }
+    array_unique($contexts);
+    return($contexts);
+  }
+
+
   function execute()
   {
     /* Call parent execute */
@@ -824,7 +869,13 @@ class phoneAccount extends plugin
 
     /* Do we need to flip is_account state? */
     if (isset($_POST['modify_state'])){
-      $this->is_account= !$this->is_account;
+
+      /* Onyl change account state if allowed */
+      if($this->is_account && $this->acl == "#all#"){
+        $this->is_account= !$this->is_account;
+      }elseif(!$this->is_account && chkacl($this->acl,"create") == ""){
+        $this->is_account= !$this->is_account;
+      }
     }
 
     /* Select no macro if, state is empty, this is the case, if the selected macro is no longer available */
@@ -840,6 +891,11 @@ class phoneAccount extends plugin
       print_red(_("The macro you selected, is no longer available for you, please choose another one."));
     }
 
+    /* Assign contexts */
+    $smarty->assign("contexts",$this->get_asterisk_contexts());
+    $smarty->assign("context" ,$this->context);
+    $smarty->assign("goFonContextACL", chkacl($this->acl,"context"));
+
     /* Assing macroselectbox values  */
     $smarty->assign("macros",$this->macros);   
     $smarty->assign("macro", $this->macro);   
@@ -968,12 +1024,12 @@ class phoneAccount extends plugin
 
     /* Add phone number */
     if (isset($_POST["add_phonenumber"]) && $_POST['phonenumber']){
-      if (is_phone_nr($_POST['phonenumber'])){
+      if (is_phone_nr($_POST['phonenumber']) && strlen($_POST['phonenumber']) <=10){
         $number= $_POST["phonenumber"];
         $this->phoneNumbers[$number]= $number;
         $this->is_modified= TRUE;
       } else {
-        print_red(_("Please enter a valid phone number!"));
+        print_red(_("Please enter a valid phone number! Because of the realtime extension tables, the number must be less than 11 digits."));
       }
     }
 
@@ -1039,6 +1095,7 @@ class phoneAccount extends plugin
   function save_object()
   {
     if (isset($_POST["phoneTab"])){
+    
       plugin::save_object();
 
       /* Save checkbox */
@@ -1059,6 +1116,18 @@ class phoneAccount extends plugin
         $this->macrostillavailable=true;
       }
 
+      /* Save context */
+      if(isset($_POST['context'])){
+        if($this->context != $_POST['context']){
+          $this->is_modified= TRUE;
+        }
+        $this->context= $_POST['context'];
+      }
+
+      if(isset($_POST['macro']) && $_POST['macro'] != $this->macro){
+        $this->is_modified =true;
+      }
+
       if(is_array($this->phoneNumbers)){
         foreach($this->phoneNumbers as $telenumms) {
           $nummsinorder[]=$telenumms; 
@@ -1068,8 +1137,12 @@ class phoneAccount extends plugin
       }
 
       /* get all Postvars */
-      if(isset($this->macroarray[$this->macro])){ 
+      if(isset($this->macroarray[$this->macro])){
         foreach($this->macroarray[$this->macro] as $key => $paras){
+
+          $backup = $this->macroarray[$this->macro][$key];  
+
           if(isset($_POST[$paras['var']])){
             $this->macroarray[$this->macro][$key]['choosen'] = $_POST[$paras['var']];
           }
@@ -1087,6 +1160,9 @@ class phoneAccount extends plugin
               }
             }
           }
+          if(count(array_diff($this->macroarray[$this->macro][$key],$backup))){
+            $this->modified = TRUE;
+          }
         }
       }
     }
@@ -1113,16 +1189,14 @@ class phoneAccount extends plugin
       }
     }
 
-    if((strlen($this->goFonPIN)<=0)){
-      $message[]=(_("Phone PIN must be at least one character long."));
-    }else{
-      if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
-        $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
-      }
+    if(preg_match("/[^0-9a-z]/i",$this->goFonPIN)){
+      $message[]=(_("The specified phone PIN contains invalid characters, only aphanumeric values are allowed here."));
     }
 
-    if(!$this->generate_mysql_entension_entries()){
-      $message[] = $this->generate_error;
+    if ($this->initially_was_account != $this->is_account || $this->is_modified){
+      if(!$this->generate_mysql_entension_entries()){
+        $message[] = $this->generate_error;
+      }
     }
 
     /* We need at least one phone number */
@@ -1147,6 +1221,16 @@ class phoneAccount extends plugin
   {
     plugin::save();
 
+    /* Force saving macro again 
+     * This ensures that 
+     *  - the macro is available on the destiantion server.
+     *  - the macro saved is up to date on the destination server.
+     */
+    if(!empty($this->macro) && $this->macro != "none")  {
+      $macro_tab = new macrotabs($this->config,$this->config->data['TABS']['MACROTABS'], $this->macro);
+      $macro_tab -> save();
+    }
+
     /* Save arrays */
     $tmp_numbers = array();
     foreach ($this->phoneNumbers as $number){
@@ -1168,7 +1252,12 @@ class phoneAccount extends plugin
 
     $this->attrs['goFonForwarding']=array();
 
-    $this->generate_mysql_entension_entries(true);
+    if ($this->initially_was_account != $this->is_account || $this->is_modified){
+      $str = $this->generate_mysql_entension_entries(true);
+      if(empty($str)){
+        print_red($str);
+      }
+    }
 
     if($this->attrs['goFonMacro']==""){
       $this->attrs['goFonMacro']=array();
@@ -1276,6 +1365,7 @@ class phoneAccount extends plugin
       $SQL[] = "DELETE FROM ".$a_SETUP['SIP_TABLE']." WHERE name='".$this->uid."';\n";
 
       foreach($SQL as $query){
+        @DEBUG (DEBUG_MYSQL, __LINE__, __FUNCTION__, __FILE__,$query, "Database query");
         if(!@mysql_query($query,$r_con)){
           print_red(_("Stop".mysql_error()));
           return false;
@@ -1308,14 +1398,14 @@ class phoneAccount extends plugin
 
     $ldap= $this->config->get_ldap_link();
     $ldap->cd($this->config->current['BASE']);
-    $ldap->search("(objectClass=goFonQueue)", array("member"));
+    $ldap->search("(&(objectClass=goFonQueue)(member=*))", array("member"));
     while($attr = $ldap->fetch()){
       if(in_array($this->dn,$attr['member'])){
         $new =new ogrouptabs($this->config, $this->config->data['TABS']['OGROUPTABS'],$attr['dn']);
         unset($new->by_object['ogroup']->memberList[$this->dn]);
         unset($new->by_object['ogroup']->member[$this->dn]);
         $new->save();
-        print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->attrs['cn']));
+        print_red(sprintf(_("Removed user '%s' from phone queue '%s'."),$this->uid,$new->by_object['ogroup']->cn));
       }
     }
     $ldap->cd($this->dn);
@@ -1393,6 +1483,15 @@ class phoneAccount extends plugin
       $this->goFonPIN = $_POST['goFonPIN'];
     }
   }
+
+
+  function allow_remove()
+  {
+    /* Check if previously selected server is still available */
+    if($this->initially_was_account && !isset($this->goFonHomeServers[$this->goFonHomeServer])){
+      return sprintf(_("The previously selected asterisk home server (%s) is no longer available. Remove aborted."),preg_replace("/,/",", ",$this->goFonHomeServer));
+    }
+  }
 }
 
 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler: