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