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