3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Person extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Person'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $email; // string(128) not_null
16 public $company_id; // int(11)
17 public $office_id; // int(11)
19 public $name; // string(128) not_null
20 public $firstname; // string(128) not_null
21 public $lastname; // string(128) not_null
22 public $phone; // string(32) not_null
23 public $fax; // string(32) not_null
25 public $role; // string(32) not_null
26 public $remarks; // blob(65535) not_null blob
27 public $passwd; // string(64) not_null
28 public $owner_id; // int(11) not_null
29 public $lang; // string(8)
30 public $no_reset_sent; // int(11)
31 public $action_type; // string(32)
32 public $project_id; // int(11)
35 public $active; // int(11) not_null
36 public $deleted_by; // int(11) not_null
37 public $deleted_dt; // datetime(19) binary
40 /* the code above is auto generated do not remove the tag below */
44 * @param {String} $templateFile (mail/XXXXXXX.txt) exclude the mail and .txt bit.
45 * @param {Array|Object} $args data to send out..
46 * @return {Array|PEAR_Error} array of $recipents, $header, $body
48 function buildMail($templateFile, $args)
51 $args = (array) $args;
52 $content = clone($this);
54 foreach((array)$args as $k=>$v) {
58 $ff = HTML_FlexyFramework::get();
61 //?? is this really the place for this???
64 empty($args['no_auth']) &&
65 !in_array($templateFile, array(
66 // templates that can be sent without authentication.
72 $content->authUser = $this->getAuthUser();
73 if (!$content->authUser) {
74 return PEAR::raiseError("Not authenticated");
78 // should handle x-forwarded...
80 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
81 $_SERVER["HTTP_HOST"] :
82 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
84 /* use the regex compiler, as it doesnt parse <tags */
87 'compiler' => 'Flexy',
89 'filters' => array('SimpleTags','Mail'),
95 if (!empty($args['templateDir'])) {
96 $tops['templateDir'] = $args['templateDir'];
101 require_once 'HTML/Template/Flexy.php';
102 $template = new HTML_Template_Flexy( $tops );
103 $template->compile("mail/$templateFile.txt");
105 /* use variables from this object to ouput data. */
106 $mailtext = $template->bufferedOutputObject($content);
109 // if a html file with the same name exists, use that as the body
110 // I've no idea where this code went, it was here before..
111 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
112 $tops['nonHTML'] = false;
113 $template = new HTML_Template_Flexy( $tops );
114 $template->compile("mail/$templateFile.html");
115 $htmlbody = $template->bufferedOutputObject($content);
121 //echo "<PRE>";print_R($mailtext);
122 //print_R($mailtext);exit;
123 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
124 require_once 'Mail/mimeDecode.php';
125 require_once 'Mail.php';
127 $decoder = new Mail_mimeDecode($mailtext);
128 $parts = $decoder->getSendArray();
130 if (PEAR::isError($parts)) {
132 //echo "PROBLEM: {$parts->message}";
135 list($recipents,$headers,$body) = $parts;
136 $recipents = array($this->email);
137 if (!empty($content->bcc) && is_array($content->bcc)) {
138 $recipents =array_merge($recipents, $content->bcc);
140 $headers['Date'] = date('r');
143 if ($htmlbody !== false) {
144 $mime = new Mail_mime(array('eol' => "\n"));
145 $mime->setHeaders($headers);
146 $mime->setTXTBody($body);
147 $mime->setHTMLBody($htmlbody);
148 // I think there might be code in mediaoutreach toEmail somewhere
149 // h embeds images here..
150 $body = $mime->get();
151 $hdrs = $mime->headers($hdrs);
160 'recipients' => $recipents,
161 'headers' => $headers,
171 * - user must be authenticate or args[no_auth] = true
172 * or template = password_[reset|welcome]
175 function sendTemplate($templateFile, $args)
178 $ar = $this->buildMail($templateFile, $args);
181 //print_r($recipents);exit;
182 $mailOptions = PEAR::getStaticProperty('Mail','options');
183 $mail = Mail::factory("SMTP",$mailOptions);
185 if (PEAR::isError($mail)) {
188 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
189 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
190 error_reporting($oe);
199 function getEmailFrom()
201 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
203 function toEventString()
205 return empty($this->name) ? $this->email : $this->name;
207 function verifyAuth()
209 $ff= HTML_FlexyFramework::get();
210 if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
211 $ff->page->jerr("Login not permited to outside companies");
218 // ---------------- authentication / passwords and keys stuff ----------------
221 $db = $this->getDatabaseConnection();
222 // we combine db + project names,
223 // otherwise if projects use different 'auth' objects
224 // then we get unserialize issues.
225 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
229 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
231 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
233 $u = DB_DataObject::factory('Person');
234 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
240 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
244 $u = DB_DataObject::factory('Person');
245 $ff = HTML_FlexyFramework::get();
246 if (!empty($ff->Pman['local_autoauth']) &&
247 (!empty($_SERVER['SERVER_ADDR'])) &&
248 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
249 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
250 $u->get('email', $ff->Pman['local_autoauth'])
252 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
257 $u = DB_DataObject::factory('Person');
259 if (!empty($_SERVER['PHP_AUTH_USER'])
261 !empty($_SERVER['PHP_AUTH_PW'])
263 $u->get('email', $_SERVER['PHP_AUTH_USER'])
265 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
267 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
274 // not in session or not matched...
275 $u = DB_DataObject::factory('Person');
276 $u->whereAdd(' LENGTH(passwd) > 0');
278 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
280 die($error->toString()); // not really a good thing to do...
282 if (!$n){ // authenticated as there are no users in the system...
289 function getAuthUser()
291 if (!$this->isAuth()) {
294 $db = $this->getDatabaseConnection();
295 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
297 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
298 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
300 $u = DB_DataObject::factory('Person');
301 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
307 $u = DB_DataObject::factory('Person');
308 $u->whereAdd(' LENGTH(passwd) > 0');
310 $u = DB_DataObject::factory('Person');
319 $this->isAuth(); // force session start..
321 $db = $this->getDatabaseConnection();
322 // refresh admin group if we are logged in as one..
323 //DB_DataObject::debugLevel(1);
324 $g = DB_DataObject::factory('Groups');
326 $g->get('name', 'Administrators');
327 $gm = DB_DataObject::Factory('group_members');
328 if (in_array($g->id,$gm->listGroupMembership($this))) {
329 // refresh admin groups.
330 $gr = DB_DataObject::Factory('group_rights');
331 $gr->applyDefs($g, 0);
334 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
335 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
340 $this->isAuth(); // force session start..
341 $db = $this->getDatabaseConnection();
342 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
343 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
346 function genPassKey ($t)
348 return md5($this->email . $t. $this->passwd);
350 function simpleAuthKey($m = 0)
352 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
354 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
356 function checkPassword($val)
359 if (substr($this->passwd,0,1) == '$') {
360 return crypt($val,$this->passwd) == $this->passwd ;
362 // old style md5 passwords...- cant be used with courier....
363 return md5($val) == $this->passwd;
365 function setPassword($value)
368 while(strlen($salt)<9) {
369 $salt.=chr(rand(64,126));
370 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
372 $this->passwd = crypt($value, '$1$'. $salt. '$');
379 $x = DB_DataObject::factory('Companies');
380 $x->get($this->company_id);
383 function loadCompany()
385 $this->company = $this->company();
390 return $this->active;
392 function authUserName($n) // set username prior to acheck user exists query.
395 $this->whereAdd('LENGTH(passwd) > 1');
400 if ($val == $this->lang) {
410 function authUserArray()
413 $aur = $this->toArray();
420 //DB_DataObject::debugLevel(1);
421 $c = DB_Dataobject::factory('Companies');
422 $im = DB_Dataobject::factory('Images');
423 $c->joinAdd($im, 'LEFT');
425 $c->selectAs($c, 'company_id_%s');
426 $c->selectAs($im, 'company_id_logo_id_%s');
427 $c->id = $this->company_id;
431 $aur = array_merge( $c->toArray(),$aur);
433 if (empty($c->company_id_logo_id_id)) {
435 $im = DB_Dataobject::factory('Images');
436 $im->ontable = 'Companies';
438 $im->imgtype = 'LOGO';
441 $im->selectAs($im, 'company_id_logo_id_%s');
442 if ($im->find(true)) {
444 foreach($im->toArray() as $k=>$v) {
451 $aur['perms'] = $this->getPerms();
452 $g = DB_DataObject::Factory('group_members');
453 $aur['groups'] = $g->listGroupMembership($this, 'name');
456 $aur['dailykey'] = '';
463 // ----------PERMS------ ----------------
466 //DB_DataObject::debugLevel(1);
467 // find out all the groups they are a member of.. + Default..
469 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
471 $g = DB_DataObject::Factory('group_rights');
477 return $g->adminRights(); // system is not set up - so they get full rights.
479 //DB_DataObject::debugLevel(1);
480 $g = DB_DataObject::Factory('group_members');
481 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
483 // add the current user to the admin group..
484 $g = DB_DataObject::Factory('Groups');
485 if ($g->get('name', 'Administrators')) {
486 $gm = DB_DataObject::Factory('group_members');
487 $gm->group_id = $g->id;
488 $gm->user_id = $this->id;
494 // ------ STANDARD PERMISSION HANDLING.
495 $isOwner = $this->company()->comptype == 'OWNER';
496 $g = DB_DataObject::Factory('group_members');
497 $grps = $g->listGroupMembership($this);
499 $isAdmin = $g->inAdmin;
500 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
501 // the load all the perms for those groups, and add them all together..
502 // then load all those
503 $g = DB_DataObject::Factory('group_rights');
504 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
505 //echo '<PRE>';print_r($ret);
511 *Basic group fetching - probably needs to filter by type eventually.
513 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
516 function groups($what=false)
518 $g = DB_DataObject::Factory('group_members');
519 $grps = $g->listGroupMembership($this);
520 $g = DB_DataObject::Factory('Groups');
521 $g->whereAddIn('id', $grps, 'int');
522 return $g->fetchAll($what);
526 function hasPerm($name, $lvl)
528 static $pcache = array();
530 if (!isset($pcache[$this->id])) {
531 $pcache[$this->id] = $this->getPerms();
533 // echo "<PRE>";print_r($pcache[$au->id]);
534 // var_dump($pcache[$au->id]);
535 if (empty($pcache[$this->id][$name])) {
539 return strpos($pcache[$this->id][$name], $lvl) > -1;
543 // ------------ROO HOOKS------------------------------------
544 function applyFilters($q, $au, $roo)
546 //DB_DataObject::DebugLevel(1);
547 if (!empty($q['query']['person_not_internal'])) {
548 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
552 if (!empty($q['query']['person_internal_only_all'])) {
555 // must be internal and not current user (need for distribution list)
556 // user has a projectdirectory entry and role is not blank.
557 //DB_DataObject::DebugLevel(1);
558 $pd = DB_DataObject::factory('ProjectDirectory');
559 $pd->whereAdd("role != ''");
561 $pd->selectAdd('distinct(person_id) as person_id');
562 $roled = $pd->fetchAll('person_id');
564 {$this->tableName()}.id IN (".implode(',', $roled) . ")
566 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
569 // -- for distribution
570 if (!empty($q['query']['person_internal_only'])) {
571 // must be internal and not current user (need for distribution list)
572 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
574 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
575 // ".id != ".$au->id);
576 $this->whereAdd("Person.id != {$au->id}");
579 if (!empty($q['query']['comptype_or_company_id'])) {
580 // DB_DataObject::debugLevel(1);
581 $bits = explode(',', $q['query']['comptype_or_company_id']);
582 $id = (int) array_pop($bits);
583 $ct = $this->escape($bits[0]);
585 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
591 if (!empty($q['query']['person_inactive'])) {
592 // DB_Dataobject::debugLevel(1);
595 $tn_p = $this->tableName();
596 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
597 $tn_g = DB_DataObject::Factory('Groups')->tableName();
599 ///---------------- Group views --------
600 if (!empty($q['query']['in_group'])) {
601 // DB_DataObject::debugLevel(1);
602 $ing = (int) $q['query']['in_group'];
603 if ($q['query']['in_group'] == -1) {
605 // list all staff who are not in a group.
606 $this->whereAdd("Person.id NOT IN (
607 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
608 $tn_g ON $tn_g.id = $tn_gm.group_id
609 WHERE $tn_g.type = ".$q['query']['type']."
615 $this->whereAdd("$tn_p.id IN (
616 SELECT distinct(user_id) FROM $tn_gm
617 WHERE group_id = $ing
623 if (!empty($q['query']['not_in_directory'])) {
624 // it's a Person list..
625 // DB_DATaobjecT::debugLevel(1);
627 // specific to project directory which is single comp. login
629 $owncomp = DB_DataObject::Factory('Companies');
630 $owncomp->get('comptype', 'OWNER');
631 if ($q['company_id'] == $owncomp->id) {
637 if ( $q['query']['not_in_directory'] > -1) {
638 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
639 // can list current - so that it does not break!!!
640 $this->whereAdd("$tn_p.id NOT IN
641 ( SELECT distinct person_id FROM $tn_pd WHERE
642 project_id = " . $q['query']['not_in_directory'] . " AND
643 company_id = " . $this->company_id . ')');
647 if (!empty($q['query']['role'])) {
648 // it's a Person list..
649 // DB_DATaobjecT::debugLevel(1);
651 // specific to project directory which is single comp. login
653 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
654 // can list current - so that it does not break!!!
655 $this->whereAdd("$tn_p.id IN
656 ( SELECT distinct person_id FROM $tn_pd WHERE
657 role = '". $this->escape($q['query']['role']) ."'
663 if (!empty($q['query']['project_member_of'])) {
664 // this is also a flag to return if they are a member..
665 //DB_DataObject::debugLevel(1);
666 $do = DB_DataObject::factory('ProjectDirectory');
667 $do->project_id = $q['query']['project_member_of'];
668 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
669 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
670 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
673 if (!empty($q['query']['project_member_filter'])) {
674 $this->having('is_member !=0');
681 if (!empty($q['query']['search'])) {
682 $s = $this->escape($q['query']['search']);
684 $tn_p.name LIKE '%$s%' OR
685 $tn_p.email LIKE '%$s%' OR
686 $tn_p.role LIKE '%$s%' OR
687 $tn_p.remarks LIKE '%$s%'
694 function setFromRoo($ar, $roo)
697 if (!empty($ar['passwd1'])) {
698 $this->setPassword($ar['passwd1']);
703 ($this->email == $roo->old->email)&&
704 ($this->company_id == $roo->old->company_id)
708 if (empty($this->email)) {
711 $xx = DB_Dataobject::factory('Person');
713 'email' => $this->email,
714 // 'company_id' => $x->company_id
718 return "Duplicate Email found";
724 * before Delete - delete significant dependancies..
725 * this is called after checkPerm..
728 function beforeDelete()
731 $e = DB_DataObject::Factory('Events');
732 $e->whereAdd('person_id = ' . $this->id);
741 * Check if the a user has access to modify this item.
742 * @param String $lvl Level (eg. Core.Projects)
743 * @param Pman_Core_DataObjects_Person $au The authenticated user.
744 * @param boolean $changes alllow changes???
746 * @return false if no access..
748 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
751 // do we have an empty system..
752 if ($au && $au->id == -1) {
756 // determine if it's staff!!!
758 if ($au->company()->comptype != 'OWNER') {
760 // - can not change company!!!
762 isset($changes['company_id']) &&
763 $changes['company_id'] != $au->company_id) {
766 // can only set new emails..
768 !empty($this->email) &&
769 isset($changes['email']) &&
770 $changes['email'] != $this->email) {
774 // edit self... - what about other staff members...
776 return $this->company_id == $au->company_id;
780 // yes, only owner company can mess with this...
781 $owncomp = DB_DataObject::Factory('Companies');
782 $owncomp->get('comptype', 'OWNER');
784 $isStaff = ($this->company_id == $owncomp->id);
788 // extra case change passwod?
789 case 'P': //??? password
790 // standard perms -- for editing + if the user is dowing them selves..
791 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
792 return $ret || $au->id == $this->id;
795 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
800 function onInsert($req, $roo)
803 if ($roo->authUser->id < 0) {
804 $g = DB_DataObject::factory('Groups');
806 $g->get('name', 'Administrators');
808 $p = DB_DataObject::factory('group_members');
809 $p->group_id = $g->id;
810 $p->user_id = $this->id;
813 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
817 if (!empty($req['project_id_addto'])) {
818 $pd = DB_DataObject::factory('ProjectDirectory');
819 $pd->project_id = $req['project_id_addto'];
820 $pd->person_id = $this->id;
822 $pd->office_id = $this->office_id;
823 $pd->company_id = $this->company_id;