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         $sesPrefix = $db->dsn['database'];
172         @session_start();
173         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
174             // in session...
175             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
176             $u = DB_DataObject::factory('Person');
177             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
178                 $u->verifyAuth();
179                 
180                 return true;
181             }
182             
183             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
184             
185         }
186         // local auth - 
187         $u = DB_DataObject::factory('Person');
188         $ff = HTML_FlexyFramework::get();
189         if (!empty($ff->Pman['local_autoauth']) && 
190             (!empty($_SERVER['SERVER_ADDR'])) &&
191             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
192             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
193             $u->get('email', $ff->Pman['local_autoauth'])
194         ) {
195             $db = $this->getDatabaseConnection();
196             $sesPrefix = $db->dsn['database'];
197             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
198             return true;
199         }
200            
201         
202         // not in session or not matched...
203         $u = DB_DataObject::factory('Person');
204         $u->whereAdd(' LENGTH(passwd) > 0');
205         $n = $u->count();
206         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
207         if ($error) {
208             die($error->toString()); // not really a good thing to do...
209         }
210         if (!$n){ // authenticated as there are no users in the system...
211             return true;
212         }
213         
214         return false;
215         
216     }
217     function getAuthUser()
218     {
219         if (!$this->isAuth()) {
220             return false;
221         }
222         $db = $this->getDatabaseConnection();
223         $sesPrefix = $db->dsn['database'];
224         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
225             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
226             
227             $u = DB_DataObject::factory('Person');
228             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
229                 return clone($u);
230             }
231              
232         }
233         
234         $u = DB_DataObject::factory('Person');
235         $u->whereAdd(' LENGTH(passwd) > 0');
236         if (!$u->count()){
237             $u = DB_DataObject::factory('Person');
238             $u->id = -1;
239             return $u;
240             
241         }
242         return false;
243     }     
244     function login()
245     {
246         $this->isAuth(); // force session start..
247         $this->verifyAuth();
248         $db = $this->getDatabaseConnection();
249         
250         
251         $g = DB_DataObject::factory('Groups');
252         $g->type = 0;
253         $g->get('name', 'Administrators');
254         if (in_array($g->id,$this->groups('id'))) {
255             // refresh admin groups.
256             $g = DB_DataObject::Factory('Group_Members');
257             $grps = $g->listGroupMembership($this);
258             
259         }
260             
261             
262         
263         $sesPrefix = $db->dsn['database'];
264         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
265         
266     }
267     function logout()
268     {
269         $this->isAuth(); // force session start..
270          $db = $this->getDatabaseConnection();
271         $sesPrefix = $db->dsn['database'];
272         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
273         
274     }    
275     function genPassKey ($t) 
276     {
277         return md5($this->email . $t. $this->passwd);
278     }
279     function simpleAuthKey($m = 0)
280     {
281         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
282         
283         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
284     } 
285     function checkPassword($val)
286     {
287         
288         if (substr($this->passwd,0,1) == '$') {
289             return crypt($val,$this->passwd) == $this->passwd ;
290         }
291         // old style md5 passwords...- cant be used with courier....
292         return md5($val) == $this->passwd;
293     }
294     function setPassword($value) 
295     {
296         $salt='';
297         while(strlen($salt)<9) {
298             $salt.=chr(rand(64,126));
299             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
300         }
301         $this->passwd = crypt($value, '$1$'. $salt. '$');
302        
303        
304     }      
305     
306     function company()
307     {
308         $x = DB_DataObject::factory('Companies');
309         $x->get($this->company_id);
310         return $x;
311     }
312     
313     
314     function active()
315     {
316         return $this->active;
317     }
318     function authUserName($n) // set username prior to acheck user exists query.
319     {
320         
321         $this->whereAdd('LENGTH(passwd) > 1'); 
322         $this->email = $n;
323     }
324     function lang($val)
325     {
326         if ($val == $this->lang) {
327             return;
328         }
329         $uu = clone($this);
330         $this->lang = $val;
331         $this->update($uu);
332
333     }
334             
335     
336     function authUserArray()
337     {
338         
339         $aur = $this->toArray();
340         
341         if ($this->id < 1) {
342             return $aur;
343         }
344         
345         
346         //DB_DataObject::debugLevel(1);
347         $c = DB_Dataobject::factory('Companies');
348         $im = DB_Dataobject::factory('Images');
349         $c->joinAdd($im, 'LEFT');
350         $c->selectAdd();
351         $c->selectAs($c, 'company_id_%s');
352         $c->selectAs($im, 'company_id_logo_id_%s');
353         $c->id = $this->company_id;
354         $c->limit(1);
355         $c->find(true);
356         
357         $aur = array_merge( $c->toArray(),$aur);
358         
359         if (empty($c->company_id_logo_id_id))  {
360                  
361             $im = DB_Dataobject::factory('Images');
362             $im->ontable = 'Companies';
363             $im->onid = $c->id;
364             $im->imgtype = 'LOGO';
365             $im->limit(1);
366             $im->selectAdd();
367             $im->selectAs($im,  'company_id_logo_id_%s');
368             if ($im->find(true)) {
369                     
370                 foreach($im->toArray() as $k=>$v) {
371                     $aur[$k] = $v;
372                 }
373             }
374         }
375       
376         // perms + groups.
377         $aur['perms']  = $this->getPerms();
378         $g = DB_DataObject::Factory('Group_Members');
379         $aur['groups']  = $g->listGroupMembership($this, 'name');
380         
381         $aur['passwd'] = '';
382         $aur['dailykey'] = '';
383         
384         
385         
386         return $aur;
387     }
388     
389     //   ----------PERMS------  ----------------
390     function getPerms() 
391     {
392          //DB_DataObject::debugLevel(1);
393         // find out all the groups they are a member of.. + Default..
394         
395         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
396         
397         $g = DB_DataObject::Factory('Group_Rights');
398         if (!$g->count()) {
399             $g->genDefault();
400         }
401         
402         if ($this->id < 0) {
403             return $g->adminRights(); // system is not set up - so they get full rights.
404         }
405         DB_DataObject::debugLevel(1);
406         $g = DB_DataObject::Factory('Group_Members');
407         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
408         if (!$g->count()) {
409             // add the current user to the admin group..
410             $g = DB_DataObject::Factory('Groups');
411             if ($g->get('name', 'Administrators')) {
412                 $gm = DB_DataObject::Factory('Group_Members');
413                 $gm->group_id = $g->id;
414                 $gm->user_id = $this->id;
415                 $gm->insert();
416             }
417             
418         }
419         
420         // ------ STANDARD PERMISSION HANDLING.
421         
422         $g = DB_DataObject::Factory('Group_Members');
423         $grps = $g->listGroupMembership($this);
424        //var_dump($grps);
425         $isAdmin = $g->inAdmin;
426         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
427         // the load all the perms for those groups, and add them all together..
428         // then load all those 
429         $g = DB_DataObject::Factory('Group_Rights');
430         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin);
431         //echo '<PRE>';print_r($ret);
432         return $ret;
433          
434         
435     }
436     /**
437      *Basic group fetching - probably needs to filter by type eventually.
438      *
439      */
440     
441     function groups()
442     {
443         $g = DB_DataObject::Factory('Group_Members');
444         $grps = $g->listGroupMembership($this);
445         $g = DB_DataObject::Factory('Groups');
446         $g->whereAddIn('id', $grps, 'int');
447         return $g->fetchAll();
448         
449     }
450     
451     function hasPerm($name, $lvl) 
452     {
453         static $pcache = array();
454         
455         if (!isset($pcache[$this->id])) {
456             $pcache[$this->id] = $this->getPerms();
457         }
458        // echo "<PRE>";print_r($pcache[$au->id]);
459        // var_dump($pcache[$au->id]);
460         if (empty($pcache[$this->id][$name])) {
461             return false;
462         }
463         
464         return strpos($pcache[$this->id][$name], $lvl) > -1;
465         
466     }    
467     
468     //  ------------ROO HOOKS------------------------------------
469     function applyFilters($q, $au)
470     {
471         if (!empty($q['query']['person_not_internal'])) {
472             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
473         }
474         if (!empty($q['query']['person_internal_only_all'])) {
475             
476             
477             // must be internal and not current user (need for distribution list)
478             // user has a projectdirectory entry and role is not blank.
479             //DB_DataObject::DebugLevel(1);
480             $pd = DB_DataObject::factory('ProjectDirectory');
481             $pd->whereAdd("role != ''");
482             $pd->selectAdd();
483             $pd->selectAdd('distinct(person_id) as person_id');
484             $roled = $pd->fetchAll('person_id');
485             $rs = $roled  ? "  OR
486                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
487                     " : '';
488             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
489             
490         }
491         // -- for distribution
492         if (!empty($q['query']['person_internal_only'])) {
493             // must be internal and not current user (need for distribution list)
494             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
495             
496             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
497             //    ".id  != ".$au->id);
498             $this->whereAdd("Person.id != {$au->id}");
499         } 
500         
501         if (!empty($q['query']['comptype_or_company_id'])) {
502            // DB_DataObject::debugLevel(1);
503             $bits = explode(',', $q['query']['comptype_or_company_id']);
504             $id = (int) array_pop($bits);
505             $ct = $this->escape($bits[0]);
506             
507             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
508             
509         }
510         
511         
512         // staff list..
513         if (!empty($q['query']['person_inactive'])) {
514            // DB_Dataobject::debugLevel(1);
515             $this->active = 1;
516         }
517         
518         ///---------------- Group views --------
519         if (!empty($q['query']['in_group'])) {
520             // DB_DataObject::debugLevel(1);
521             $ing = (int) $q['query']['in_group'];
522             if ($q['query']['in_group'] == -1) {
523                 // list all staff who are not in a group.
524                 $this->whereAdd("Person.id NOT IN (
525                     SELECT distinct(user_id) FROM Group_Members LEFT JOIN
526                         Groups ON Groups.id = Group_Members.group_id
527                         WHERE Groups.type = ".$q['query']['type']."
528                     )");
529                 
530                 
531             } else {
532                 
533                 $this->whereAdd("Person.id IN (
534                     SELECT distinct(user_id) FROM Group_Members 
535                         WHERE group_id = $ing
536                     )");
537                }
538             
539         }
540         
541         if (!empty($q['query']['not_in_directory'])) { 
542             // it's a Person list..
543             // DB_DATaobjecT::debugLevel(1);
544             
545             // specific to project directory which is single comp. login
546             //
547             $owncomp = DB_DataObject::Factory('Companies');
548             $owncomp->get('comptype', 'OWNER');
549             if ($q['company_id'] == $owncomp->id) {
550                 $this->active =1;
551             }
552             
553             
554             if ( $q['query']['not_in_directory'] > -1) {
555                 // can list current - so that it does not break!!!
556                 $x->whereAdd('Person.id NOT IN 
557                     ( SELECT distinct person_id FROM ProjectDirectory WHERE
558                         project_id = ' . $q['query']['not_in_directory'] . ' AND 
559                         company_id = ' . $this->company_id . ')');
560             }
561         }
562         
563         
564         if (!empty($q['query']['project_member_of'])) {
565                // this is also a flag to return if they are a member..
566             //DB_DataObject::debugLevel(1);
567             $do = DB_DataObject::factory('ProjectDirectory');
568             $do->project_id = $q['query']['project_member_of'];
569             
570             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
571             $this->selectAdd('IF(ProjectDirectory.id IS NULL, 0,  ProjectDirectory.id )  as is_member');
572                 
573                 
574             if (!empty($q['query']['project_member_filter'])) {
575                 $this->having('is_member !=0');
576             
577             }
578             
579         }
580         
581         
582         if (!empty($q['query']['search'])) {
583             $s = $this->escape($q['query']['search']);
584                     $this->whereAdd("
585                         Person.name LIKE '%$s%'  OR
586                         Person.email LIKE '%$s%'  OR
587                         Person.role LIKE '%$s%'  OR
588                         Person.remarks LIKE '%$s%' 
589                         
590                     ");
591         }
592         
593         //
594     }
595     function setFromRoo($ar, $roo)
596     {
597         $this->setFrom($ar);
598         if (!empty($ar['passwd1'])) {
599             $this->setPassword($ar['passwd1']);
600         }
601         
602         
603         if (    $this->id &&
604                 ($this->email == $roo->old->email)&&
605                 ($this->company_id == $roo->old->company_id)
606             ) {
607             return true;
608         }
609         if (empty($this->email)) {
610             return true;
611         }
612         $xx = DB_Dataobject::factory('Person');
613         $xx->setFrom(array(
614             'email' => $this->email,
615            // 'company_id' => $x->company_id
616         ));
617         
618         if ($xx->count()) {
619             return "Duplicate Email found";
620         }
621         return true;
622     }
623     /**
624      *
625      * before Delete - delete significant dependancies..
626      * this is called after checkPerm..
627      */
628     
629     function beforeDelete()
630     {
631         
632         $e = DB_DataObject::Factory('Events');
633         $e->whereAdd('person_id = ' . $this->id);
634         $e->delete(true);
635         
636         // anything else?  
637         
638     }
639     
640     
641     /***
642      * Check if the a user has access to modify this item.
643      * @param String $lvl Level (eg. Core.Projects)
644      * @param Pman_Core_DataObjects_Person $au The authenticated user.
645      * @param boolean $changes alllow changes???
646      *
647      * @return false if no access..
648      */
649     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
650     {
651          
652        // do we have an empty system..
653         if ($au && $au->id == -1) {
654             return true;
655         }
656         
657         // determine if it's staff!!!
658          
659         if ($au->company()->comptype != 'OWNER') {
660             
661             // - can not change company!!!
662             if ($changes && 
663                 isset($changes['company_id']) && 
664                 $changes['company_id'] != $au->company_id) {
665                 return false;
666             }
667             // can only set new emails..
668             if ($changes && 
669                     !empty($this->email) && 
670                     isset($changes['email']) && 
671                     $changes['email'] != $this->email) {
672                 return false;
673             }
674             
675             // edit self... - what about other staff members...
676             
677             return $this->company_id == $au->company_id;
678         }
679          
680          
681         // yes, only owner company can mess with this...
682         $owncomp = DB_DataObject::Factory('Companies');
683         $owncomp->get('comptype', 'OWNER');
684         
685         $isStaff = ($this->company_id ==  $owncomp->id);
686         
687     
688         switch ($lvl) {
689             // extra case change passwod?
690             case 'P': //??? password
691                 // standard perms -- for editing + if the user is dowing them selves..
692                 $ret = $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
693                 return $ret || $au->id == $this->id;
694             
695             case 'S': // list..
696                 return $au->hasPerm("Core.Person", "S");
697             
698             case 'E': // edit
699                 return $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
700             
701             case 'A': // add
702                 return $isStaff ? $au->hasPerm("Core.Person", "A") : $au->hasPerm("Core.Staff", "A");
703             
704             case 'D': // add
705                 return $isStaff ? $au->hasPerm("Core.Person", "D") : $au->hasPerm("Core.Staff", "D");
706         
707         }
708         return false;
709     }
710     function onInsert($req, $roo)  
711     {
712         
713         if ($roo->authUser->id < 0) {
714             $g = DB_DataObject::factory('Groups');
715             $g->type = 0;
716             $g->get('name', 'Administrators');
717             
718             $p = DB_DataObject::factory('Group_Members');
719             $p->group_id = $g->id;
720             $p->user_id = $this->id;     
721             if (!$p->count()) {
722                 $p->insert();
723                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
724             }
725             $this->login();
726         }
727         if (!empty($req['project_id_addto'])) {
728             $pd = DB_DataObject::factory('ProjectDirectory');
729             $pd->project_id = $req['project_id_addto'];
730             $pd->person_id = $this->id; 
731             $pd->ispm =0;
732             $pd->office_id = $this->office_id;
733             $pd->company_id = $this->company_id;
734             $pd->insert();
735         }
736         
737     }
738  }