DataObjects/Person.php
[Pman.Core] / DataObjects / Person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Person extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'Person';                          // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $office_id;                       // int(11)  
15     public $name;                            // string(128)  not_null
16     public $phone;                           // string(32)  not_null
17     public $fax;                             // string(32)  not_null
18     public $email;                           // string(128)  not_null
19     public $company_id;                      // int(11)  
20     public $role;                            // string(32)  not_null
21     public $active;                          // int(11)  not_null
22     public $remarks;                         // blob(65535)  not_null blob
23     public $passwd;                          // string(64)  not_null
24     public $owner_id;                        // int(11)  not_null
25     public $lang;                            // string(8)  
26     public $no_reset_sent;                   // int(11)  
27     public $action_type;                     // string(32)  
28     public $project_id;                      // int(11)  
29     public $deleted_by;                      // int(11)  not_null
30     public $deleted_dt;                      // datetime(19)  binary
31
32     
33     /* the code above is auto generated do not remove the tag below */
34     ###END_AUTOCODE
35     /**
36      *
37      * @param {String} $templateFile  (mail/XXXXXXX.txt) exclude the mail and .txt bit.
38      * @param {Array|Object} $args   data to send out..
39      * @return {Array|PEAR_Error} array of $recipents, $header, $body 
40      */
41     function buildMail($templateFile, $args)
42     {
43           
44         $args = (array) $args;
45         $content  = clone($this);
46         
47         foreach((array)$args as $k=>$v) {
48             $content->$k = $v;
49         }
50         
51         $ff = HTML_FlexyFramework::get();
52         
53         
54         //?? is this really the place for this???
55         if (
56                 !$ff->cli && 
57                 empty($args['no_auth']) &&
58                 !in_array($templateFile, array(
59                     // templates that can be sent without authentication.
60                      'password_reset' ,
61                      'password_welcome'
62                  ))
63             ) {
64             
65             $content->authUser = $this->getAuthUser();
66             if (!$content->authUser) {
67                 return PEAR::raiseError("Not authenticated");
68             }
69         }
70         
71         // should handle x-forwarded...
72         
73         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
74             $_SERVER["HTTP_HOST"] :
75             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
76             
77         /* use the regex compiler, as it doesnt parse <tags */
78         require_once 'HTML/Template/Flexy.php';
79         $template = new HTML_Template_Flexy( array(
80             'compiler'    => 'Flexy',
81             'nonHTML' => true,
82             'filters' => array('SimpleTags','Mail'),
83             //     'debug'=>1,
84         ));
85         
86      
87          
88         
89         $template->compile("mail/$templateFile.txt");
90         
91         /* use variables from this object to ouput data. */
92         $mailtext = $template->bufferedOutputObject($content);
93         //echo "<PRE>";print_R($mailtext);
94         //print_R($mailtext);exit;
95         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
96         require_once 'Mail/mimeDecode.php';
97         require_once 'Mail.php';
98         
99         $decoder = new Mail_mimeDecode($mailtext);
100         $parts = $decoder->getSendArray();
101         if (PEAR::isError($parts)) {
102             return $parts;
103             //echo "PROBLEM: {$parts->message}";
104             //exit;
105         } 
106         list($recipents,$headers,$body) = $parts;
107         $recipents = array($this->email);
108         if (!empty($content->bcc) && is_array($content->bcc)) {
109             $recipents =array_merge($recipents, $content->bcc);
110         }
111         $headers['Date'] = date('r');
112         
113         return array(
114             'recipents' => $recipents,
115             'headers'    => $headers,
116             'body'      => $body
117         );
118         
119         
120     }
121     
122     
123     /**
124      * send a template
125      * - user must be authenticate or args[no_auth] = true
126      *   or template = password_[reset|welcome]
127      * 
128      */
129     function sendTemplate($templateFile, $args)
130     {
131         
132         $ar = $this->buildMail($templateFile, $args);
133          
134         //print_r($recipents);exit;
135         $mailOptions = PEAR::getStaticProperty('Mail','options');
136         $mail = Mail::factory("SMTP",$mailOptions);
137         
138         if (PEAR::isError($mail)) {
139             return $mail;
140         } 
141         $oe = error_reporting(E_ALL ^ E_NOTICE);
142         $ret = $mail->send($ar['recipents'],$ar['headers'],$ar['body']);
143         error_reporting($oe);
144        
145         return $ret;
146     
147     }
148     function getEmailFrom()
149     {
150         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
151     }
152     function toEventString() 
153     {
154         return empty($this->name) ? $this->email : $this->name;
155     } 
156     function verifyAuth()
157     { 
158         $ff= HTML_FlexyFramework::get();
159         if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
160             $ff->page->jerr("Login not permited to outside companies");
161         }
162         return true;
163         
164     }    
165    
166    
167     //   ---------------- authentication / passwords and keys stuff  ----------------
168     function isAuth()
169     {
170         $db = $this->getDatabaseConnection();
171         // we combine db + project names,
172         // otherwise if projects use different 'auth' objects
173         // then we get unserialize issues.
174         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
175         
176         
177         @session_start();
178         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
179             // in session...
180             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
181             
182             $u = DB_DataObject::factory('Person');
183             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
184                 $u->verifyAuth();
185                 
186                 return true;
187             }
188             
189             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
190             
191         }
192         // local auth - 
193         $u = DB_DataObject::factory('Person');
194         $ff = HTML_FlexyFramework::get();
195         if (!empty($ff->Pman['local_autoauth']) && 
196             (!empty($_SERVER['SERVER_ADDR'])) &&
197             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
198             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
199             $u->get('email', $ff->Pman['local_autoauth'])
200         ) {
201             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
202             return true;
203         }
204            
205         
206         // not in session or not matched...
207         $u = DB_DataObject::factory('Person');
208         $u->whereAdd(' LENGTH(passwd) > 0');
209         $n = $u->count();
210         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
211         if ($error) {
212             die($error->toString()); // not really a good thing to do...
213         }
214         if (!$n){ // authenticated as there are no users in the system...
215             return true;
216         }
217         
218         return false;
219         
220     }
221     function getAuthUser()
222     {
223         if (!$this->isAuth()) {
224             return false;
225         }
226         $db = $this->getDatabaseConnection();
227         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
228         
229         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
230             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
231             
232             $u = DB_DataObject::factory('Person');
233             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
234                 return clone($u);
235             }
236              
237         }
238         
239         $u = DB_DataObject::factory('Person');
240         $u->whereAdd(' LENGTH(passwd) > 0');
241         if (!$u->count()){
242             $u = DB_DataObject::factory('Person');
243             $u->id = -1;
244             return $u;
245             
246         }
247         return false;
248     }     
249     function login()
250     {
251         $this->isAuth(); // force session start..
252         $this->verifyAuth();
253         $db = $this->getDatabaseConnection();
254         // refresh admin group if we are logged in as one..
255         //DB_DataObject::debugLevel(1);
256         $g = DB_DataObject::factory('Groups');
257         $g->type = 0;
258         $g->get('name', 'Administrators');
259         $gm = DB_DataObject::Factory('Group_Members');
260         if (in_array($g->id,$gm->listGroupMembership($this))) {
261             // refresh admin groups.
262             $gr = DB_DataObject::Factory('Group_Rights');
263             $gr->applyDefs($g, 0);
264         }
265              
266         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
267         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
268         
269     }
270     function logout()
271     {
272         $this->isAuth(); // force session start..
273          $db = $this->getDatabaseConnection();
274         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
275         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
276         
277     }    
278     function genPassKey ($t) 
279     {
280         return md5($this->email . $t. $this->passwd);
281     }
282     function simpleAuthKey($m = 0)
283     {
284         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
285         
286         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
287     } 
288     function checkPassword($val)
289     {
290         
291         if (substr($this->passwd,0,1) == '$') {
292             return crypt($val,$this->passwd) == $this->passwd ;
293         }
294         // old style md5 passwords...- cant be used with courier....
295         return md5($val) == $this->passwd;
296     }
297     function setPassword($value) 
298     {
299         $salt='';
300         while(strlen($salt)<9) {
301             $salt.=chr(rand(64,126));
302             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
303         }
304         $this->passwd = crypt($value, '$1$'. $salt. '$');
305        
306        
307     }      
308     
309     function company()
310     {
311         $x = DB_DataObject::factory('Companies');
312         $x->get($this->company_id);
313         return $x;
314     }
315     
316     
317     function active()
318     {
319         return $this->active;
320     }
321     function authUserName($n) // set username prior to acheck user exists query.
322     {
323         
324         $this->whereAdd('LENGTH(passwd) > 1'); 
325         $this->email = $n;
326     }
327     function lang($val)
328     {
329         if ($val == $this->lang) {
330             return;
331         }
332         $uu = clone($this);
333         $this->lang = $val;
334         $this->update($uu);
335
336     }
337             
338     
339     function authUserArray()
340     {
341         
342         $aur = $this->toArray();
343         
344         if ($this->id < 1) {
345             return $aur;
346         }
347         
348         
349         //DB_DataObject::debugLevel(1);
350         $c = DB_Dataobject::factory('Companies');
351         $im = DB_Dataobject::factory('Images');
352         $c->joinAdd($im, 'LEFT');
353         $c->selectAdd();
354         $c->selectAs($c, 'company_id_%s');
355         $c->selectAs($im, 'company_id_logo_id_%s');
356         $c->id = $this->company_id;
357         $c->limit(1);
358         $c->find(true);
359         
360         $aur = array_merge( $c->toArray(),$aur);
361         
362         if (empty($c->company_id_logo_id_id))  {
363                  
364             $im = DB_Dataobject::factory('Images');
365             $im->ontable = 'Companies';
366             $im->onid = $c->id;
367             $im->imgtype = 'LOGO';
368             $im->limit(1);
369             $im->selectAdd();
370             $im->selectAs($im,  'company_id_logo_id_%s');
371             if ($im->find(true)) {
372                     
373                 foreach($im->toArray() as $k=>$v) {
374                     $aur[$k] = $v;
375                 }
376             }
377         }
378       
379         // perms + groups.
380         $aur['perms']  = $this->getPerms();
381         $g = DB_DataObject::Factory('Group_Members');
382         $aur['groups']  = $g->listGroupMembership($this, 'name');
383         
384         $aur['passwd'] = '';
385         $aur['dailykey'] = '';
386         
387         
388         
389         return $aur;
390     }
391     
392     //   ----------PERMS------  ----------------
393     function getPerms() 
394     {
395          //DB_DataObject::debugLevel(1);
396         // find out all the groups they are a member of.. + Default..
397         
398         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
399         
400         $g = DB_DataObject::Factory('Group_Rights');
401         if (!$g->count()) {
402             $g->genDefault();
403         }
404         
405         if ($this->id < 0) {
406             return $g->adminRights(); // system is not set up - so they get full rights.
407         }
408         //DB_DataObject::debugLevel(1);
409         $g = DB_DataObject::Factory('Group_Members');
410         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
411         if (!$g->count()) {
412             // add the current user to the admin group..
413             $g = DB_DataObject::Factory('Groups');
414             if ($g->get('name', 'Administrators')) {
415                 $gm = DB_DataObject::Factory('Group_Members');
416                 $gm->group_id = $g->id;
417                 $gm->user_id = $this->id;
418                 $gm->insert();
419             }
420             
421         }
422         
423         // ------ STANDARD PERMISSION HANDLING.
424         
425         $g = DB_DataObject::Factory('Group_Members');
426         $grps = $g->listGroupMembership($this);
427        //var_dump($grps);
428         $isAdmin = $g->inAdmin;
429         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
430         // the load all the perms for those groups, and add them all together..
431         // then load all those 
432         $g = DB_DataObject::Factory('Group_Rights');
433         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin);
434         //echo '<PRE>';print_r($ret);
435         return $ret;
436          
437         
438     }
439     /**
440      *Basic group fetching - probably needs to filter by type eventually.
441      *
442      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
443      */
444     
445     function groups($what=false)
446     {
447         $g = DB_DataObject::Factory('Group_Members');
448         $grps = $g->listGroupMembership($this);
449         $g = DB_DataObject::Factory('Groups');
450         $g->whereAddIn('id', $grps, 'int');
451         return $g->fetchAll($what);
452         
453     }
454     
455     function hasPerm($name, $lvl) 
456     {
457         static $pcache = array();
458         
459         if (!isset($pcache[$this->id])) {
460             $pcache[$this->id] = $this->getPerms();
461         }
462        // echo "<PRE>";print_r($pcache[$au->id]);
463        // var_dump($pcache[$au->id]);
464         if (empty($pcache[$this->id][$name])) {
465             return false;
466         }
467         
468         return strpos($pcache[$this->id][$name], $lvl) > -1;
469         
470     }    
471     
472     //  ------------ROO HOOKS------------------------------------
473     function applyFilters($q, $au, $roo)
474     {
475         //DB_DataObject::DebugLevel(1);
476         if (!empty($q['query']['person_not_internal'])) {
477             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
478         }
479         if (!empty($q['query']['person_internal_only_all'])) {
480             
481             
482             // must be internal and not current user (need for distribution list)
483             // user has a projectdirectory entry and role is not blank.
484             //DB_DataObject::DebugLevel(1);
485             $pd = DB_DataObject::factory('ProjectDirectory');
486             $pd->whereAdd("role != ''");
487             $pd->selectAdd();
488             $pd->selectAdd('distinct(person_id) as person_id');
489             $roled = $pd->fetchAll('person_id');
490             $rs = $roled  ? "  OR
491                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
492                     " : '';
493             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
494             
495         }
496         // -- for distribution
497         if (!empty($q['query']['person_internal_only'])) {
498             // must be internal and not current user (need for distribution list)
499             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
500             
501             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
502             //    ".id  != ".$au->id);
503             $this->whereAdd("Person.id != {$au->id}");
504         } 
505         
506         if (!empty($q['query']['comptype_or_company_id'])) {
507            // DB_DataObject::debugLevel(1);
508             $bits = explode(',', $q['query']['comptype_or_company_id']);
509             $id = (int) array_pop($bits);
510             $ct = $this->escape($bits[0]);
511             
512             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
513             
514         }
515         
516         
517         // staff list..
518         if (!empty($q['query']['person_inactive'])) {
519            // DB_Dataobject::debugLevel(1);
520             $this->active = 1;
521         }
522         $tn_p = $this->tableName();
523         $tn_gm = DB_DataObject::Factory('Group_Members')->tableName();
524         $tn_g = DB_DataObject::Factory('Groups')->tableName();
525
526         ///---------------- Group views --------
527         if (!empty($q['query']['in_group'])) {
528             // DB_DataObject::debugLevel(1);
529             $ing = (int) $q['query']['in_group'];
530             if ($q['query']['in_group'] == -1) {
531              
532                 // list all staff who are not in a group.
533                 $this->whereAdd("Person.id NOT IN (
534                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
535                         $tn_g ON $tn_g.id = $tn_gm.group_id
536                         WHERE $tn_g.type = ".$q['query']['type']."
537                     )");
538                 
539                 
540             } else {
541                 
542                 $this->whereAdd("$tn_p.id IN (
543                     SELECT distinct(user_id) FROM $tn_gm
544                         WHERE group_id = $ing
545                     )");
546                }
547             
548         }
549         
550         if (!empty($q['query']['not_in_directory'])) { 
551             // it's a Person list..
552             // DB_DATaobjecT::debugLevel(1);
553             
554             // specific to project directory which is single comp. login
555             //
556             $owncomp = DB_DataObject::Factory('Companies');
557             $owncomp->get('comptype', 'OWNER');
558             if ($q['company_id'] == $owncomp->id) {
559                 $this->active =1;
560             }
561             
562             
563
564             if ( $q['query']['not_in_directory'] > -1) {
565                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
566                 // can list current - so that it does not break!!!
567                 $x->whereAdd("$tn_p.id NOT IN 
568                     ( SELECT distinct person_id FROM $tn_pd WHERE
569                         project_id = " . $q['query']['not_in_directory'] . " AND 
570                         company_id = " . $this->company_id . ')');
571             }
572         }
573         
574         
575         if (!empty($q['query']['project_member_of'])) {
576                // this is also a flag to return if they are a member..
577             //DB_DataObject::debugLevel(1);
578             $do = DB_DataObject::factory('ProjectDirectory');
579             $do->project_id = $q['query']['project_member_of'];
580             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
581             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
582             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
583                 
584                 
585             if (!empty($q['query']['project_member_filter'])) {
586                 $this->having('is_member !=0');
587             
588             }
589             
590         }
591         
592         
593         if (!empty($q['query']['search'])) {
594             $s = $this->escape($q['query']['search']);
595                     $this->whereAdd("
596                         $tn_p.name LIKE '%$s%'  OR
597                         $tn_p.email LIKE '%$s%'  OR
598                         $tn_p.role LIKE '%$s%'  OR
599                         $tn_p.remarks LIKE '%$s%' 
600                         
601                     ");
602         }
603         
604         //
605     }
606     function setFromRoo($ar, $roo)
607     {
608         $this->setFrom($ar);
609         if (!empty($ar['passwd1'])) {
610             $this->setPassword($ar['passwd1']);
611         }
612         
613         
614         if (    $this->id &&
615                 ($this->email == $roo->old->email)&&
616                 ($this->company_id == $roo->old->company_id)
617             ) {
618             return true;
619         }
620         if (empty($this->email)) {
621             return true;
622         }
623         $xx = DB_Dataobject::factory('Person');
624         $xx->setFrom(array(
625             'email' => $this->email,
626            // 'company_id' => $x->company_id
627         ));
628         
629         if ($xx->count()) {
630             return "Duplicate Email found";
631         }
632         return true;
633     }
634     /**
635      *
636      * before Delete - delete significant dependancies..
637      * this is called after checkPerm..
638      */
639     
640     function beforeDelete()
641     {
642         
643         $e = DB_DataObject::Factory('Events');
644         $e->whereAdd('person_id = ' . $this->id);
645         $e->delete(true);
646         
647         // anything else?  
648         
649     }
650     
651     
652     /***
653      * Check if the a user has access to modify this item.
654      * @param String $lvl Level (eg. Core.Projects)
655      * @param Pman_Core_DataObjects_Person $au The authenticated user.
656      * @param boolean $changes alllow changes???
657      *
658      * @return false if no access..
659      */
660     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
661     {
662          
663        // do we have an empty system..
664         if ($au && $au->id == -1) {
665             return true;
666         }
667         
668         // determine if it's staff!!!
669          
670         if ($au->company()->comptype != 'OWNER') {
671             
672             // - can not change company!!!
673             if ($changes && 
674                 isset($changes['company_id']) && 
675                 $changes['company_id'] != $au->company_id) {
676                 return false;
677             }
678             // can only set new emails..
679             if ($changes && 
680                     !empty($this->email) && 
681                     isset($changes['email']) && 
682                     $changes['email'] != $this->email) {
683                 return false;
684             }
685             
686             // edit self... - what about other staff members...
687             
688             return $this->company_id == $au->company_id;
689         }
690          
691          
692         // yes, only owner company can mess with this...
693         $owncomp = DB_DataObject::Factory('Companies');
694         $owncomp->get('comptype', 'OWNER');
695         
696         $isStaff = ($this->company_id ==  $owncomp->id);
697         
698     
699         switch ($lvl) {
700             // extra case change passwod?
701             case 'P': //??? password
702                 // standard perms -- for editing + if the user is dowing them selves..
703                 $ret = $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
704                 return $ret || $au->id == $this->id;
705             
706             case 'S': // list..
707                 return $au->hasPerm("Core.Person", "S");
708             
709             case 'E': // edit
710                 return $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
711             
712             case 'A': // add
713                 return $isStaff ? $au->hasPerm("Core.Person", "A") : $au->hasPerm("Core.Staff", "A");
714             
715             case 'D': // add
716                 return $isStaff ? $au->hasPerm("Core.Person", "D") : $au->hasPerm("Core.Staff", "D");
717         
718         }
719         return false;
720     }
721     function onInsert($req, $roo)  
722     {
723         
724         if ($roo->authUser->id < 0) {
725             $g = DB_DataObject::factory('Groups');
726             $g->type = 0;
727             $g->get('name', 'Administrators');
728             
729             $p = DB_DataObject::factory('Group_Members');
730             $p->group_id = $g->id;
731             $p->user_id = $this->id;     
732             if (!$p->count()) {
733                 $p->insert();
734                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
735             }
736             $this->login();
737         }
738         if (!empty($req['project_id_addto'])) {
739             $pd = DB_DataObject::factory('ProjectDirectory');
740             $pd->project_id = $req['project_id_addto'];
741             $pd->person_id = $this->id; 
742             $pd->ispm =0;
743             $pd->office_id = $this->office_id;
744             $pd->company_id = $this->company_id;
745             $pd->insert();
746         }
747         
748     }
749  }