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