DataObjects/ProjectDirectory.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)  not_null
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 $action_type;                     // string(32)  
28     public $project_id;                      // int(11)  
29     public $deleted_by;                      // int(11)  not_null
30     public $deleted_dt;                      // datetime(19)  binary
31
32     
33     /* the code above is auto generated do not remove the tag below */
34     ###END_AUTOCODE
35     /**
36      *
37      * @param {String} $templateFile  (mail/XXXXXXX.txt) exclude the mail and .txt bit.
38      * @param {Array|Object} $args   data to send out..
39      * @return {Array|PEAR_Error} array of $recipents, $header, $body 
40      */
41     function buildMail($templateFile, $args)
42     {
43           
44         $args = (array) $args;
45         $content  = clone($this);
46         
47         foreach((array)$args as $k=>$v) {
48             $content->$k = $v;
49         }
50         
51         $ff = HTML_FlexyFramework::get();
52         
53         
54         //?? is this really the place for this???
55         if (
56                 !$ff->cli && 
57                 empty($args['no_auth']) &&
58                 !in_array($templateFile, array(
59                     // templates that can be sent without authentication.
60                      'password_reset' ,
61                      'password_welcome'
62                  ))
63             ) {
64             
65             $content->authUser = $this->getAuthUser();
66             if (!$content->authUser) {
67                 return PEAR::raiseError("Not authenticated");
68             }
69         }
70         
71         // should handle x-forwarded...
72         
73         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
74             $_SERVER["HTTP_HOST"] :
75             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
76             
77         /* use the regex compiler, as it doesnt parse <tags */
78         require_once 'HTML/Template/Flexy.php';
79         $template = new HTML_Template_Flexy( array(
80             'compiler'    => 'Flexy',
81             'nonHTML' => true,
82             'filters' => array('SimpleTags','Mail'),
83             //     'debug'=>1,
84         ));
85         
86      
87          
88         
89         $template->compile("mail/$templateFile.txt");
90         
91         /* use variables from this object to ouput data. */
92         $mailtext = $template->bufferedOutputObject($content);
93         //echo "<PRE>";print_R($mailtext);
94         //print_R($mailtext);exit;
95         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
96         require_once 'Mail/mimeDecode.php';
97         require_once 'Mail.php';
98         
99         $decoder = new Mail_mimeDecode($mailtext);
100         $parts = $decoder->getSendArray();
101         if (PEAR::isError($parts)) {
102             return $parts;
103             //echo "PROBLEM: {$parts->message}";
104             //exit;
105         } 
106         list($recipents,$headers,$body) = $parts;
107         $recipents = array($this->email);
108         if (!empty($content->bcc) && is_array($content->bcc)) {
109             $recipents =array_merge($recipents, $content->bcc);
110         }
111         $headers['Date'] = date('r');
112         
113         return array(
114             'recipents' => $recipents,
115             'headers'    => $headers,
116             'body'      => $body
117         );
118         
119         
120     }
121     
122     
123     /**
124      * send a template
125      * - user must be authenticate or args[no_auth] = true
126      *   or template = password_[reset|welcome]
127      * 
128      */
129     function sendTemplate($templateFile, $args)
130     {
131         
132         $ar = $this->buildMail($templateFile, $args);
133          
134         //print_r($recipents);exit;
135         $mailOptions = PEAR::getStaticProperty('Mail','options');
136         $mail = Mail::factory("SMTP",$mailOptions);
137         
138         if (PEAR::isError($mail)) {
139             return $mail;
140         } 
141         $oe = error_reporting(E_ALL ^ E_NOTICE);
142         $ret = $mail->send($ar['recipents'],$ar['headers'],$ar['body']);
143         error_reporting($oe);
144        
145         return $ret;
146     
147     }
148     function getEmailFrom()
149     {
150         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
151     }
152     function toEventString() 
153     {
154         return empty($this->name) ? $this->email : $this->name;
155     } 
156     function verifyAuth()
157     { 
158         $ff= HTML_FlexyFramework::get();
159         if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
160             $ff->page->jerr("Login not permited to outside companies");
161         }
162         return true;
163         
164     }    
165    
166    
167     //   ---------------- authentication / passwords and keys stuff  ----------------
168     function isAuth()
169     {
170         $db = $this->getDatabaseConnection();
171         $sesPrefix = $db->dsn['database'];
172         @session_start();
173         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
174             // in session...
175             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
176             $u = DB_DataObject::factory('Person');
177             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
178                 $u->verifyAuth();
179                 
180                 return true;
181             }
182             
183             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
184             
185         }
186         // local auth - 
187         $u = DB_DataObject::factory('Person');
188         $ff = HTML_FlexyFramework::get();
189         if (!empty($ff->Pman['local_autoauth']) && 
190             (!empty($_SERVER['SERVER_ADDR'])) &&
191             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
192             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
193             $u->get('email', $ff->Pman['local_autoauth'])
194         ) {
195             $db = $this->getDatabaseConnection();
196             $sesPrefix = $db->dsn['database'];
197             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
198             return true;
199         }
200            
201         
202         // not in session or not matched...
203         $u = DB_DataObject::factory('Person');
204         $u->whereAdd(' LENGTH(passwd) > 0');
205         $n = $u->count();
206         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
207         if ($error) {
208             die($error->toString()); // not really a good thing to do...
209         }
210         if (!$n){ // authenticated as there are no users in the system...
211             return true;
212         }
213         
214         return false;
215         
216     }
217     function getAuthUser()
218     {
219         if (!$this->isAuth()) {
220             return false;
221         }
222         $db = $this->getDatabaseConnection();
223         $sesPrefix = $db->dsn['database'];
224         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
225             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
226             
227             $u = DB_DataObject::factory('Person');
228             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
229                 return clone($u);
230             }
231              
232         }
233         
234         $u = DB_DataObject::factory('Person');
235         $u->whereAdd(' LENGTH(passwd) > 0');
236         if (!$u->count()){
237             $u = DB_DataObject::factory('Person');
238             $u->id = -1;
239             return $u;
240             
241         }
242         return false;
243     }     
244     function login()
245     {
246         $this->isAuth(); // force session start..
247         $this->verifyAuth();
248         $db = $this->getDatabaseConnection();
249         
250         
251         // refresh admin group if we are logged in as one..
252         //DB_DataObject::debugLevel(1);
253         $g = DB_DataObject::factory('Groups');
254         $g->type = 0;
255         $g->get('name', 'Administrators');
256         $gm = DB_DataObject::Factory('Group_Members');
257         if (in_array($g->id,$gm->listGroupMembership($this))) {
258             // refresh admin groups.
259             $gr = DB_DataObject::Factory('Group_Rights');
260             $gr->applyDefs($g, 0);
261         }
262             
263             
264         
265         $sesPrefix = $db->dsn['database'];
266         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
267         
268     }
269     function logout()
270     {
271         $this->isAuth(); // force session start..
272          $db = $this->getDatabaseConnection();
273         $sesPrefix = $db->dsn['database'];
274         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
275         
276     }    
277     function genPassKey ($t) 
278     {
279         return md5($this->email . $t. $this->passwd);
280     }
281     function simpleAuthKey($m = 0)
282     {
283         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
284         
285         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
286     } 
287     function checkPassword($val)
288     {
289         
290         if (substr($this->passwd,0,1) == '$') {
291             return crypt($val,$this->passwd) == $this->passwd ;
292         }
293         // old style md5 passwords...- cant be used with courier....
294         return md5($val) == $this->passwd;
295     }
296     function setPassword($value) 
297     {
298         $salt='';
299         while(strlen($salt)<9) {
300             $salt.=chr(rand(64,126));
301             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
302         }
303         $this->passwd = crypt($value, '$1$'. $salt. '$');
304        
305        
306     }      
307     
308     function company()
309     {
310         $x = DB_DataObject::factory('Companies');
311         $x->get($this->company_id);
312         return $x;
313     }
314     
315     
316     function active()
317     {
318         return $this->active;
319     }
320     function authUserName($n) // set username prior to acheck user exists query.
321     {
322         
323         $this->whereAdd('LENGTH(passwd) > 1'); 
324         $this->email = $n;
325     }
326     function lang($val)
327     {
328         if ($val == $this->lang) {
329             return;
330         }
331         $uu = clone($this);
332         $this->lang = $val;
333         $this->update($uu);
334
335     }
336             
337     
338     function authUserArray()
339     {
340         
341         $aur = $this->toArray();
342         
343         if ($this->id < 1) {
344             return $aur;
345         }
346         
347         
348         //DB_DataObject::debugLevel(1);
349         $c = DB_Dataobject::factory('Companies');
350         $im = DB_Dataobject::factory('Images');
351         $c->joinAdd($im, 'LEFT');
352         $c->selectAdd();
353         $c->selectAs($c, 'company_id_%s');
354         $c->selectAs($im, 'company_id_logo_id_%s');
355         $c->id = $this->company_id;
356         $c->limit(1);
357         $c->find(true);
358         
359         $aur = array_merge( $c->toArray(),$aur);
360         
361         if (empty($c->company_id_logo_id_id))  {
362                  
363             $im = DB_Dataobject::factory('Images');
364             $im->ontable = 'Companies';
365             $im->onid = $c->id;
366             $im->imgtype = 'LOGO';
367             $im->limit(1);
368             $im->selectAdd();
369             $im->selectAs($im,  'company_id_logo_id_%s');
370             if ($im->find(true)) {
371                     
372                 foreach($im->toArray() as $k=>$v) {
373                     $aur[$k] = $v;
374                 }
375             }
376         }
377       
378         // perms + groups.
379         $aur['perms']  = $this->getPerms();
380         $g = DB_DataObject::Factory('Group_Members');
381         $aur['groups']  = $g->listGroupMembership($this, 'name');
382         
383         $aur['passwd'] = '';
384         $aur['dailykey'] = '';
385         
386         
387         
388         return $aur;
389     }
390     
391     //   ----------PERMS------  ----------------
392     function getPerms() 
393     {
394          //DB_DataObject::debugLevel(1);
395         // find out all the groups they are a member of.. + Default..
396         
397         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
398         
399         $g = DB_DataObject::Factory('Group_Rights');
400         if (!$g->count()) {
401             $g->genDefault();
402         }
403         
404         if ($this->id < 0) {
405             return $g->adminRights(); // system is not set up - so they get full rights.
406         }
407         //DB_DataObject::debugLevel(1);
408         $g = DB_DataObject::Factory('Group_Members');
409         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
410         if (!$g->count()) {
411             // add the current user to the admin group..
412             $g = DB_DataObject::Factory('Groups');
413             if ($g->get('name', 'Administrators')) {
414                 $gm = DB_DataObject::Factory('Group_Members');
415                 $gm->group_id = $g->id;
416                 $gm->user_id = $this->id;
417                 $gm->insert();
418             }
419             
420         }
421         
422         // ------ STANDARD PERMISSION HANDLING.
423         
424         $g = DB_DataObject::Factory('Group_Members');
425         $grps = $g->listGroupMembership($this);
426        //var_dump($grps);
427         $isAdmin = $g->inAdmin;
428         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
429         // the load all the perms for those groups, and add them all together..
430         // then load all those 
431         $g = DB_DataObject::Factory('Group_Rights');
432         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin);
433         //echo '<PRE>';print_r($ret);
434         return $ret;
435          
436         
437     }
438     /**
439      *Basic group fetching - probably needs to filter by type eventually.
440      *
441      */
442     
443     function groups()
444     {
445         $g = DB_DataObject::Factory('Group_Members');
446         $grps = $g->listGroupMembership($this);
447         $g = DB_DataObject::Factory('Groups');
448         $g->whereAddIn('id', $grps, 'int');
449         return $g->fetchAll();
450         
451     }
452     
453     function hasPerm($name, $lvl) 
454     {
455         static $pcache = array();
456         
457         if (!isset($pcache[$this->id])) {
458             $pcache[$this->id] = $this->getPerms();
459         }
460        // echo "<PRE>";print_r($pcache[$au->id]);
461        // var_dump($pcache[$au->id]);
462         if (empty($pcache[$this->id][$name])) {
463             return false;
464         }
465         
466         return strpos($pcache[$this->id][$name], $lvl) > -1;
467         
468     }    
469     
470     //  ------------ROO HOOKS------------------------------------
471     function applyFilters($q, $au, $roo)
472     {
473         //DB_DataObject::DebugLevel(1);
474         if (!empty($q['query']['person_not_internal'])) {
475             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
476         }
477         if (!empty($q['query']['person_internal_only_all'])) {
478             
479             
480             // must be internal and not current user (need for distribution list)
481             // user has a projectdirectory entry and role is not blank.
482             //DB_DataObject::DebugLevel(1);
483             $pd = DB_DataObject::factory('ProjectDirectory');
484             $pd->whereAdd("role != ''");
485             $pd->selectAdd();
486             $pd->selectAdd('distinct(person_id) as person_id');
487             $roled = $pd->fetchAll('person_id');
488             $rs = $roled  ? "  OR
489                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
490                     " : '';
491             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
492             
493         }
494         // -- for distribution
495         if (!empty($q['query']['person_internal_only'])) {
496             // must be internal and not current user (need for distribution list)
497             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
498             
499             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
500             //    ".id  != ".$au->id);
501             $this->whereAdd("Person.id != {$au->id}");
502         } 
503         
504         if (!empty($q['query']['comptype_or_company_id'])) {
505            // DB_DataObject::debugLevel(1);
506             $bits = explode(',', $q['query']['comptype_or_company_id']);
507             $id = (int) array_pop($bits);
508             $ct = $this->escape($bits[0]);
509             
510             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
511             
512         }
513         
514         
515         // staff list..
516         if (!empty($q['query']['person_inactive'])) {
517            // DB_Dataobject::debugLevel(1);
518             $this->active = 1;
519         }
520         $tn_p = $this->tableName();
521         $tn_gm = DB_DataObject::Factory('Group_Members')->tableName();
522         $tn_g = DB_DataObject::Factory('Groups')->tableName();
523
524         ///---------------- Group views --------
525         if (!empty($q['query']['in_group'])) {
526             // DB_DataObject::debugLevel(1);
527             $ing = (int) $q['query']['in_group'];
528             if ($q['query']['in_group'] == -1) {
529              
530                 // list all staff who are not in a group.
531                 $this->whereAdd("Person.id NOT IN (
532                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
533                         $tn_g ON $tn_g.id = $tn_gm.group_id
534                         WHERE $tn_g.type = ".$q['query']['type']."
535                     )");
536                 
537                 
538             } else {
539                 
540                 $this->whereAdd("$tn_p.id IN (
541                     SELECT distinct(user_id) FROM $tn_gm
542                         WHERE group_id = $ing
543                     )");
544                }
545             
546         }
547         
548         if (!empty($q['query']['not_in_directory'])) { 
549             // it's a Person list..
550             // DB_DATaobjecT::debugLevel(1);
551             
552             // specific to project directory which is single comp. login
553             //
554             $owncomp = DB_DataObject::Factory('Companies');
555             $owncomp->get('comptype', 'OWNER');
556             if ($q['company_id'] == $owncomp->id) {
557                 $this->active =1;
558             }
559             
560             
561
562             if ( $q['query']['not_in_directory'] > -1) {
563                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
564                 // can list current - so that it does not break!!!
565                 $x->whereAdd("$tn_p.id NOT IN 
566                     ( SELECT distinct person_id FROM $tn_pd WHERE
567                         project_id = " . $q['query']['not_in_directory'] . " AND 
568                         company_id = " . $this->company_id . ')');
569             }
570         }
571         
572         
573         if (!empty($q['query']['project_member_of'])) {
574                // this is also a flag to return if they are a member..
575             //DB_DataObject::debugLevel(1);
576             $do = DB_DataObject::factory('ProjectDirectory');
577             $do->project_id = $q['query']['project_member_of'];
578             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
579             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
580             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
581                 
582                 
583             if (!empty($q['query']['project_member_filter'])) {
584                 $this->having('is_member !=0');
585             
586             }
587             
588         }
589         
590         
591         if (!empty($q['query']['search'])) {
592             $s = $this->escape($q['query']['search']);
593                     $this->whereAdd("
594                         $tn_p.name LIKE '%$s%'  OR
595                         $tn_p.email LIKE '%$s%'  OR
596                         $tn_p.role LIKE '%$s%'  OR
597                         $tn_p.remarks LIKE '%$s%' 
598                         
599                     ");
600         }
601         
602         //
603     }
604     function setFromRoo($ar, $roo)
605     {
606         $this->setFrom($ar);
607         if (!empty($ar['passwd1'])) {
608             $this->setPassword($ar['passwd1']);
609         }
610         
611         
612         if (    $this->id &&
613                 ($this->email == $roo->old->email)&&
614                 ($this->company_id == $roo->old->company_id)
615             ) {
616             return true;
617         }
618         if (empty($this->email)) {
619             return true;
620         }
621         $xx = DB_Dataobject::factory('Person');
622         $xx->setFrom(array(
623             'email' => $this->email,
624            // 'company_id' => $x->company_id
625         ));
626         
627         if ($xx->count()) {
628             return "Duplicate Email found";
629         }
630         return true;
631     }
632     /**
633      *
634      * before Delete - delete significant dependancies..
635      * this is called after checkPerm..
636      */
637     
638     function beforeDelete()
639     {
640         
641         $e = DB_DataObject::Factory('Events');
642         $e->whereAdd('person_id = ' . $this->id);
643         $e->delete(true);
644         
645         // anything else?  
646         
647     }
648     
649     
650     /***
651      * Check if the a user has access to modify this item.
652      * @param String $lvl Level (eg. Core.Projects)
653      * @param Pman_Core_DataObjects_Person $au The authenticated user.
654      * @param boolean $changes alllow changes???
655      *
656      * @return false if no access..
657      */
658     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
659     {
660          
661        // do we have an empty system..
662         if ($au && $au->id == -1) {
663             return true;
664         }
665         
666         // determine if it's staff!!!
667          
668         if ($au->company()->comptype != 'OWNER') {
669             
670             // - can not change company!!!
671             if ($changes && 
672                 isset($changes['company_id']) && 
673                 $changes['company_id'] != $au->company_id) {
674                 return false;
675             }
676             // can only set new emails..
677             if ($changes && 
678                     !empty($this->email) && 
679                     isset($changes['email']) && 
680                     $changes['email'] != $this->email) {
681                 return false;
682             }
683             
684             // edit self... - what about other staff members...
685             
686             return $this->company_id == $au->company_id;
687         }
688          
689          
690         // yes, only owner company can mess with this...
691         $owncomp = DB_DataObject::Factory('Companies');
692         $owncomp->get('comptype', 'OWNER');
693         
694         $isStaff = ($this->company_id ==  $owncomp->id);
695         
696     
697         switch ($lvl) {
698             // extra case change passwod?
699             case 'P': //??? password
700                 // standard perms -- for editing + if the user is dowing them selves..
701                 $ret = $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
702                 return $ret || $au->id == $this->id;
703             
704             case 'S': // list..
705                 return $au->hasPerm("Core.Person", "S");
706             
707             case 'E': // edit
708                 return $isStaff ? $au->hasPerm("Core.Person", "E") : $au->hasPerm("Core.Staff", "E");
709             
710             case 'A': // add
711                 return $isStaff ? $au->hasPerm("Core.Person", "A") : $au->hasPerm("Core.Staff", "A");
712             
713             case 'D': // add
714                 return $isStaff ? $au->hasPerm("Core.Person", "D") : $au->hasPerm("Core.Staff", "D");
715         
716         }
717         return false;
718     }
719     function onInsert($req, $roo)  
720     {
721         
722         if ($roo->authUser->id < 0) {
723             $g = DB_DataObject::factory('Groups');
724             $g->type = 0;
725             $g->get('name', 'Administrators');
726             
727             $p = DB_DataObject::factory('Group_Members');
728             $p->group_id = $g->id;
729             $p->user_id = $this->id;     
730             if (!$p->count()) {
731                 $p->insert();
732                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
733             }
734             $this->login();
735         }
736         if (!empty($req['project_id_addto'])) {
737             $pd = DB_DataObject::factory('ProjectDirectory');
738             $pd->project_id = $req['project_id_addto'];
739             $pd->person_id = $this->id; 
740             $pd->ispm =0;
741             $pd->office_id = $this->office_id;
742             $pd->company_id = $this->company_id;
743             $pd->insert();
744         }
745         
746     }
747  }