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