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