3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'Person'; // table name
14 public $id; // int(11) not_null primary_key auto_increment
15 public $email; // string(128) not_null
18 public $company_id; // int(11)
19 public $office_id; // int(11)
20 public $name; // string(128) not_null
21 public $firstname; // string(128) not_null
22 public $lastname; // string(128) not_null
23 public $phone; // string(32) not_null
24 public $fax; // string(32) not_null
26 public $role; // string(32) not_null
27 public $remarks; // blob(65535) not_null blob
28 public $passwd; // string(64) not_null
29 public $owner_id; // int(11) not_null
30 public $lang; // string(8)
31 public $no_reset_sent; // int(11)
32 public $action_type; // string(32)
33 public $project_id; // int(11)
36 public $active; // int(11) not_null
37 public $deleted_by; // int(11) not_null
38 public $deleted_dt; // datetime(19) binary
41 public $name_facebook; // VARCHAR(128) NULL;
42 public $url_blog; // VARCHAR(256) NULL ;
43 public $url_twitter; // VARCHAR(256) NULL ;
44 public $url_linkedin; // VARCHAR(256) NULL ;
46 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
47 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 /* the code above is auto generated do not remove the tag below */
54 $p = DB_DataObject::Factory('Person');
55 $p->get($this->owner_id);
64 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
70 function buildMail($templateFile, $args)
73 $args = (array) $args;
74 $content = clone($this);
76 foreach((array)$args as $k=>$v) {
80 $ff = HTML_FlexyFramework::get();
83 //?? is this really the place for this???
86 empty($args['no_auth']) &&
87 !in_array($templateFile, array(
88 // templates that can be sent without authentication.
94 $content->authUser = $this->getAuthUser();
95 if (!$content->authUser) {
96 return PEAR::raiseError("Not authenticated");
100 // should handle x-forwarded...
102 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
103 $_SERVER["HTTP_HOST"] :
104 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
106 /* use the regex compiler, as it doesnt parse <tags */
109 'compiler' => 'Flexy',
111 'filters' => array('SimpleTags','Mail'),
117 if (!empty($args['templateDir'])) {
118 $tops['templateDir'] = $args['templateDir'];
123 require_once 'HTML/Template/Flexy.php';
124 $template = new HTML_Template_Flexy( $tops );
125 $template->compile("mail/$templateFile.txt");
127 /* use variables from this object to ouput data. */
128 $mailtext = $template->bufferedOutputObject($content);
131 // if a html file with the same name exists, use that as the body
132 // I've no idea where this code went, it was here before..
133 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
134 $tops['nonHTML'] = false;
135 $template = new HTML_Template_Flexy( $tops );
136 $template->compile("mail/$templateFile.html");
137 $htmlbody = $template->bufferedOutputObject($content);
143 //echo "<PRE>";print_R($mailtext);
144 //print_R($mailtext);exit;
145 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
146 require_once 'Mail/mimeDecode.php';
147 require_once 'Mail.php';
149 $decoder = new Mail_mimeDecode($mailtext);
150 $parts = $decoder->getSendArray();
152 if (PEAR::isError($parts)) {
154 //echo "PROBLEM: {$parts->message}";
157 list($recipents,$headers,$body) = $parts;
158 $recipents = array($this->email);
159 if (!empty($content->bcc) && is_array($content->bcc)) {
160 $recipents =array_merge($recipents, $content->bcc);
162 $headers['Date'] = date('r');
164 if ($htmlbody !== false) {
165 require_once 'Mail/mime.php';
166 $mime = new Mail_mime(array('eol' => "\n"));
167 $mime->setTXTBody($body);
168 $mime->setHTMLBody($htmlbody);
169 // I think there might be code in mediaoutreach toEmail somewhere
170 // h embeds images here..
171 $body = $mime->get();
172 $headers = $mime->headers($headers);
179 'recipients' => $recipents,
180 'headers' => $headers,
190 * - user must be authenticate or args[no_auth] = true
191 * or template = password_[reset|welcome]
194 function sendTemplate($templateFile, $args)
197 $ar = $this->buildMail($templateFile, $args);
200 //print_r($recipents);exit;
201 $mailOptions = PEAR::getStaticProperty('Mail','options');
202 $mail = Mail::factory("SMTP",$mailOptions);
204 if (PEAR::isError($mail)) {
207 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
208 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
209 error_reporting($oe);
218 function getEmailFrom()
220 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
222 function toEventString()
224 return empty($this->name) ? $this->email : $this->name;
226 function verifyAuth()
228 $ff= HTML_FlexyFramework::get();
229 if (!empty($ff->Pman['auth_comptype']) &&
230 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
233 // force a logout - without a check on the isAuth - as this is called from there..
234 $db = $this->getDatabaseConnection();
235 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
236 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
239 $ff->page->jerr("Login not permited to outside companies");
246 // ---------------- authentication / passwords and keys stuff ----------------
249 $db = $this->getDatabaseConnection();
250 // we combine db + project names,
251 // otherwise if projects use different 'auth' objects
252 // then we get unserialize issues.
253 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
258 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
260 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
262 $u = DB_DataObject::factory('Person');
263 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
265 return $u->verifyAuth();
271 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
275 $u = DB_DataObject::factory('Person');
276 $ff = HTML_FlexyFramework::get();
277 if (!empty($ff->Pman['local_autoauth']) &&
278 (!empty($_SERVER['SERVER_ADDR'])) &&
279 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
280 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
281 $u->get('email', $ff->Pman['local_autoauth'])
283 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
288 $u = DB_DataObject::factory('Person');
290 if (!empty($_SERVER['PHP_AUTH_USER'])
292 !empty($_SERVER['PHP_AUTH_PW'])
294 $u->get('email', $_SERVER['PHP_AUTH_USER'])
296 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
298 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
302 if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
306 // not in session or not matched...
307 $u = DB_DataObject::factory('Person');
308 $u->whereAdd(' LENGTH(passwd) > 0');
310 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $n;
311 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
313 die($error->toString()); // not really a good thing to do...
315 if (!$n){ // authenticated as there are no users in the system...
322 function getAuthUser()
324 if (!$this->isAuth()) {
327 $db = $this->getDatabaseConnection();
328 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
332 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
333 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
335 $u = DB_DataObject::factory('Person');
336 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
342 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
343 $u = DB_DataObject::factory('Person');
344 $u->whereAdd(' LENGTH(passwd) > 0');
345 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $u->count();
349 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
351 // fake person - open system..
352 //$ce = DB_DataObject::factory('core_enum');
356 $u = DB_DataObject::factory('Person');
365 $this->isAuth(); // force session start..
366 if (!$this->verifyAuth()) {
369 $db = $this->getDatabaseConnection();
372 // open up iptables at login..
373 $dbname = $this->database();
374 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
376 // refresh admin group if we are logged in as one..
377 //DB_DataObject::debugLevel(1);
378 $g = DB_DataObject::factory('Groups');
380 $g->get('name', 'Administrators');
381 $gm = DB_DataObject::Factory('group_members');
382 if (in_array($g->id,$gm->listGroupMembership($this))) {
383 // refresh admin groups.
384 $gr = DB_DataObject::Factory('group_rights');
385 $gr->applyDefs($g, 0);
388 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
389 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
394 $this->isAuth(); // force session start..
395 $db = $this->getDatabaseConnection();
396 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
397 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
400 function genPassKey ($t)
402 return md5($this->email . $t. $this->passwd);
404 function simpleAuthKey($m = 0)
406 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
408 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
410 function checkPassword($val)
413 if (substr($this->passwd,0,1) == '$') {
414 return crypt($val,$this->passwd) == $this->passwd ;
416 // old style md5 passwords...- cant be used with courier....
417 return md5($val) == $this->passwd;
419 function setPassword($value)
422 while(strlen($salt)<9) {
423 $salt.=chr(rand(64,126));
424 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
426 $this->passwd = crypt($value, '$1$'. $salt. '$');
431 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
433 require_once 'Text/Password.php';
434 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
435 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
436 $this->setPassword($this->rawPasswd);
437 return $this->rawPasswd;
442 $x = DB_DataObject::factory('Companies');
444 $x->get($this->company_id);
447 function loadCompany()
449 $this->company = $this->company();
454 return $this->active;
456 function authUserName($n) // set username prior to acheck user exists query.
459 $this->whereAdd('LENGTH(passwd) > 1');
464 if (!func_num_args()) {
467 $val = array_shift(func_get_args());
468 if ($val == $this->lang) {
478 function authUserArray()
481 $aur = $this->toArray();
488 //DB_DataObject::debugLevel(1);
489 $c = DB_Dataobject::factory('Companies');
490 $im = DB_Dataobject::factory('Images');
491 $c->joinAdd($im, 'LEFT');
493 $c->selectAs($c, 'company_id_%s');
494 $c->selectAs($im, 'company_id_logo_id_%s');
495 $c->id = $this->company_id;
499 $aur = array_merge( $c->toArray(),$aur);
501 if (empty($c->company_id_logo_id_id)) {
503 $im = DB_Dataobject::factory('Images');
504 $im->ontable = 'Companies';
506 $im->imgtype = 'LOGO';
509 $im->selectAs($im, 'company_id_logo_id_%s');
510 if ($im->find(true)) {
512 foreach($im->toArray() as $k=>$v) {
519 $aur['perms'] = $this->getPerms();
520 $g = DB_DataObject::Factory('group_members');
521 $aur['groups'] = $g->listGroupMembership($this, 'name');
524 $aur['dailykey'] = '';
531 // ----------PERMS------ ----------------
534 //DB_DataObject::debugLevel(1);
535 // find out all the groups they are a member of.. + Default..
537 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
539 $g = DB_DataObject::Factory('group_rights');
545 return $g->adminRights(); // system is not set up - so they get full rights.
547 //DB_DataObject::debugLevel(1);
548 $g = DB_DataObject::Factory('group_members');
549 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
551 // add the current user to the admin group..
552 $g = DB_DataObject::Factory('Groups');
553 if ($g->get('name', 'Administrators')) {
554 $gm = DB_DataObject::Factory('group_members');
555 $gm->group_id = $g->id;
556 $gm->user_id = $this->id;
562 // ------ STANDARD PERMISSION HANDLING.
563 $isOwner = $this->company()->comptype == 'OWNER';
564 $g = DB_DataObject::Factory('group_members');
565 $grps = $g->listGroupMembership($this);
567 $isAdmin = $g->inAdmin;
568 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
569 // the load all the perms for those groups, and add them all together..
570 // then load all those
571 $g = DB_DataObject::Factory('group_rights');
572 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
573 //echo '<PRE>';print_r($ret);
579 *Basic group fetching - probably needs to filter by type eventually.
581 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
584 function groups($what=false)
586 $g = DB_DataObject::Factory('group_members');
587 $grps = $g->listGroupMembership($this);
588 $g = DB_DataObject::Factory('Groups');
589 $g->whereAddIn('id', $grps, 'int');
590 return $g->fetchAll($what);
596 function hasPerm($name, $lvl)
598 static $pcache = array();
600 if (!isset($pcache[$this->id])) {
601 $pcache[$this->id] = $this->getPerms();
603 // echo "<PRE>";print_r($pcache[$au->id]);
604 // var_dump($pcache[$au->id]);
605 if (empty($pcache[$this->id][$name])) {
609 return strpos($pcache[$this->id][$name], $lvl) > -1;
613 // ------------ROO HOOKS------------------------------------
614 function applyFilters($q, $au, $roo)
616 //DB_DataObject::DebugLevel(1);
617 if (!empty($q['query']['person_not_internal'])) {
618 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
622 if (!empty($q['query']['person_internal_only_all'])) {
625 // must be internal and not current user (need for distribution list)
626 // user has a projectdirectory entry and role is not blank.
627 //DB_DataObject::DebugLevel(1);
628 $pd = DB_DataObject::factory('ProjectDirectory');
629 $pd->whereAdd("role != ''");
631 $pd->selectAdd('distinct(person_id) as person_id');
632 $roled = $pd->fetchAll('person_id');
634 {$this->tableName()}.id IN (".implode(',', $roled) . ")
636 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
639 // -- for distribution
640 if (!empty($q['query']['person_internal_only'])) {
641 // must be internal and not current user (need for distribution list)
642 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
644 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
645 // ".id != ".$au->id);
646 $this->whereAdd("Person.id != {$au->id}");
649 if (!empty($q['query']['comptype_or_company_id'])) {
650 // DB_DataObject::debugLevel(1);
651 $bits = explode(',', $q['query']['comptype_or_company_id']);
652 $id = (int) array_pop($bits);
653 $ct = $this->escape($bits[0]);
655 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
661 if (!empty($q['query']['person_inactive'])) {
662 // DB_Dataobject::debugLevel(1);
665 $tn_p = $this->tableName();
666 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
667 $tn_g = DB_DataObject::Factory('Groups')->tableName();
669 ///---------------- Group views --------
670 if (!empty($q['query']['in_group'])) {
671 // DB_DataObject::debugLevel(1);
672 $ing = (int) $q['query']['in_group'];
673 if ($q['query']['in_group'] == -1) {
675 // list all staff who are not in a group.
676 $this->whereAdd("Person.id NOT IN (
677 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
678 $tn_g ON $tn_g.id = $tn_gm.group_id
679 WHERE $tn_g.type = ".$q['query']['type']."
685 $this->whereAdd("$tn_p.id IN (
686 SELECT distinct(user_id) FROM $tn_gm
687 WHERE group_id = $ing
693 if (!empty($q['query']['not_in_directory'])) {
694 // it's a Person list..
695 // DB_DATaobjecT::debugLevel(1);
697 // specific to project directory which is single comp. login
699 $owncomp = DB_DataObject::Factory('Companies');
700 $owncomp->get('comptype', 'OWNER');
701 if ($q['company_id'] == $owncomp->id) {
707 if ( $q['query']['not_in_directory'] > -1) {
708 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
709 // can list current - so that it does not break!!!
710 $this->whereAdd("$tn_p.id NOT IN
711 ( SELECT distinct person_id FROM $tn_pd WHERE
712 project_id = " . $q['query']['not_in_directory'] . " AND
713 company_id = " . $this->company_id . ')');
717 if (!empty($q['query']['role'])) {
718 // it's a Person list..
719 // DB_DATaobjecT::debugLevel(1);
721 // specific to project directory which is single comp. login
723 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
724 // can list current - so that it does not break!!!
725 $this->whereAdd("$tn_p.id IN
726 ( SELECT distinct person_id FROM $tn_pd WHERE
727 role = '". $this->escape($q['query']['role']) ."'
733 if (!empty($q['query']['project_member_of'])) {
734 // this is also a flag to return if they are a member..
735 //DB_DataObject::debugLevel(1);
736 $do = DB_DataObject::factory('ProjectDirectory');
737 $do->project_id = $q['query']['project_member_of'];
738 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
739 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
740 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
743 if (!empty($q['query']['project_member_filter'])) {
744 $this->having('is_member !=0');
750 if (!empty($q['query']['search'])) {
752 // use our magic search builder...
754 require_once 'Text/SearchParser.php';
755 $x = new Text_SearchParser($q['query']['search']);
763 "join_company_id_id.name"
766 $str = $x->toSQL(array(
769 'company' => 'join_company_id_id.name',
770 //'country' => 'Clipping.country',
771 // 'media' => 'Clipping.media_name',
773 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
778 $this->whereAdd($str); /*
779 $tn_p.name LIKE '%$s%' OR
780 $tn_p.email LIKE '%$s%' OR
781 $tn_p.role LIKE '%$s%' OR
782 $tn_p.phone LIKE '%$s%' OR
783 $tn_p.remarks LIKE '%$s%'
790 function setFromRoo($ar, $roo)
793 if (!empty($ar['passwd1'])) {
794 $this->setPassword($ar['passwd1']);
799 ($this->email == $roo->old->email)&&
800 ($this->company_id == $roo->old->company_id)
804 if (empty($this->email)) {
807 $xx = DB_Dataobject::factory('Person');
809 'email' => $this->email,
810 // 'company_id' => $x->company_id
814 return "Duplicate Email found";
820 * before Delete - delete significant dependancies..
821 * this is called after checkPerm..
824 function beforeDelete()
827 $e = DB_DataObject::Factory('Events');
828 $e->whereAdd('person_id = ' . $this->id);
837 * Check if the a user has access to modify this item.
838 * @param String $lvl Level (eg. Core.Projects)
839 * @param Pman_Core_DataObjects_Person $au The authenticated user.
840 * @param boolean $changes alllow changes???
842 * @return false if no access..
844 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
847 // do we have an empty system..
848 if ($au && $au->id == -1) {
852 // determine if it's staff!!!
854 if ($au->company()->comptype != 'OWNER') {
856 // - can not change company!!!
858 isset($changes['company_id']) &&
859 $changes['company_id'] != $au->company_id) {
862 // can only set new emails..
864 !empty($this->email) &&
865 isset($changes['email']) &&
866 $changes['email'] != $this->email) {
870 // edit self... - what about other staff members...
872 return $this->company_id == $au->company_id;
876 // yes, only owner company can mess with this...
877 $owncomp = DB_DataObject::Factory('Companies');
878 $owncomp->get('comptype', 'OWNER');
880 $isStaff = ($this->company_id == $owncomp->id);
884 // extra case change passwod?
885 case 'P': //??? password
886 // standard perms -- for editing + if the user is dowing them selves..
887 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
888 return $ret || $au->id == $this->id;
891 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
896 function onInsert($req, $roo)
899 $p = DB_DataObject::factory('person');
900 if ($roo->authUser->id < 0 && $p->count() == 1) {
901 // this seems a bit risky...
903 $g = DB_DataObject::factory('Groups');
907 $g->get('name', 'Administrators');
909 $p = DB_DataObject::factory('group_members');
910 $p->group_id = $g->id;
911 $p->user_id = $this->id;
914 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
918 if (!empty($req['project_id_addto'])) {
919 $pd = DB_DataObject::factory('ProjectDirectory');
920 $pd->project_id = $req['project_id_addto'];
921 $pd->person_id = $this->id;
923 $pd->office_id = $this->office_id;
924 $pd->company_id = $this->company_id;
930 function importFromArray($roo, $persons, $prefix)
932 if (!is_array($persons) || empty($persons)) {
933 $roo->jerr("error in the person data. - empty on not valid");
935 DB_DataObject::factory('groups')->initGroups();
937 foreach($persons as $person){
938 $p = DB_DataObject::factory('person');
939 if($p->get('name', $person['name'])){
942 $p->setFrom($person);
944 $companies = DB_DataObject::factory('companies');
945 if(!$companies->get('comptype', 'OWNER')){
946 $roo->jerr("Missing OWNER companies!");
948 $p->company_id = $companies->pid();
949 // strip the 'spaces etc.. make lowercase..
950 $name = strtolower(str_replace(' ', '', $person['name']));
951 $p->setPassword("$prefix$name");
954 // if $person->groups is set.. then
955 // add this person to that group eg. groups : [ 'Administrator' ]
956 if(!empty($person['groups'])){
957 $groups = DB_DataObject::factory('groups');
958 if(!$groups->get('name', $person['groups'])){
959 $roo->jerr("Missing groups : {$person['groups']}");
961 $gm = DB_DataObject::factory('group_members');
962 $gm->change($p, $groups, true);
965 $p->onInsert(array(), $roo);