Merge branch 'master' of http://git.roojs.com:8081/Pman.Core
[Pman.Core] / DataObjects / Person.php
index 7d9200c..3ab74eb 100644 (file)
@@ -11,21 +11,28 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
 
     public $__table = 'Person';                          // table name
     public $id;                              // int(11)  not_null primary_key auto_increment
+    public $email;                           // string(128)  not_null
+    
+    public $company_id;                      // int(11)  
     public $office_id;                       // int(11)  
+    
     public $name;                            // string(128)  not_null
+    public $firstname;                            // string(128)  not_null
+    public $lastname;                            // string(128)  not_null
     public $phone;                           // string(32)  not_null
     public $fax;                             // string(32)  not_null
-    public $email;                           // string(128)  not_null
-    public $company_id;                      // int(11)  
+    
     public $role;                            // string(32)  not_null
-    public $active;                          // int(11)  not_null
     public $remarks;                         // blob(65535)  not_null blob
     public $passwd;                          // string(64)  not_null
     public $owner_id;                        // int(11)  not_null
     public $lang;                            // string(8)  
     public $no_reset_sent;                   // int(11)  
     public $action_type;                     // string(32)  
-    public $project_id;                      // int(11)  
+    public $project_id;                      // int(11)
+
+    
+    public $active;                          // int(11)  not_null
     public $deleted_by;                      // int(11)  not_null
     public $deleted_dt;                      // datetime(19)  binary
 
@@ -48,12 +55,20 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             $content->$k = $v;
         }
         
+        $ff = HTML_FlexyFramework::get();
+        
+        
         //?? is this really the place for this???
