3 * Table Definition for Person
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'core_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 ;
45 public $linkedin_id; // VARCHAR(256) NULL ;
47 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
48 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 public $countries; // VARCHAR(128) NULL;
51 /* the code above is auto generated do not remove the tag below */
54 static $authUser = false;
59 $p = DB_DataObject::Factory($this->tableName());
60 $p->get($this->owner_id);
69 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
75 function buildMail($templateFile, $args)
78 $args = (array) $args;
79 $content = clone($this);
81 foreach((array)$args as $k=>$v) {
85 $ff = HTML_FlexyFramework::get();
88 //?? is this really the place for this???
91 empty($args['no_auth']) &&
92 !in_array($templateFile, array(
93 // templates that can be sent without authentication.
99 $content->authUser = $this->getAuthUser();
100 if (!$content->authUser) {
101 return PEAR::raiseError("Not authenticated");
105 // should handle x-forwarded...
107 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
108 $_SERVER["HTTP_HOST"] :
109 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
111 /* use the regex compiler, as it doesnt parse <tags */
114 'compiler' => 'Flexy',
116 'filters' => array('SimpleTags','Mail'),
122 if (!empty($args['templateDir'])) {
123 $tops['templateDir'] = $args['templateDir'];
128 require_once 'HTML/Template/Flexy.php';
129 $template = new HTML_Template_Flexy( $tops );
130 $template->compile("mail/$templateFile.txt");
132 /* use variables from this object to ouput data. */
133 $mailtext = $template->bufferedOutputObject($content);
136 // if a html file with the same name exists, use that as the body
137 // I've no idea where this code went, it was here before..
138 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
139 $tops['nonHTML'] = false;
140 $template = new HTML_Template_Flexy( $tops );
141 $template->compile("mail/$templateFile.html");
142 $htmlbody = $template->bufferedOutputObject($content);
148 //echo "<PRE>";print_R($mailtext);
149 //print_R($mailtext);exit;
150 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
151 require_once 'Mail/mimeDecode.php';
152 require_once 'Mail.php';
154 $decoder = new Mail_mimeDecode($mailtext);
155 $parts = $decoder->getSendArray();
157 if (is_a($parts,'PEAR_Error')) {
159 //echo "PROBLEM: {$parts->message}";
162 list($recipents,$headers,$body) = $parts;
163 $recipents = array($this->email);
164 if (!empty($content->bcc) && is_array($content->bcc)) {
165 $recipents =array_merge($recipents, $content->bcc);
167 $headers['Date'] = date('r');
169 if ($htmlbody !== false) {
170 require_once 'Mail/mime.php';
171 $mime = new Mail_mime(array('eol' => "\n"));
172 $mime->setTXTBody($body);
173 $mime->setHTMLBody($htmlbody);
174 // I think there might be code in mediaoutreach toEmail somewhere
175 // h embeds images here..
176 $body = $mime->get();
177 $headers = $mime->headers($headers);
181 'recipients' => $recipents,
182 'headers' => $headers,
190 * - user must be authenticate or args[no_auth] = true
191 * or template = password_[reset|welcome]
194 function sendTemplate($templateFile, $args)
196 $ar = $this->buildMail($templateFile, $args);
198 //print_r($recipents);exit;
199 $mailOptions = PEAR::getStaticProperty('Mail','options');
200 $mail = Mail::factory("SMTP",$mailOptions);
202 if (PEAR::isError($mail)) {
205 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
206 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
207 error_reporting($oe);
215 function getEmailFrom()
217 if (empty($this->name)) {
221 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
224 function toEventString()
226 return empty($this->name) ? $this->email : $this->name;
229 function verifyAuth()
231 $ff= HTML_FlexyFramework::get();
232 if (!empty($ff->Pman['auth_comptype']) &&
233 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
236 $sesPrefix = $this->sesPrefix();
238 self::$authUser = false;
239 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
243 //$ff->page->jerr("Login not permited to outside companies");
250 // ---------------- authentication / passwords and keys stuff ----------------
255 $ff= HTML_FlexyFramework::get();
257 $sesPrefix = $this->sesPrefix();
259 if (self::$authUser) {
260 return self::$authUser;
264 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
266 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
267 $u = DB_DataObject::factory($this->tableName());
268 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
269 if ($u->verifyAuth()) {
270 self::$authUser = $u;
274 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
275 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
276 setcookie('Pman.timeout', -1, time() + (30*60), '/');
281 $u = DB_DataObject::factory($this->tableName());
283 if (!empty($_SERVER['PHP_AUTH_USER'])
285 !empty($_SERVER['PHP_AUTH_PW'])
287 $u->get('email', $_SERVER['PHP_AUTH_USER'])
289 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
291 // logged in via http auth
293 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
294 self::$authUser = $u;
298 if (!$this->canInitializeSystem()) {
299 // die("can not init");
304 $auto_auth_allow = false;
305 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
306 $auto_auth_allow = true;
309 (!empty($_SERVER['SERVER_ADDR'])) &&
311 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
312 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
316 $_SERVER['SERVER_ADDR'] == '::1' &&
317 $_SERVER['REMOTE_ADDR'] == '::1'
321 $auto_auth_allow = true;
325 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
326 $auto_auth_allow = false;
328 //var_dump($auto_auth_allow);
330 $default_admin = false;
331 if ($auto_auth_allow) {
332 $group = DB_DataObject::factory('core_group');
333 $group->get('name', 'Administrators');
335 $member = DB_DataObject::factory('core_group_member');
337 $member->group_id = $group->id;
339 join_user_id_id.id IS NOT NULL
341 if($member->find(true)){
342 $default_admin = DB_DataObject::factory($this->tableName());
343 if(!$default_admin->get($member->user_id)){
344 $default_admin = false;
349 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
350 $u = DB_DataObject::factory($this->tableName());
351 $ff = HTML_FlexyFramework::get();
353 if ($auto_auth_allow &&
354 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
357 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
359 // if we request other URLS.. then we get auto logged in..
361 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
365 //var_dump(session_id());
366 //var_dump($_SESSION[__CLASS__]);
368 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
371 //die("got this far?");
372 // not in session or not matched...
373 $u = DB_DataObject::factory($this->tableName());
374 $u->whereAdd(' LENGTH(passwd) > 0');
376 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
377 if (class_exists('PEAR')) {
378 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
380 die($error->toString()); // not really a good thing to do...
383 if (!$n){ // authenticated as there are no users in the system...
390 function canInitializeSystem()
393 return !strcasecmp(get_class($this) , __CLASS__);
396 function getAuthUser()
398 if (!$this->isAuth()) {
402 $ff= HTML_FlexyFramework::get();
404 $sesPrefix = $this->sesPrefix();
406 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
408 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
409 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
411 $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
413 if ($u->get($a->id)) { /// && strlen($u->passwd)) { // should work out the pid .. really..
415 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
416 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
422 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
423 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
424 setcookie('Pman.timeout', -1, time() + (30*60), '/');
430 if (!$this->canInitializeSystem()) {
436 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
437 $u = DB_DataObject::factory($this->tableName());
438 $u->whereAdd(' LENGTH(passwd) > 0');
439 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
444 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
445 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
448 // fake person - open system..
449 //$ce = DB_DataObject::factory('core_enum');
453 $u = DB_DataObject::factory($this->tableName());
456 // if a company has been created fill that in in company_id_id
457 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
459 $u->company_id_id = $c->pid();
460 $u->company_id = $c->pid();
470 $this->isAuth(); // force session start..
471 if (!$this->verifyAuth()) { // check for company valid..
475 // open up iptables at login..
476 $dbname = $this->databaseNickname();
477 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
479 // refresh admin group if we are logged in as one..
480 //DB_DataObject::debugLevel(1);
481 $g = DB_DataObject::factory('core_group');
483 $g->get('name', 'Administrators');
484 $gm = DB_DataObject::Factory('core_group_member');
485 if (in_array($g->id,$gm->listGroupMembership($this))) {
486 // refresh admin groups.
487 $gr = DB_DataObject::Factory('core_group_right');
488 $gr->applyDefs($g, 0);
491 $sesPrefix = $this->sesPrefix();
493 // we should not store the whole data in the session - otherwise it get's huge.
494 $p = DB_DAtaObject::Factory($this->tableName());
495 $p->get($this->pid());
499 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
500 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
502 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
503 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
504 // ensure it's written so that ajax calls can fetch it..
511 $this->isAuth(); // force session start..
513 $sesPrefix = $this->sesPrefix();
515 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
517 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
520 function genPassKey ($t)
522 return md5($this->email . $t. $this->passwd);
524 function simpleAuthKey($m = 0)
526 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
528 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
531 function checkTwoFactorAuthentication($val)
535 // also used in login
536 require_once 'System.php';
540 empty($this->oath_key)
545 $oathtool = System::which('oathtool');
551 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
553 $password = exec($cmd);
555 return ($password == $val) ? true : false;
558 function checkPassword($val)
560 if (substr($this->passwd,0,1) == '$') {
561 if (function_exists('pasword_verify')) {
562 return password_verify($val, $this->passwd);
564 return crypt($val,$this->passwd) == $this->passwd ;
566 // old style md5 passwords...- cant be used with courier....
567 return md5($val) == $this->passwd;
570 function setPassword($value)
572 if (function_exists('pasword_hash')) {
573 return password_hash($value);
577 while(strlen($salt)<9) {
578 $salt.=chr(rand(64,126));
579 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
581 $this->passwd = crypt($value, '$1$'. $salt. '$');
586 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
588 require_once 'Text/Password.php';
589 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
590 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
591 $this->setPassword($this->rawPasswd);
592 return $this->rawPasswd;
597 $x = DB_DataObject::factory('core_company');
599 $x->get($this->company_id);
602 function loadCompany()
604 $this->company = $this->company();
609 return $this->active;
611 function authUserName($n) // set username prior to acheck user exists query.
614 $this->whereAdd('LENGTH(passwd) > 1');
619 if (!func_num_args()) {
622 $val = array_shift(func_get_args());
623 if ($val == $this->lang) {
633 function authUserArray()
636 $aur = $this->toArray();
643 //DB_DataObject::debugLevel(1);
644 $c = DB_Dataobject::factory('core_company');
645 $im = DB_Dataobject::factory('Images');
646 $c->joinAdd($im, 'LEFT');
648 $c->selectAs($c, 'company_id_%s');
649 $c->selectAs($im, 'company_id_logo_id_%s');
650 $c->id = $this->company_id;
654 $aur = array_merge( $c->toArray(),$aur);
656 if (empty($c->company_id_logo_id_id)) {
658 $im = DB_Dataobject::factory('Images');
659 $im->ontable = DB_DataObject::factory('core_company')->tableName();
661 $im->imgtype = 'LOGO';
664 $im->selectAs($im, 'company_id_logo_id_%s');
665 if ($im->find(true)) {
667 foreach($im->toArray() as $k=>$v) {
668 if (!preg_match('/^company_id_logo_id_/', $k)) {
677 $aur['perms'] = $this->getPerms();
678 $g = DB_DataObject::Factory('core_group_member');
679 $aur['groups'] = $g->listGroupMembership($this, 'name');
682 $aur['dailykey'] = '';
683 $aur['oath_key'] = '';
685 $aur['oath_key_enable'] = !empty($this->oath_key);
686 $aur['require_oath'] = 1;
688 $s = DB_DataObject::Factory('core_setting');
689 $oath_require = $s->lookup('core', 'two_factor_authentication_requirement');
690 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
695 // ----------PERMS------ ----------------
698 //DB_DataObject::debugLevel(1);
699 // find out all the groups they are a member of.. + Default..
701 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
703 $g = DB_DataObject::Factory('core_group_right');
709 return $g->adminRights(); // system is not set up - so they get full rights.
711 //DB_DataObject::debugLevel(1);
712 $g = DB_DataObject::Factory('core_group_member');
713 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
715 // add the current user to the admin group..
716 $g = DB_DataObject::Factory('core_group');
717 if ($g->get('name', 'Administrators')) {
718 $gm = DB_DataObject::Factory('core_group_member');
719 $gm->group_id = $g->id;
720 $gm->user_id = $this->id;
726 // ------ STANDARD PERMISSION HANDLING.
727 $isOwner = $this->company()->comptype == 'OWNER';
728 $g = DB_DataObject::Factory('core_group_member');
729 $grps = $g->listGroupMembership($this);
731 $isAdmin = $g->inAdmin; //??? what???
732 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
733 // the load all the perms for those groups, and add them all together..
734 // then load all those
735 $g = DB_DataObject::Factory('core_group_right');
736 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
737 //echo '<PRE>';print_r($ret);
743 *Basic group fetching - probably needs to filter by type eventually.
745 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
748 function groups($what=false)
750 $g = DB_DataObject::Factory('core_group_member');
751 $grps = $g->listGroupMembership($this);
752 $g = DB_DataObject::Factory('core_group');
753 $g->whereAddIn('id', $grps, 'int');
754 return $g->fetchAll($what);
760 function hasPerm($name, $lvl)
762 static $pcache = array();
764 if (!isset($pcache[$this->id])) {
765 $pcache[$this->id] = $this->getPerms();
768 // echo "<PRE>";print_r($pcache[$au->id]);
769 // var_dump($pcache[$au->id]);
770 if (empty($pcache[$this->id][$name])) {
774 return strpos($pcache[$this->id][$name], $lvl) > -1;
778 // ------------ROO HOOKS------------------------------------
779 function applyFilters($q, $au, $roo)
781 //DB_DataObject::DebugLevel(1);
782 if(!empty($q['_to_qr_code'])){
783 $person = DB_DataObject::factory('Core_person');
784 $person->id = $q['id'];
786 if(!$person->find(true)) {
787 $roo->jerr('_invalid_person');
790 $hash = $this->generateOathKey();
792 $_SESSION[__CLASS__] =
793 isset($_SESSION[__CLASS__]) ?
794 $_SESSION[__CLASS__] : array();
795 $_SESSION[__CLASS__]['oath'] =
796 isset($_SESSION[__CLASS__]['oath']) ?
797 $_SESSION[__CLASS__]['oath'] : array();
799 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
801 $qrcode = $person->generateQRCode($hash);
804 $roo->jerr('Fail to generate QR Code');
810 if(!empty($q['two_factor_auth_code'])) {
811 $person = DB_DataObject::factory('core_person');
812 $person->get($q['id']);
814 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
816 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
818 unset($_SESSION[__CLASS__]['oath'][$person->id]);
822 $roo->jerr('_invalid_auth_code');
825 if(!empty($q['oath_key_disable'])) {
826 $person = DB_DataObject::factory('core_person');
827 $person->get($q['id']);
831 $person->oath_key = '';
837 if (!empty($q['query']['is_owner'])) {
838 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
841 if (!empty($q['query']['person_not_internal'])) {
842 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
845 if (!empty($q['query']['person_internal_only_all'])) {
848 // must be internal and not current user (need for distribution list)
849 // user has a projectdirectory entry and role is not blank.
850 //DB_DataObject::DebugLevel(1);
851 $pd = DB_DataObject::factory('ProjectDirectory');
852 $pd->whereAdd("role != ''");
854 $pd->selectAdd('distinct(person_id) as person_id');
855 $roled = $pd->fetchAll('person_id');
857 {$this->tableName()}.id IN (".implode(',', $roled) . ")
859 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
862 // -- for distribution
863 if (!empty($q['query']['person_internal_only'])) {
864 // must be internal and not current user (need for distribution list)
865 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
867 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
868 // ".id != ".$au->id);
869 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
872 if (!empty($q['query']['comptype_or_company_id'])) {
873 // DB_DataObject::debugLevel(1);
874 $bits = explode(',', $q['query']['comptype_or_company_id']);
875 $id = (int) array_pop($bits);
876 $ct = $this->escape($bits[0]);
878 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
884 if (!empty($q['query']['person_inactive'])) {
885 // DB_Dataobject::debugLevel(1);
888 $tn_p = $this->tableName();
889 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
890 $tn_g = DB_DataObject::Factory('core_group')->tableName();
892 ///---------------- Group views --------
893 if (!empty($q['query']['in_group'])) {
894 // DB_DataObject::debugLevel(1);
895 $ing = (int) $q['query']['in_group'];
896 if ($q['query']['in_group'] == -1) {
898 // list all staff who are not in a group.
899 $this->whereAdd("{$this->tableName()}.id NOT IN (
900 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
901 $tn_g ON $tn_g.id = $tn_gm.group_id)");
905 $this->whereAdd("$tn_p.id IN (
906 SELECT distinct(user_id) FROM $tn_gm
907 WHERE group_id = $ing
913 if(!empty($q['in_group_name'])){
915 $v = $this->escape($q['in_group_name']);
920 DISTINCT(user_id) FROM $tn_gm
924 $tn_g.id = $tn_gm.group_id
931 // #2307 Search Country!!
932 if (!empty($q['query']['in_country'])) {
933 // DB_DataObject::debugLevel(1);
934 $inc = $q['query']['in_country'];
935 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
938 if (!empty($q['query']['not_in_directory'])) {
939 // it's a Person list..
940 // DB_DATaobjecT::debugLevel(1);
942 // specific to project directory which is single comp. login
944 $owncomp = DB_DataObject::Factory('core_company');
945 $owncomp->get('comptype', 'OWNER');
946 if ($q['company_id'] == $owncomp->id) {
952 if ( $q['query']['not_in_directory'] > -1) {
953 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
954 // can list current - so that it does not break!!!
955 $this->whereAdd("$tn_p.id NOT IN
956 ( SELECT distinct person_id FROM $tn_pd WHERE
957 project_id = " . $q['query']['not_in_directory'] . " AND
958 company_id = " . $this->company_id . ')');
962 if (!empty($q['query']['role'])) {
963 // it's a Person list..
964 // DB_DATaobjecT::debugLevel(1);
966 // specific to project directory which is single comp. login
968 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
969 // can list current - so that it does not break!!!
970 $this->whereAdd("$tn_p.id IN
971 ( SELECT distinct person_id FROM $tn_pd WHERE
972 role = '". $this->escape($q['query']['role']) ."'
978 if (!empty($q['query']['project_member_of'])) {
979 // this is also a flag to return if they are a member..
980 //DB_DataObject::debugLevel(1);
981 $do = DB_DataObject::factory('ProjectDirectory');
982 $do->project_id = $q['query']['project_member_of'];
983 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
984 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
985 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
988 if (!empty($q['query']['project_member_filter'])) {
989 $this->having('is_member !=0');
995 if(!empty($q['query']['name'])){
997 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1000 if(!empty($q['query']['name_starts'])){
1002 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1006 if (!empty($q['query']['search'])) {
1008 // use our magic search builder...
1010 require_once 'Text/SearchParser.php';
1011 $x = new Text_SearchParser($q['query']['search']);
1019 "join_company_id_id.name"
1021 $tbcols = $this->table();
1022 foreach(array('firstname','lastname') as $k) {
1023 if (isset($tbcols[$k])) {
1024 $props[] = "{$tn_p}.{$k}";
1031 $str = $x->toSQL(array(
1032 'default' => $props,
1034 'company' => 'join_company_id_id.name',
1035 //'country' => 'Clipping.country',
1036 // 'media' => 'Clipping.media_name',
1038 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1043 $this->whereAdd($str); /*
1044 $tn_p.name LIKE '%$s%' OR
1045 $tn_p.email LIKE '%$s%' OR
1046 $tn_p.role LIKE '%$s%' OR
1047 $tn_p.phone LIKE '%$s%' OR
1048 $tn_p.remarks LIKE '%$s%'
1053 // project directory rules -- this may distrupt things.
1054 $p = DB_DataObject::factory('ProjectDirectory');
1055 // if project directories are set up, then we can apply project query rules..
1058 $pids = $p->projects($au);
1059 if (isset($q['query']['project_id'])) {
1060 $pid = (int)$q['query']['project_id'];
1061 if (!in_array($pid, $pids)) {
1062 $roo->jerr("Project not in users valid projects");
1064 $pids = array($pid);
1067 //if (empty($q['_anyrole'])) { // should be project_directry_role
1068 // $p->whereAdd("{$p->tableName()}.role != ''");
1070 if (!empty($q['query']['role'])) { // should be project_directry_role
1071 $role = $this->escape($q['query']['role']);
1073 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1077 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1078 $peps = $p->people($pids);
1079 $this->whereAddIn("{$tn}.id", $peps, 'int');
1083 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1084 if (isset($q['query']['ticket_id'])) {
1085 // find out what state the ticket is in.
1086 $t = DB_DataObject::Factory('mtrack_ticket');
1088 $t->get($q['query']['ticket_id']);
1090 if (!$this->checkPerm('S', $au)) {
1091 $roo->jerr("permssion denied to query state of ticket");
1094 $p = DB_DataObject::factory('ProjectDirectory');
1095 $pids = array($t->project_id);
1097 $peps = $p->people($pids);
1099 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1101 //$this->whereAdd('join_prole != ''");
1106 * Seems we never expose oath_key / passwd, so...
1109 if($this->tableName() == 'core_person'){
1110 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1113 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1114 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1121 function setFromRoo($ar, $roo)
1123 $this->setFrom($ar);
1125 if(!empty($ar['_enable_oath_key'])){
1126 $oath_key = $this->generateOathKey();
1129 if (!empty($ar['passwd1'])) {
1130 $this->setPassword($ar['passwd1']);
1134 ($this->email == $roo->old->email)&&
1135 ($this->company_id == $roo->old->company_id)
1139 if (empty($this->email)) {
1142 // this only applies to our owner company..
1143 $c = $this->company();
1144 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1149 $xx = DB_Dataobject::factory($this->tableName());
1151 'email' => $this->email,
1152 // 'company_id' => $x->company_id
1156 return "Duplicate Email found";
1163 * before Delete - delete significant dependancies..
1164 * this is called after checkPerm..
1167 function beforeDelete($dependants_array, $roo)
1169 //delete group membership except for admin group..
1170 // if they are a member of admin group do not delete anything.
1171 $default_admin = false;
1173 $e = DB_DataObject::Factory('Events');
1174 $e->whereAdd('person_id = ' . $this->id);
1176 $g = DB_DataObject::Factory('core_group');
1177 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1179 $p = DB_DataObject::Factory('core_group_member');
1181 'user_id' => $this->id,
1182 'group_id' => $g->id
1186 $roo->jerr("Please remove this user from the Administrator group before deleting");
1190 $p = DB_DataObject::Factory('core_group_member');
1191 $p->user_id = $this->id;
1192 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1193 $e->logDeletedRecord($mem);
1195 foreach($mem as $p) {
1199 $e = DB_DataObject::Factory('Events');
1200 $e->person_id = $this->id;
1201 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1203 $e->logDeletedRecord($eve);
1204 foreach($eve as $e) {
1215 * Check if the a user has access to modify this item.
1216 * @param String $lvl Level (eg. Core.Projects)
1217 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1218 * @param boolean $changes alllow changes???
1220 * @return false if no access..
1222 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1225 // do we have an empty system..
1226 if ($au && $au->id == -1) {
1229 // if not authenticated... do not allow in???
1234 // determine if it's staff!!!
1235 $owncomp = DB_DataObject::Factory('core_company');
1236 $owncomp->get('comptype', 'OWNER');
1237 $isStaff = ($au->company_id == $owncomp->id);
1242 // - can not change company!!!
1244 isset($changes['company_id']) &&
1245 $changes['company_id'] != $au->company_id) {
1248 // can only set new emails..
1250 !empty($this->email) &&
1251 isset($changes['email']) &&
1252 $changes['email'] != $this->email) {
1257 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1258 // ???? do we want this?
1260 // edit self... - what about other staff members...
1262 //return $this->company_id == $au->company_id;
1266 // yes, only owner company can mess with this...
1272 // extra case change passwod?
1273 case 'P': //??? password
1274 // standard perms -- for editing + if the user is dowing them selves..
1275 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1276 return $ret || $au->id == $this->id;
1279 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1285 function beforeInsert($req, $roo)
1287 $p = DB_DataObject::factory('core_person');
1288 if ($roo->authUser->id > -1 || $p->count() > 1) {
1291 $c = DB_DataObject::Factory('core_company');
1294 if (!$tc || $tc> 1) {
1295 $roo->jerr("can not create initial user as multiple companies already exist");
1298 $this->company_id = $c->id;
1299 $this->email = trim($this->email);
1303 function onInsert($req, $roo)
1306 $p = DB_DataObject::factory('core_person');
1307 if ($roo->authUser->id < 0 && $p->count() == 1) {
1308 // this seems a bit risky...
1310 $g = DB_DataObject::factory('core_group');
1314 $g->get('name', 'Administrators');
1316 $p = DB_DataObject::factory('core_group_member');
1317 $p->group_id = $g->id;
1318 $p->user_id = $this->id;
1321 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1325 if (!empty($req['project_id_addto'])) {
1326 $pd = DB_DataObject::factory('ProjectDirectory');
1327 $pd->project_id = $req['project_id_addto'];
1328 $pd->person_id = $this->id;
1330 $pd->office_id = $this->office_id;
1331 $pd->company_id = $this->company_id;
1337 function importFromArray($roo, $persons, $opts)
1339 if (empty($opts['prefix'])) {
1340 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1343 if (!is_array($persons) || empty($persons)) {
1344 $roo->jerr("error in the person data. - empty on not valid");
1346 DB_DataObject::factory('core_group')->initGroups();
1348 foreach($persons as $person){
1349 $p = DB_DataObject::factory('core_person');
1350 if($p->get('name', $person['name'])){
1353 $p->setFrom($person);
1355 $companies = DB_DataObject::factory('core_company');
1356 if(!$companies->get('comptype', 'OWNER')){
1357 $roo->jerr("Missing OWNER companies!");
1359 $p->company_id = $companies->pid();
1360 // strip the 'spaces etc.. make lowercase..
1361 $name = strtolower(str_replace(' ', '', $person['name']));
1362 $p->setPassword("{$opts['prefix']}{$name}");
1365 // if $person->groups is set.. then
1366 // add this person to that group eg. groups : [ 'Administrator' ]
1367 if(!empty($person['groups'])){
1368 $groups = DB_DataObject::factory('core_group');
1369 if(!$groups->get('name', $person['groups'])){
1370 $roo->jerr("Missing groups : {$person['groups']}");
1372 $gm = DB_DataObject::factory('core_group_member');
1373 $gm->change($p, $groups, true);
1376 $p->onInsert(array(), $roo);
1380 // this is for the To: "{getEmailName()}" <email@address>
1381 // not good for Dear XXXX, - use {person.firstname} for that.
1382 function getEmailName()
1386 if(!empty($this->honor)){
1387 array_push($name, $this->honor);
1390 if(!empty($this->name)){
1391 array_push($name, $this->name);
1393 return implode(' ', $name);
1396 if(!empty($this->firstname) || !empty($this->lastname)){
1397 array_push($name, $this->firstname);
1398 array_push($name, $this->lastname);
1400 $name = array_filter($name);
1402 return implode(' ', $name);
1405 return $this->email;
1408 function sesPrefix()
1410 $ff= HTML_FlexyFramework::get();
1412 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1414 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1416 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1421 function loginPublic()
1423 $this->isAuth(); // force session start..
1425 $db = $this->getDatabaseConnection();
1427 $ff = HTML_FlexyFramework::get();
1429 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1433 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1435 $p = DB_DAtaObject::Factory($this->tableName());
1436 $p->get($this->pid());
1438 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1443 function beforeUpdate($old, $q, $roo)
1445 $this->email = trim($this->email);
1448 function generateOathKey()
1450 require 'Base32.php';
1452 $base32 = new Base32();
1454 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1457 function generateQRCode($hash)
1460 empty($this->email) &&
1466 $issuer = (empty($this->name)) ?
1467 rawurlencode('ROOJS') : rawurlencode($this->name);
1469 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1471 require_once 'Image/QRCode.php';
1473 $qrcode = new Image_QRCode();
1475 $image = $qrcode->makeCode($uri, array(
1476 'output_type' => 'return'
1481 $base64 = base64_encode(ob_get_contents());
1484 return "data:image/png;base64,{$base64}";