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