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)  
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 $project_id;                      // int(11)  
28     public $action_type;                     // string(32)  
29
30     
31     /* the code above is auto generated do not remove the tag below */
32     ###END_AUTOCODE
33     
34     function sendTemplate($templateFile, $args)
35     {
36         
37         
38         
39         $content  = clone($this);
40         
41         foreach((array)$args as $k=>$v) {
42             $content->$k = $v;
43         }
44         
45         if (!in_array($templateFile, array(
46            // templates that can be sent without authentication.
47             'password_reset' ,
48             'password_welcome'
49             ))) {
50             $content->authUser = $this->getAuthUser();
51             if (!$content->authUser) {
52                 return PEAR::raiseError("Not authenticated");
53             }
54         }
55         
56         $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
57         /* use the regex compiler, as it doesnt parse <tags */
58         require_once 'HTML/Template/Flexy.php';
59         $template = new HTML_Template_Flexy( array(
60                  'compiler'    => 'Regex',
61                  'filters' => array('SimpleTags','Mail'),
62             //     'debug'=>1,
63             ));
64         
65      
66          
67         
68         $template->compile("mail/$templateFile.txt");
69         
70         /* use variables from this object to ouput data. */
71         $mailtext = $template->bufferedOutputObject($content);
72         //echo "<PRE>";print_R($mailtext);
73         
74         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
75         require_once 'Mail/mimeDecode.php';
76         require_once 'Mail.php';
77         
78         $decoder = new Mail_mimeDecode($mailtext);
79         $parts = $decoder->getSendArray();
80         if (PEAR::isError($parts)) {
81             return $parts;
82             //echo "PROBLEM: {$parts->message}";
83             //exit;
84         } 
85         list($recipents,$headers,$body) = $parts;
86         $recipents = array($this->email);
87         if (!empty($content->bcc) && is_array($content->bcc)) {
88             $recipents =array_merge($recipents, $content->bcc);
89         }
90         //print_r($recipents);exit;
91         $mailOptions = PEAR::getStaticProperty('Mail','options');
92         $mail = Mail::factory("SMTP",$mailOptions);
93         $headers['Date'] = date('r');
94         if (PEAR::isError($mail)) {
95             return $mail;
96         } 
97         $oe = error_reporting(E_ALL ^ E_NOTICE);
98         $ret = $mail->send($recipents,$headers,$body);
99         error_reporting($oe);
100        
101         return $ret;
102     
103     }
104     function getEmailFrom()
105     {
106         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
107     }
108     function toEventString() 
109     {
110         return empty($this->name) ? $this->email : $this->name;
111     } 
112     function whereAddIn($key, $list, $type) {
113         $ar = array();
114         foreach($list as $k) {
115             $ar[] = $type =='int' ? (int)$k : $this->escape($k);
116         }
117         if (!$ar) {
118             return;
119         }
120         $this->whereAdd("$key IN (". implode(',', $ar). ')');
121     }
122     function fetchAll($k= false, $v = false) 
123     {
124         // should it even do this!!!?!?
125         if ($k !== false && 
126                 (   // only do this is we have not been explicit..
127                     empty($this->_query['data_select']) || 
128                     ($this->_query['data_select'] == '*')
129                 )
130             ) {
131             $this->selectAdd();
132             $this->selectAdd($k);
133             if ($v !== false) {
134                 $this->selectAdd($v);
135             }
136         }
137         
138         $this->find();
139         $ret = array();
140         while ($this->fetch()) {
141             if ($v !== false) {
142                 $ret[$this->$k] = $this->$v;
143                 continue;
144             }
145             $ret[] = $k === false ? clone($this) : $this->$k;
146         }
147         return $ret;
148          
149     }
150     //   ---------------- authentication / passwords and keys stuff  ----------------
151     function isAuth()
152     {
153         $db = $this->getDatabaseConnection();
154         $sesPrefix = $db->dsn['database'];
155         @session_start();
156         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
157             // in session...
158             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
159             $u = DB_DataObject::factory('Person');
160             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
161                 return true;
162             }
163             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
164             
165         }
166         // not in session or not matched...
167         $u = DB_DataObject::factory('Person');
168         $u->whereAdd(' LENGTH(passwd) > 0');
169         $n = $u->count();
170         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
171         if ($error) {
172             die($error->toString()); // not really a good thing to do...
173         }
174         if (!$n){ // authenticated as there are no users in the system...
175             return true;
176         }
177         
178         return false;
179         
180     }
181     function getAuthUser()
182     {
183         if (!$this->isAuth()) {
184             return false;
185         }
186         $db = $this->getDatabaseConnection();
187         $sesPrefix = $db->dsn['database'];
188         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
189             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
190             
191             $u = DB_DataObject::factory('Person');
192             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
193                 return clone($u);
194             }
195              
196         }
197         
198         $u = DB_DataObject::factory('Person');
199         $u->whereAdd(' LENGTH(passwd) > 0');
200         if (!$u->count()){
201             $u = DB_DataObject::factory('Person');
202             $u->id = -1;
203             return $u;
204             
205         }
206         return false;
207     }     
208     function login()
209     {
210         $this->isAuth(); // force session start..
211          $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         if (substr($this->passwd,0,1) == '$') {
237             return crypt($val,$this->passwd) == $this->passwd ;
238         }
239         // old style md5 passwords...- cant be used with courier....
240         return md5($val) == $this->passwd;
241     }
242     function setPassword($value) 
243     {
244         $salt='';
245         while(strlen($salt)<9) {
246             $salt.=chr(rand(64,126));
247             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
248         }
249         $this->passwd = crypt($value, '$1$'. $salt. '$');
250        
251     }      
252     
253     function company()
254     {
255         $x = DB_DataObject::factory('Companies');
256         $x->get($this->company_id);
257         return $x;
258     }
259     
260     
261     function active()
262     {
263         return $this->active;
264     }
265     function authUserName($n) // set username prior to acheck user exists query.
266     {
267         
268         $this->whereAdd('LENGTH(passwd) > 1'); 
269         $this->email = $n;
270     }
271     function lang($val)
272     {
273         if ($val == $this->lang) {
274             return;
275         }
276         $uu = clone($this);
277         $this->lang = $val;
278         $this->update($uu);
279
280     }
281             
282     
283     function authUserArray()
284     {
285         
286         $aur = $this->toArray();
287         
288         
289         
290         //DB_DataObject::debugLevel(1);
291         $c = DB_Dataobject::factory('Companies');
292         $im = DB_Dataobject::factory('Images');
293         $c->joinAdd($im, 'LEFT');
294         $c->selectAdd();
295         $c->selectAs($c, 'company_id_%s');
296         $c->selectAs($im, 'company_id_logo_id_%s');
297         $c->id = $this->company_id;
298         $c->limit(1);
299         $c->find(true);
300         
301         $aur = array_merge( $c->toArray(),$aur);
302         
303         if (empty($c->company_id_logo_id_id))  {
304                  
305             $im = DB_Dataobject::factory('Images');
306             $im->ontable = 'Companies';
307             $im->onid = $c->id;
308             $im->imgtype = 'LOGO';
309             $im->limit(1);
310             $im->selectAs($im,  'company_id_logo_id_%s');
311             if ($im->find(true)) {
312                     
313                 foreach($im->toArray() as $k=>$v) {
314                     $aur[$k] = $v;
315                 }
316             }
317         }
318         /*
319         now handled by interface...
320         
321         $lang = empty($this->lang) ? 'en' : $this->lang;
322         if (empty($_SESSION['Pman_I18N'][$lang])) {
323             require_once 'Pman/I18N.php';
324             $x = new Pman_I18N();
325             $x->setSession($this);
326             
327         }
328         
329         $aur['i18n'] =$_SESSION['Pman_I18N'][$lang];
330         */
331         // perms + groups.
332         $aur['perms']  = $this->getPerms();
333         $g = DB_DataObject::Factory('Group_Members');
334         $aur['groups']  = $g->listGroupMembership($this, 'name');
335         
336         $aur['passwd'] = '';
337         $aur['dailykey'] = '';
338         
339         
340         
341         return $aur;
342     }
343     
344     //   ----------PERMS------  ----------------
345     function getPerms() 
346     {
347          //DB_DataObject::debugLevel(1);
348         // find out all the groups they are a member of.. + Default..
349         $g = DB_DataObject::Factory('Group_Rights');
350         if (!$g->count()) {
351             $g->genDefault();
352         }
353         if ($this->id < 0) {
354             return $g->adminRights();
355         }
356         
357         $g = DB_DataObject::Factory('Group_Members');
358         $grps = $g->listGroupMembership($this);
359         $isAdmin = $g->inAdmin;
360        // var_dump($grps);
361         // the load all the perms for those groups, and add them all together..
362         // then load all those 
363         $g = DB_DataObject::Factory('Group_Rights');
364         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin);
365        // echo '<PRE>';print_r($ret);
366         return $ret;
367          
368         
369     }
370     function hasPerm($name, $lvl) 
371     {
372         static $pcache = array();
373         
374         if (!isset($pcache[$this->id])) {
375             $pcache[$this->id] = $this->getPerms();
376         }
377        // echo "<PRE>";print_r($pcache[$au->id]);
378        // var_dump($pcache[$au->id]);
379         if (empty($pcache[$this->id][$name])) {
380             return false;
381         }
382         
383         return strpos($pcache[$this->id][$name], $lvl) > -1;
384         
385     }    
386     
387     //  ------------ROO HOOKS------------------------------------
388     function applyFilters($q, $au)
389     {
390         if (!empty($q['query']['person_not_internal'])) {
391             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
392         }
393         if (!empty($q['query']['person_internal_only_all'])) {
394             // must be internal and not current user (need for distribution list)
395             $this->whereAdd(" join_company_id_id.isOwner = 1");
396             
397         }
398         // -- for distribution
399         if (!empty($q['query']['person_internal_only'])) {
400             // must be internal and not current user (need for distribution list)
401             $this->whereAdd(" join_company_id_id.isOwner = 1");
402             
403             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
404             //    ".id  != ".$au->id);
405             $this->whereAdd("Person.id != {$au->id}");
406         } 
407         // staff list..
408         if (!empty($q['query']['person_inactive'])) {
409            // DB_Dataobject::debugLevel(1);
410             $this->active = 1;
411         }
412         
413         ///---------------- Group views --------
414         if (!empty($q['query']['in_group'])) {
415             // DB_DataObject::debugLevel(1);
416             $ing = (int) $q['query']['in_group'];
417             if ($q['query']['in_group'] == -1) {
418                 // list all staff who are not in a group.
419                 $this->whereAdd("Person.id NOT IN (
420                     SELECT distinct(user_id) FROM Group_Members LEFT JOIN
421                         Groups ON Groups.id = Group_Members.group_id
422                         WHERE Groups.type = ".$q['query']['type']."
423                     )");
424                 
425                 
426             } else {
427                 
428                 $this->whereAdd("Person.id IN (
429                     SELECT distinct(user_id) FROM Group_Members 
430                         WHERE group_id = $ing
431                     )");
432                }
433             
434         }
435         
436         if (!empty($q['query']['not_in_directory'])) { 
437             // it's a Person list..
438             // DB_DATaobjecT::debugLevel(1);
439             
440             // specific to project directory which is single comp. login
441             //
442             $owncomp = DB_DataObject::Factory('Companies');
443             $owncomp->get('comptype', 'OWNER');
444             if ($q['company_id'] == $owncomp->id) {
445                 $this->active =1;
446             }
447             
448             
449             if ( $q['query']['not_in_directory'] > -1) {
450                 // can list current - so that it does not break!!!
451                 $x->whereAdd('Person.id NOT IN 
452                     ( SELECT distinct person_id FROM ProjectDirectory WHERE
453                         project_id = ' . $q['query']['not_in_directory'] . ' AND 
454                         company_id = ' . $this->company_id . ')');
455             }
456         }
457         
458         if (!empty($q['query']['search'])) {
459             $s = $this->escape($q['query']['search']);
460                     $this->whereAdd("
461                         Person.name LIKE '%$s%'  OR
462                         Person.email LIKE '%$s%'  OR
463                         Person.role LIKE '%$s%'  OR
464                         Person.remarks LIKE '%$s%' 
465                         
466                     ");
467         }
468         
469         //
470     }
471     function setFromRoo($ar, $roo)
472     {
473         $this->setFrom($ar);
474         if (!empty($ar['passwd1'])) {
475             $this->setPassword($ar['passwd1']);
476         }
477         
478         
479         if (    $this->id &&
480                 ($this->email == $roo->old->email)&&
481                 ($this->company_id == $roo->old->company_id)
482             ) {
483             return true;
484         }
485         $xx = DB_Dataobject::factory('Person');
486         $xx->setFrom(array(
487             'email' => $this->email,
488            // 'company_id' => $x->company_id
489         ));
490         
491         if ($xx->count()) {
492             return "Duplicate Email found";
493         }
494         return true;
495     }    
496     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
497     {
498          
499        // do we have an empty system..
500         if ($au && $au->id == -1) {
501             return true;
502         }
503         
504         // determine if it's staff!!!
505          
506         if ($au->company()->comptype != 'OWNER') {
507             
508             // - can not change company!!!
509             if ($changes && 
510                 isset($changes['company_id']) && 
511                 $changes['company_id'] != $au->company_id) {
512                 return false;
513             }
514             // can only set new emails..
515             if ($changes && 
516                     !empty($this->email) && 
517                     isset($changes['email']) && 
518                     $changes['email'] != $this->email) {
519                 return false;
520             }
521             
522             // edit self... - what about other staff members...
523             
524             return $this->company_id == $au->company_id;
525         }
526          
527          
528         // yes, only owner company can mess with this...
529         $owncomp = DB_DataObject::Factory('Companies');
530         $owncomp->get('comptype', 'OWNER');
531         
532         $isStaff = ($this->company_id ==  $owncomp->id);
533         
534     
535         switch ($lvl) {
536             // extra case change passwod?
537             case 'P': //??? password
538                 // standard perms -- for editing + if the user is dowing them selves..
539                 $ret = $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
540                 return $ret || $au->id == $this->id;
541             
542             case 'S': // list..
543                 return $au->hasPerm("Core.Person", "S");
544             
545             case 'E': // edit
546                 return $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
547             
548             case 'A': // add
549                 return $isStaff ? $au->hasPerm("Core.Person", "A") : $au->hasPerm("Core.Staff", "A");
550             
551             case 'D': // add
552                 return $isStaff ? $au->hasPerm("Core.Person", "D") : $au->hasPerm("Core.Staff", "D");
553         
554         }
555         return false;
556     }
557     function onInsert($req, $roo)  
558     {
559         
560         if ($roo->authUser->id < 0) {
561             $g = DB_DataObject::factory('Groups');
562             $g->type = 0;
563             $g->get('name', 'Administrators');
564             
565             $p = DB_DataObject::factory('Group_Members');
566             $p->group_id = $g->id;
567             $p->user_id = $this->id;     
568             if (!$p->count()) {
569                 $p->insert();
570                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
571             }
572             $this->login();
573         }
574         if (!empty($req['project_id_addto'])) {
575             $pd = DB_DataObject::factory('ProjectDirectory');
576             $pd->project_id = $req['project_id_addto'];
577             $pd->person_id = $this->id; 
578             $pd->ispm =0;
579             $pd->office_id = $this->office_id;
580             $pd->company_id = $this->company_id;
581             $pd->insert();
582         }
583         
584     }
585  }