DataObjects/Core_notify_recur.php
[Pman.Core] / DataObjects / Person.php
index 6f9cf21..d5e8446 100644 (file)
@@ -32,23 +32,36 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     
     /* the code above is auto generated do not remove the tag below */
     ###END_AUTOCODE
-    
+    /**
+     *
+     * @param {String} $templateFile  (mail/XXXXXXX.txt) exclude the mail and .txt bit.
+     * @param {Array|Object} $args   data to send out..
+     * @return {Array|PEAR_Error} array of $recipents, $header, $body 
+     */
     function buildMail($templateFile, $args)
     {
           
-        
+        $args = (array) $args;
         $content  = clone($this);
         
         foreach((array)$args as $k=>$v) {
             $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");
@@ -64,7 +77,8 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         /* use the regex compiler, as it doesnt parse <tags */
         require_once 'HTML/Template/Flexy.php';
         $template = new HTML_Template_Flexy( array(
-            'compiler'    => 'Regex',
+            'compiler'    => 'Flexy',
+            'nonHTML' => true,
             'filters' => array('SimpleTags','Mail'),
             //     'debug'=>1,
         ));
@@ -77,7 +91,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';
@@ -94,18 +108,13 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         if (!empty($content->bcc) && is_array($content->bcc)) {
             $recipents =array_merge($recipents, $content->bcc);
         }
-        //print_r($recipents);exit;
-        $mailOptions = PEAR::getStaticProperty('Mail','options');
-        $mail = Mail::factory("SMTP",$mailOptions);
         $headers['Date'] = date('r');
-        if (PEAR::isError($mail)) {
-            return $mail;
-        } 
-        $oe = error_reporting(E_ALL ^ E_NOTICE);
-        $ret = $mail->send($recipents,$headers,$body);
-        error_reporting($oe);
-       
-        return $ret;
+        
+        return array(
+            'recipients' => $recipents,
+            'headers'    => $headers,
+            'body'      => $body
+        );
         
         
     }
@@ -120,73 +129,27 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
     function sendTemplate($templateFile, $args)
     {
         
+        $ar = $this->buildMail($templateFile, $args);
+      
         
-        
-        $content  = clone($this);
-        
-        foreach((array)$args as $k=>$v) {
-            $content->$k = $v;
-        }
-        
-        if (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");
-            }
-        }
-        
-        $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
-        /* use the regex compiler, as it doesnt parse <tags */
-        require_once 'HTML/Template/Flexy.php';
-        $template = new HTML_Template_Flexy( array(
-                 'compiler'    => 'Regex',
-                 'filters' => array('SimpleTags','Mail'),
-            //     'debug'=>1,
-            ));
-        
-     
-         
-        
-        $template->compile("mail/$templateFile.txt");
-        
-        /* use variables from this object to ouput data. */
-        $mailtext = $template->bufferedOutputObject($content);
-        //echo "<PRE>";print_R($mailtext);
-        
-        /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
-        require_once 'Mail/mimeDecode.php';
-        require_once 'Mail.php';
-        
-        $decoder = new Mail_mimeDecode($mailtext);
-        $parts = $decoder->getSendArray();
-        if (PEAR::isError($parts)) {
-            return $parts;
-            //echo "PROBLEM: {$parts->message}";
-            //exit;
-        } 
-        list($recipents,$headers,$body) = $parts;
-        $recipents = array($this->email);
-        if (!empty($content->bcc) && is_array($content->bcc)) {
-            $recipents =array_merge($recipents, $content->bcc);
-        }
         //print_r($recipents);exit;
         $mailOptions = PEAR::getStaticProperty('Mail','options');
         $mail = Mail::factory("SMTP",$mailOptions);
-        $headers['Date'] = date('r');
+        
         if (PEAR::isError($mail)) {
             return $mail;
         } 
-        $oe = error_reporting(E_ALL ^ E_NOTICE);
-        $ret = $mail->send($recipents,$headers,$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 . '>';
@@ -210,11 +173,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();
@@ -234,12 +203,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');
@@ -262,7 +246,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']);
             
@@ -287,8 +272,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);
         
     }
@@ -296,7 +293,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'] = "";
         
     }    
@@ -328,6 +325,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         }
         $this->passwd = crypt($value, '$1$'. $salt. '$');
        
+       
     }      
     
     function company()
@@ -336,7 +334,10 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         $x->get($this->company_id);
         return $x;
     }
-    
+    function loadCompany()
+    {
+        $this->company = $this->company();
+    }
     
     function active()
     {
@@ -390,6 +391,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)) {
                     
@@ -428,8 +430,9 @@ 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.
         }
-        
+        //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');
@@ -446,7 +449,7 @@ class Pman_Core_DataObjects_Person extends DB_DataObject
         
         $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..
@@ -461,15 +464,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');
         $grps = $g->listGroupMembership($this);
         $g = DB_DataObject::Factory('Groups');
         $g->whereAddIn('id', $grps, 'int');
-        return $g->fetchAll();
+        return $g->fetchAll($what);
         
     }
     
@@ -491,14 +495,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
@@ -527,24 +546,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
                     )");
                }
@@ -564,14 +587,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'])) {
@@ -579,9 +619,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'])) {
@@ -595,10 +635,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%' 
                         
                     ");
         }
@@ -702,20 +742,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;