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