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