-        if (empty($args['no_auth']) && !in_array($templateFile, array(
-           // templates that can be sent without authentication.
-            'password_reset' ,
-            'password_welcome'
-            ))) {
+        if (
+                !$ff->cli && 
+                empty($args['no_auth']) &&
+                !in_array($templateFile, array(
+                    // templates that can be sent without authentication.
+                     'password_reset' ,
+                     'password_welcome'
+                 ))
+            ) {
+            
             $content->authUser = $this->getAuthUser();
             if (!$content->authUser) {
                 return PEAR::raiseError("Not authenticated");
@@ -67,12 +82,22 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
             
         /* use the regex compiler, as it doesnt parse <tags */
-        require_once 'HTML/Template/Flexy.php';
-        $template = new HTML_Template_Flexy( array(
-            'compiler'    => 'Regex',
+        
+        $tops = array(
+            'compiler'    => 'Flexy',
+            'nonHTML' => true,
             'filters' => array('SimpleTags','Mail'),
             //     'debug'=>1,
-        ));
+        );
+        
+        
+        
+        if (!empty($args['templateDir'])) {
+            $tops['templateDir'] = $args['templateDir'];
+        }
+        
+        require_once 'HTML/Template/Flexy.php';
+        $template = new HTML_Template_Flexy( $tops );
         
      
          
@@ -82,7 +107,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         /* use variables from this object to ouput data. */
         $mailtext = $template->bufferedOutputObject($content);
         //echo "<PRE>";print_R($mailtext);
-        
+        //print_R($mailtext);exit;
         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
         require_once 'Mail/mimeDecode.php';
         require_once 'Mail.php';
@@ -102,8 +127,8 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         $headers['Date'] = date('r');
         
         return array(
-            'recipents' => $recipents,
-            'headers'    => $header,
+            'recipients' => $recipents,
+            'headers'    => $headers,
             'body'      => $body
         );
         
@@ -121,7 +146,8 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     {
         
         $ar = $this->buildMail($templateFile, $args);
-         
+      
+        
         //print_r($recipents);exit;
         $mailOptions = PEAR::getStaticProperty('Mail','options');
         $mail = Mail::factory("SMTP",$mailOptions);
@@ -129,13 +155,17 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         if (PEAR::isError($mail)) {
             return $mail;
         } 
-        $oe = error_reporting(E_ALL ^ E_NOTICE);
-        $ret = $mail->send($ar['recipents'],$ar['headers'],$ar['body']);
+        $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
+        $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
         error_reporting($oe);
        
         return $ret;
     
     }
+    
+  
+    
+    
     function getEmailFrom()
     {
         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
@@ -159,11 +189,17 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     function isAuth()
     {
         $db = $this->getDatabaseConnection();
-        $sesPrefix = $db->dsn['database'];
+        // we combine db + project names,
+        // otherwise if projects use different 'auth' objects
+        // then we get unserialize issues.
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
+        
+        
         @session_start();
         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
             // in session...
             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
+            
             $u = DB_DataObject::factory('Person');
             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
                 $u->verifyAuth();
@@ -183,12 +219,27 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
             $u->get('email', $ff->Pman['local_autoauth'])
         ) {
-            $db = $this->getDatabaseConnection();
-            $sesPrefix = $db->dsn['database'];
             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
             return true;
         }
            
+        // http basic auth..
+        $u = DB_DataObject::factory('Person');
+
+        if (!empty($_SERVER['PHP_AUTH_USER']) 
+            &&
+            !empty($_SERVER['PHP_AUTH_PW'])
+            &&
+            $u->get('email', $_SERVER['PHP_AUTH_USER'])
+            &&
+            $u->checkPassword($_SERVER['PHP_AUTH_PW'])
+           ) {
+            $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
+            return true; 
+        }
+        
+        
+        
         
         // not in session or not matched...
         $u = DB_DataObject::factory('Person');
@@ -211,7 +262,8 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             return false;
         }
         $db = $this->getDatabaseConnection();
-        $sesPrefix = $db->dsn['database'];
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
+        
         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
             
@@ -236,8 +288,20 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     {
         $this->isAuth(); // force session start..
         $this->verifyAuth();
-         $db = $this->getDatabaseConnection();
-        $sesPrefix = $db->dsn['database'];
+        $db = $this->getDatabaseConnection();
+        // refresh admin group if we are logged in as one..
+        //DB_DataObject::debugLevel(1);
+        $g = DB_DataObject::factory('Groups');
+        $g->type = 0;
+        $g->get('name', 'Administrators');
+        $gm = DB_DataObject::Factory('group_members');
+        if (in_array($g->id,$gm->listGroupMembership($this))) {
+            // refresh admin groups.
+            $gr = DB_DataObject::Factory('group_rights');
+            $gr->applyDefs($g, 0);
+        }
+             
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
         
     }
@@ -245,7 +309,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     {
         $this->isAuth(); // force session start..
          $db = $this->getDatabaseConnection();
-        $sesPrefix = $db->dsn['database'];
+        $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
         
     }    
@@ -277,6 +341,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         }
         $this->passwd = crypt($value, '$1$'. $salt. '$');
        
+       
     }      
     
     function company()
@@ -285,10 +350,13 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         $x->get($this->company_id);
         return $x;
     }
-    
+    function loadCompany()
+    {
+        $this->company = $this->company();
+    }
     
     function active()
