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