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