-    {
+    { 
         return $this->active;
     }
     function authUserName($n) // set username prior to acheck user exists query.
@@ -339,6 +407,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             $im->onid = $c->id;
             $im->imgtype = 'LOGO';
             $im->limit(1);
+            $im->selectAdd();
             $im->selectAs($im,  'company_id_logo_id_%s');
             if ($im->find(true)) {
                     
@@ -350,7 +419,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
       
         // perms + groups.
         $aur['perms']  = $this->getPerms();
-        $g = DB_DataObject::Factory('Group_Members');
+        $g = DB_DataObject::Factory('group_members');
         $aur['groups']  = $g->listGroupMembership($this, 'name');
         
         $aur['passwd'] = '';
@@ -369,7 +438,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         
         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
         
-        $g = DB_DataObject::Factory('Group_Rights');
+        $g = DB_DataObject::Factory('group_rights');
         if (!$g->count()) {
             $g->genDefault();
         }
@@ -377,13 +446,14 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         if ($this->id < 0) {
             return $g->adminRights(); // system is not set up - so they get full rights.
         }
-        
-        $g = DB_DataObject::Factory('Group_Members');
+        //DB_DataObject::debugLevel(1);
+        $g = DB_DataObject::Factory('group_members');
+        $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
         if (!$g->count()) {
             // add the current user to the admin group..
             $g = DB_DataObject::Factory('Groups');
             if ($g->get('name', 'Administrators')) {
-                $gm = DB_DataObject::Factory('Group_Members');
+                $gm = DB_DataObject::Factory('group_members');
                 $gm->group_id = $g->id;
                 $gm->user_id = $this->id;
                 $gm->insert();
@@ -392,16 +462,16 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         }
         
         // ------ STANDARD PERMISSION HANDLING.
-        
-        $g = DB_DataObject::Factory('Group_Members');
+        $isOwner = $this->company()->comptype == 'OWNER';
+        $g = DB_DataObject::Factory('group_members');
         $grps = $g->listGroupMembership($this);
-       // print_r($grps);
+       //var_dump($grps);
         $isAdmin = $g->inAdmin;
         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
         // the load all the perms for those groups, and add them all together..
         // then load all those 
-        $g = DB_DataObject::Factory('Group_Rights');
-        $ret =  $g->listPermsFromGroupIds($grps, $isAdmin);
+        $g = DB_DataObject::Factory('group_rights');
+        $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
         //echo '<PRE>';print_r($ret);
         return $ret;
          
@@ -410,15 +480,16 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     /**
      *Basic group fetching - probably needs to filter by type eventually.
      *
+     *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
      */
     
-    function groups()
+    function groups($what=false)
     {
-        $g = DB_DataObject::Factory('Group_Members');
+        $g = DB_DataObject::Factory('group_members');
         $grps = $g->listGroupMembership($this);
         $g = DB_DataObject::Factory('Groups');
         $g->whereAddIn('id', $grps, 'int');
-        return $g->fetchAll();
+        return $g->fetchAll($what);
         
     }
     
@@ -440,14 +511,29 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     }    
     
     //  ------------ROO HOOKS------------------------------------
-    function applyFilters($q, $au)
+    function applyFilters($q, $au, $roo)
     {
+        //DB_DataObject::DebugLevel(1);
         if (!empty($q['query']['person_not_internal'])) {
             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
         }
+        
+        
         if (!empty($q['query']['person_internal_only_all'])) {
+            
+            
             // must be internal and not current user (need for distribution list)
-            $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
+            // user has a projectdirectory entry and role is not blank.
+            //DB_DataObject::DebugLevel(1);
+            $pd = DB_DataObject::factory('ProjectDirectory');
+            $pd->whereAdd("role != ''");
+            $pd->selectAdd();
+            $pd->selectAdd('distinct(person_id) as person_id');
+            $roled = $pd->fetchAll('person_id');
+            $rs = $roled  ? "  OR
+                    {$this->tableName()}.id IN (".implode(',', $roled) . ") 
+                    " : '';
+            $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
             
         }
         // -- for distribution
@@ -476,24 +562,28 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
            // DB_Dataobject::debugLevel(1);
             $this->active = 1;
         }
-        
+        $tn_p = $this->tableName();
+        $tn_gm = DB_DataObject::Factory('group_members')->tableName();
+        $tn_g = DB_DataObject::Factory('Groups')->tableName();
+
         ///---------------- Group views --------
         if (!empty($q['query']['in_group'])) {
             // DB_DataObject::debugLevel(1);
             $ing = (int) $q['query']['in_group'];
             if ($q['query']['in_group'] == -1) {
+             
                 // list all staff who are not in a group.
                 $this->whereAdd("Person.id NOT IN (
-                    SELECT distinct(user_id) FROM Group_Members LEFT JOIN
-                        Groups ON Groups.id = Group_Members.group_id
-                        WHERE Groups.type = ".$q['query']['type']."
+                    SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
+                        $tn_g ON $tn_g.id = $tn_gm.group_id
+                        WHERE $tn_g.type = ".$q['query']['type']."
                     )");
                 
                 
             } else {
                 
-                $this->whereAdd("Person.id IN (
-                    SELECT distinct(user_id) FROM Group_Members 
+                $this->whereAdd("$tn_p.id IN (
+                    SELECT distinct(user_id) FROM $tn_gm
                         WHERE group_id = $ing
                     )");
                }
@@ -513,14 +603,31 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             }
             
             
+
             if ( $q['query']['not_in_directory'] > -1) {
+                $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
                 // can list current - so that it does not break!!!
-                $x->whereAdd('Person.id NOT IN 
-                    ( SELECT distinct person_id FROM ProjectDirectory WHERE
-                        project_id = ' . $q['query']['not_in_directory'] . ' AND 
-                        company_id = ' . $this->company_id . ')');
+                $this->whereAdd("$tn_p.id NOT IN 
+                    ( SELECT distinct person_id FROM $tn_pd WHERE
+                        project_id = " . $q['query']['not_in_directory'] . " AND 
+                        company_id = " . $this->company_id . ')');
             }
         }
+           
+        if (!empty($q['query']['role'])) { 
+            // it's a Person list..
+            // DB_DATaobjecT::debugLevel(1);
+            
+            // specific to project directory which is single comp. login
+            //
+            $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
+                // can list current - so that it does not break!!!
+            $this->whereAdd("$tn_p.id IN 
+                    ( SELECT distinct person_id FROM $tn_pd WHERE
+                        role = '". $this->escape($q['query']['role']) ."'
+            )");
+        
+        }
         
         
         if (!empty($q['query']['project_member_of'])) {
@@ -528,9 +635,9 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             //DB_DataObject::debugLevel(1);
             $do = DB_DataObject::factory('ProjectDirectory');
             $do->project_id = $q['query']['project_member_of'];
-            
+            $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
-            $this->selectAdd('IF(ProjectDirectory.id IS NULL, 0,  ProjectDirectory.id )  as is_member');
+            $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
                 
                 
             if (!empty($q['query']['project_member_filter'])) {
@@ -544,10 +651,10 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         if (!empty($q['query']['search'])) {
             $s = $this->escape($q['query']['search']);
                     $this->whereAdd("
-                        Person.name LIKE '%$s%'  OR
-                        Person.email LIKE '%$s%'  OR
-                        Person.role LIKE '%$s%'  OR
-                        Person.remarks LIKE '%$s%' 
+                        $tn_p.name LIKE '%$s%'  OR
+                        $tn_p.email LIKE '%$s%'  OR
+                        $tn_p.role LIKE '%$s%'  OR
+                        $tn_p.remarks LIKE '%$s%' 
                         
                     ");
         }
@@ -651,20 +758,11 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             // extra case change passwod?
             case 'P': //??? password
                 // standard perms -- for editing + if the user is dowing them selves..
-                $ret = $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
+                $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
                 return $ret || $au->id == $this->id;
             
-            case 'S': // list..
-                return $au->hasPerm("Core.Person", "S");
-            
-            case 'E': // edit
-                return $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
-            
-            case 'A': // add
-                return $isStaff ? $au->hasPerm("Core.Person", "A") : $au->hasPerm("Core.Staff", "A");
-            
-            case 'D': // add
-                return $isStaff ? $au->hasPerm("Core.Person", "D") : $au->hasPerm("Core.Staff", "D");
+            default:                
+                return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
         
         }
         return false;
@@ -677,7 +775,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
             $g->type = 0;
             $g->get('name', 'Administrators');
             
-            $p = DB_DataObject::factory('Group_Members');
+            $p = DB_DataObject::factory('group_members');
             $p->group_id = $g->id;
             $p->user_id = $this->id;     
             if (!$p->count()) {