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