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;
53 /* the code above is auto generated do not remove the tag below */
56 static $authUser = false;
61 // this might be a Person in some old code?
62 $p = DB_DataObject::Factory('core_person');
63 $p->get($this->owner_id);
72 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
78 function buildMail($templateFile, $args)
81 $args = (array) $args;
82 $content = clone($this);
84 foreach((array)$args as $k=>$v) {
88 $ff = HTML_FlexyFramework::get();
91 //?? is this really the place for this???
94 empty($args['no_auth']) &&
95 !in_array($templateFile, array(
96 // templates that can be sent without authentication.
102 $content->authUser = $this->getAuthUser();
103 if (!$content->authUser) {
104 return PEAR::raiseError("Not authenticated");
108 // should handle x-forwarded...
110 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
111 $_SERVER["HTTP_HOST"] :
112 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
114 /* use the regex compiler, as it doesnt parse <tags */
117 'compiler' => 'Flexy',
119 'filters' => array('SimpleTags','Mail'),
125 if (!empty($args['templateDir'])) {
126 $tops['templateDir'] = $args['templateDir'];
131 require_once 'HTML/Template/Flexy.php';
132 $template = new HTML_Template_Flexy( $tops );
133 $template->compile("mail/$templateFile.txt");
135 /* use variables from this object to ouput data. */
136 $mailtext = $template->bufferedOutputObject($content);
139 // if a html file with the same name exists, use that as the body
140 // I've no idea where this code went, it was here before..
141 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
142 $tops['nonHTML'] = false;
143 $template = new HTML_Template_Flexy( $tops );
144 $template->compile("mail/$templateFile.html");
145 $htmlbody = $template->bufferedOutputObject($content);
151 //echo "<PRE>";print_R($mailtext);
152 //print_R($mailtext);exit;
153 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
154 require_once 'Mail/mimeDecode.php';
155 require_once 'Mail.php';
157 $decoder = new Mail_mimeDecode($mailtext);
158 $parts = $decoder->getSendArray();
160 if (is_a($parts,'PEAR_Error')) {
162 //echo "PROBLEM: {$parts->message}";
165 list($recipents,$headers,$body) = $parts;
166 $recipents = array($this->email);
167 if (!empty($content->bcc) && is_array($content->bcc)) {
168 $recipents =array_merge($recipents, $content->bcc);
170 $headers['Date'] = date('r');
172 if ($htmlbody !== false) {
173 require_once 'Mail/mime.php';
174 $mime = new Mail_mime(array('eol' => "\n"));
175 $mime->setTXTBody($body);
176 $mime->setHTMLBody($htmlbody);
177 // I think there might be code in mediaoutreach toEmail somewhere
178 // h embeds images here..
179 $body = $mime->get();
180 $headers = $mime->headers($headers);
184 'recipients' => $recipents,
185 'headers' => $headers,
193 * - user must be authenticate or args[no_auth] = true
194 * or template = password_[reset|welcome]
197 function sendTemplate($templateFile, $args)
199 $ar = $this->buildMail($templateFile, $args);
201 //print_r($recipents);exit;
202 $mailOptions = PEAR::getStaticProperty('Mail','options');
203 $mail = Mail::factory("SMTP",$mailOptions);
205 if (PEAR::isError($mail)) {
208 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
209 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
210 error_reporting($oe);
218 function getEmailFrom()
220 if (empty($this->name)) {
224 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
227 function toEventString()
229 return empty($this->name) ? $this->email : $this->name;
232 function verifyAuth()
234 $ff= HTML_FlexyFramework::get();
235 if (!empty($ff->Pman['auth_comptype']) &&
236 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
239 $sesPrefix = $this->sesPrefix();
241 self::$authUser = false;
242 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
246 //$ff->page->jerr("Login not permited to outside companies");
253 // ---------------- authentication / passwords and keys stuff ----------------
256 // do not start a session if we are using http auth...
257 if (empty($_SERVER['PHP_AUTH_USER']) && php_sapi_name() != "cli") {
261 $ff= HTML_FlexyFramework::get();
263 $sesPrefix = $this->sesPrefix();
265 if (self::$authUser) {
266 return self::$authUser;
270 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
272 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
273 $u = DB_DataObject::factory($this->tableName());
275 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
276 if ($u->verifyAuth()) {
277 self::$authUser = $u;
281 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
282 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
283 setcookie('Pman.timeout', -1, time() + (30*60), '/');
288 $u = DB_DataObject::factory($this->tableName());
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 // logged in via http auth
299 // http auth will not need session...
300 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
301 self::$authUser = $u;
305 if (!$this->canInitializeSystem()) {
306 // die("can not init");
311 $auto_auth_allow = false;
312 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
313 $auto_auth_allow = true;
315 if ( !empty($ff->Pman['local_autoauth'])
317 !empty($_SERVER['SERVER_ADDR']) &&
318 !empty($_SERVER['REMOTE_ADDR']) &&
321 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
322 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
326 $_SERVER['SERVER_ADDR'] == '::1' &&
327 $_SERVER['REMOTE_ADDR'] == '::1'
332 $auto_auth_allow = true;
336 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
337 $auto_auth_allow = false;
339 //var_dump($auto_auth_allow);
341 $default_admin = false;
342 if ($auto_auth_allow) {
343 $group = DB_DataObject::factory('core_group');
344 $group->get('name', 'Administrators');
346 $member = DB_DataObject::factory('core_group_member');
348 $member->group_id = $group->id;
350 join_user_id_id.id IS NOT NULL
352 if($member->find(true)){
353 $default_admin = DB_DataObject::factory($this->tableName());
354 $default_admin->autoJoin();
355 if(!$default_admin->get($member->user_id)){
356 $default_admin = false;
361 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
362 $u = DB_DataObject::factory($this->tableName());
364 $ff = HTML_FlexyFramework::get();
366 if ($auto_auth_allow &&
367 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
370 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
372 // if we request other URLS.. then we get auto logged in..
373 self::$authUser = $default_admin ? $default_admin : $u;;
374 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
378 //var_dump(session_id());
379 //var_dump($_SESSION[__CLASS__]);
381 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
384 //die("got this far?");
385 // not in session or not matched...
386 $u = DB_DataObject::factory($this->tableName());
387 $u->whereAdd(' LENGTH(passwd) > 0');
389 if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) {
390 $_SESSION[get_class($this)] = array();
392 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
393 if (class_exists('PEAR')) {
394 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
396 die($error->toString()); // not really a good thing to do...
399 if (!$n){ // authenticated as there are no users in the system...
406 function canInitializeSystem()
409 return !strcasecmp(get_class($this) , __CLASS__);
412 function getAuthUser()
414 if (!$this->isAuth()) {
418 $ff= HTML_FlexyFramework::get();
420 $sesPrefix = $this->sesPrefix();
422 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
424 if (self::$authUser) {
426 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
427 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
428 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
430 // not really sure why it's cloned..
431 return clone (self::$authUser);
438 if (!$this->canInitializeSystem()) {
444 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
445 $u = DB_DataObject::factory($this->tableName());
446 $u->whereAdd(' LENGTH(passwd) > 0');
447 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
452 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
453 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
456 // fake person - open system..
457 //$ce = DB_DataObject::factory('core_enum');
461 $u = DB_DataObject::factory($this->tableName());
464 // if a company has been created fill that in in company_id_id
465 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
467 $u->company_id_id = $c->pid();
468 $u->company_id = $c->pid();
478 $this->isAuth(); // force session start..
479 if (!$this->verifyAuth()) { // check for company valid..
483 // open up iptables at login..
484 $dbname = $this->databaseNickname();
485 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
487 // refresh admin group if we are logged in as one..
488 //DB_DataObject::debugLevel(1);
489 $g = DB_DataObject::factory('core_group');
491 $g->get('name', 'Administrators');
492 $gm = DB_DataObject::Factory('core_group_member');
493 if (in_array($g->id,$gm->listGroupMembership($this))) {
494 // refresh admin groups.
495 $gr = DB_DataObject::Factory('core_group_right');
496 $gr->applyDefs($g, 0);
499 $sesPrefix = $this->sesPrefix();
501 // we should not store the whole data in the session - otherwise it get's huge.
502 $p = DB_DAtaObject::Factory($this->tableName());
503 $p->get($this->pid());
507 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
508 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
510 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
511 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
513 $pp = DB_DAtaObject::Factory($this->tableName());
514 $pp->get($this->pid());
517 self::$authUser = $pp;
518 // ensure it's written so that ajax calls can fetch it..
525 $this->isAuth(); // force session start..
527 $sesPrefix = $this->sesPrefix();
528 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
529 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
530 self::$authUser = false;
533 function genPassKey ($t)
535 return md5($this->email . $t. $this->passwd);
537 function simpleAuthKey($m = 0)
539 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
541 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
544 * When we generate autologin urls:
545 * eg. /Somesite/Test/12
547 * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
549 * eg. genAutoLoginURL($sub, $expires)
551 function genAutoLoginURL($url, $expires = false)
553 $expires = $expires === false ? strtotime("NOW + 1 WEEK") : $expires;
554 //echo serialize(array($url, $expires, $this->email, $this->passwd));
555 //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
557 return $url.'/'.$this->id .'/'.$expires.'/'.
560 array($url, $expires, $this->email,$this->passwd)
566 function validateAutoLogin($called)
568 $bits = explode("/",$called);
569 if (count($bits) < 4) {
570 return false; // unrelated.
572 $hash = array_pop($bits);
573 $time = array_pop($bits);
575 $id = array_pop($bits);
576 if (!is_numeric($time) || !is_numeric($id)) {
577 return false; // wrong format.
579 $u = DB_DataObject::Factory($this->tableName());
581 $url = implode("/", $bits);
582 if ($time < time()) {
585 //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
586 //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
587 if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
595 function checkTwoFactorAuthentication($val)
599 // also used in login
600 require_once 'System.php';
604 empty($this->oath_key)
609 $oathtool = System::which('oathtool');
615 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
617 $password = exec($cmd);
619 return ($password == $val) ? true : false;
622 function checkPassword($val)
624 if (substr($this->passwd,0,1) == '$') {
625 if (function_exists('pasword_verify')) {
626 return password_verify($val, $this->passwd);
628 return crypt($val,$this->passwd) == $this->passwd ;
630 // old style md5 passwords...- cant be used with courier....
631 return md5($val) == $this->passwd;
634 function setPassword($value)
636 if (function_exists('pasword_hash')) {
637 return password_hash($value);
641 while(strlen($salt)<9) {
642 $salt.=chr(rand(64,126));
643 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
645 $this->passwd = crypt($value, '$1$'. $salt. '$');
650 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
652 require_once 'Text/Password.php';
653 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
654 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
655 $this->setPassword($this->rawPasswd);
656 return $this->rawPasswd;
661 if (empty($this->company_id)) {
664 $x = DB_DataObject::factory('core_company');
666 $x->get($this->company_id);
669 function loadCompany()
671 $this->company = $this->company();
676 return $this->active;
678 function authUserName($n) // set username prior to acheck user exists query.
681 $this->whereAdd('LENGTH(passwd) > 1');
686 if (!func_num_args()) {
689 $ar = func_get_args();
690 $val = array_shift($ar);
691 if ($val == $this->lang) {
701 function authUserArray()
703 $aur = $this->toArray();
709 //DB_DataObject::debugLevel(1);
710 $c = DB_Dataobject::factory('core_company');
711 $im = DB_Dataobject::factory('Images');
712 $c->joinAdd($im, 'LEFT');
714 $c->selectAs($c, 'company_id_%s');
715 $c->selectAs($im, 'company_id_logo_id_%s');
716 $c->id = $this->company_id;
720 $aur = array_merge( $c->toArray(),$aur);
722 if (empty($c->company_id_logo_id_id)) {
724 $im = DB_Dataobject::factory('Images');
725 $im->ontable = DB_DataObject::factory('core_company')->tableName();
727 $im->imgtype = 'LOGO';
730 $im->selectAs($im, 'company_id_logo_id_%s');
731 if ($im->find(true)) {
733 foreach($im->toArray() as $k=>$v) {
734 if (!preg_match('/^company_id_logo_id_/', $k)) {
743 $aur['perms'] = $this->getPerms();
744 $g = DB_DataObject::Factory('core_group_member');
745 $aur['groups'] = $g->listGroupMembership($this, 'name');
748 $aur['dailykey'] = '';
749 $aur['oath_key'] = '';
751 $aur['oath_key_enable'] = !empty($this->oath_key);
752 $aur['require_oath'] = 1;
754 $s = DB_DataObject::Factory('core_setting');
755 $oath_require = $s->lookup('core', 'two_factor_auth_required');
756 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
758 $aur['core_person_settings'] = array();
760 $core_person_settings = DB_DataObject::factory('core_person_settings');
761 $core_person_settings->setFrom(array(
762 'person_id' => $this->id
765 $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
770 // ----------PERMS------ ----------------
773 //DB_DataObject::debugLevel(1);
774 // find out all the groups they are a member of.. + Default..
776 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
778 $g = DB_DataObject::Factory('core_group_right');
784 return $g->adminRights(); // system is not set up - so they get full rights.
786 //DB_DataObject::debugLevel(1);
787 $g = DB_DataObject::Factory('core_group_member');
788 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
790 // add the current user to the admin group..
791 $g = DB_DataObject::Factory('core_group');
792 if ($g->get('name', 'Administrators')) {
793 $gm = DB_DataObject::Factory('core_group_member');
794 $gm->group_id = $g->id;
795 $gm->user_id = $this->id;
801 // ------ STANDARD PERMISSION HANDLING.
802 $isOwner = $this->company()->comptype == 'OWNER';
803 $g = DB_DataObject::Factory('core_group_member');
804 $grps = $g->listGroupMembership($this);
806 $isAdmin = $g->inAdmin; //??? what???
807 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
808 // the load all the perms for those groups, and add them all together..
809 // then load all those
810 $g = DB_DataObject::Factory('core_group_right');
811 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
812 //echo '<PRE>';print_r($ret);
818 *Basic group fetching - probably needs to filter by type eventually.
820 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
823 function groups($what=false)
825 $g = DB_DataObject::Factory('core_group_member');
826 $grps = $g->listGroupMembership($this);
827 $g = DB_DataObject::Factory('core_group');
828 $g->whereAddIn('id', $grps, 'int');
829 return $g->fetchAll($what);
835 function hasPerm($name, $lvl)
837 static $pcache = array();
839 if (!isset($pcache[$this->id])) {
840 $pcache[$this->id] = $this->getPerms();
843 // echo "<PRE>";print_r($pcache[$au->id]);
844 // var_dump($pcache[$au->id]);
845 if (empty($pcache[$this->id][$name])) {
849 return strpos($pcache[$this->id][$name], $lvl) > -1;
853 // ------------ROO HOOKS------------------------------------
854 function applyFilters($q, $au, $roo)
856 //DB_DataObject::DebugLevel(1);
857 if(!empty($q['_to_qr_code'])){
858 $person = DB_DataObject::factory('Core_person');
859 $person->id = $q['id'];
861 if(!$person->find(true)) {
862 $roo->jerr('_invalid_person');
865 $hash = $this->generateOathKey();
867 $_SESSION[__CLASS__] =
868 isset($_SESSION[__CLASS__]) ?
869 $_SESSION[__CLASS__] : array();
870 $_SESSION[__CLASS__]['oath'] =
871 isset($_SESSION[__CLASS__]['oath']) ?
872 $_SESSION[__CLASS__]['oath'] : array();
874 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
876 $qrcode = $person->generateQRCode($hash);
879 $roo->jerr('Fail to generate QR Code');
885 'issuer' => $person->qrCodeIssuer()
889 if(!empty($q['two_factor_auth_code'])) {
890 $person = DB_DataObject::factory('core_person');
891 $person->get($q['id']);
893 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
895 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
897 unset($_SESSION[__CLASS__]['oath'][$person->id]);
901 $roo->jerr('_invalid_auth_code');
904 if(!empty($q['oath_key_disable'])) {
905 $person = DB_DataObject::factory('core_person');
906 $person->get($q['id']);
910 $person->oath_key = '';
916 if (!empty($q['query']['is_owner'])) {
917 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
920 if (!empty($q['query']['person_not_internal'])) {
921 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
924 if (!empty($q['query']['person_internal_only_all'])) {
927 // must be internal and not current user (need for distribution list)
928 // user has a projectdirectory entry and role is not blank.
929 //DB_DataObject::DebugLevel(1);
930 $pd = DB_DataObject::factory('ProjectDirectory');
931 $pd->whereAdd("role != ''");
933 $pd->selectAdd('distinct(person_id) as person_id');
934 $roled = $pd->fetchAll('person_id');
936 {$this->tableName()}.id IN (".implode(',', $roled) . ")
938 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
941 // -- for distribution
942 if (!empty($q['query']['person_internal_only'])) {
943 // must be internal and not current user (need for distribution list)
944 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
946 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
947 // ".id != ".$au->id);
948 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
951 if (!empty($q['query']['comptype_or_company_id'])) {
952 // DB_DataObject::debugLevel(1);
953 $bits = explode(',', $q['query']['comptype_or_company_id']);
954 $id = (int) array_pop($bits);
955 $ct = $this->escape($bits[0]);
957 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
963 if (!empty($q['query']['person_inactive'])) {
964 // DB_Dataobject::debugLevel(1);
967 $tn_p = $this->tableName();
968 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
969 $tn_g = DB_DataObject::Factory('core_group')->tableName();
971 ///---------------- Group views --------
972 if (!empty($q['query']['in_group'])) {
973 // DB_DataObject::debugLevel(1);
974 $ing = (int) $q['query']['in_group'];
975 if ($q['query']['in_group'] == -1) {
977 // list all staff who are not in a group.
978 $this->whereAdd("{$this->tableName()}.id NOT IN (
979 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
980 $tn_g ON $tn_g.id = $tn_gm.group_id)");
984 $this->whereAdd("$tn_p.id IN (
985 SELECT distinct(user_id) FROM $tn_gm
986 WHERE group_id = $ing
992 if(!empty($q['in_group_name'])){
994 $v = $this->escape($q['in_group_name']);
999 DISTINCT(user_id) FROM $tn_gm
1003 $tn_g.id = $tn_gm.group_id
1009 if(!empty($q['in_group_starts'])){
1011 $v = $this->escape($q['in_group_starts']);
1016 DISTINCT(user_id) FROM $tn_gm
1020 $tn_g.id = $tn_gm.group_id
1022 $tn_g.name LIKE '{$v}%'
1029 // #2307 Search Country!!
1030 if (!empty($q['query']['in_country'])) {
1031 // DB_DataObject::debugLevel(1);
1032 $inc = $q['query']['in_country'];
1033 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1036 if (!empty($q['query']['not_in_directory'])) {
1037 // it's a Person list..
1038 // DB_DATaobjecT::debugLevel(1);
1040 // specific to project directory which is single comp. login
1042 $owncomp = DB_DataObject::Factory('core_company');
1043 $owncomp->get('comptype', 'OWNER');
1044 if ($q['company_id'] == $owncomp->id) {
1050 if ( $q['query']['not_in_directory'] > -1) {
1051 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1052 // can list current - so that it does not break!!!
1053 $this->whereAdd("$tn_p.id NOT IN
1054 ( SELECT distinct person_id FROM $tn_pd WHERE
1055 project_id = " . $q['query']['not_in_directory'] . " AND
1056 company_id = " . $this->company_id . ')');
1060 if (!empty($q['query']['role'])) {
1061 // it's a Person list..
1062 // DB_DATaobjecT::debugLevel(1);
1064 // specific to project directory which is single comp. login
1066 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1067 // can list current - so that it does not break!!!
1068 $this->whereAdd("$tn_p.id IN
1069 ( SELECT distinct person_id FROM $tn_pd WHERE
1070 role = '". $this->escape($q['query']['role']) ."'
1076 if (!empty($q['query']['project_member_of'])) {
1077 // this is also a flag to return if they are a member..
1078 //DB_DataObject::debugLevel(1);
1079 $do = DB_DataObject::factory('ProjectDirectory');
1080 $do->project_id = $q['query']['project_member_of'];
1081 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1082 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1083 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1086 if (!empty($q['query']['project_member_filter'])) {
1087 $this->having('is_member !=0');
1093 if(!empty($q['query']['name'])){
1095 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1099 if(!empty($q['query']['name_or_email'])){
1100 $v = $this->escape($q['query']['name_or_email']);
1102 {$this->tableName()}.name LIKE '%{$v}%'
1104 {$this->tableName()}.email LIKE '%{$v}%'
1107 if(!empty($q['query']['name_starts'])){
1109 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1113 if (!empty($q['query']['search'])) {
1115 // use our magic search builder...
1117 require_once 'Text/SearchParser.php';
1118 $x = new Text_SearchParser($q['query']['search']);
1126 "join_company_id_id.name"
1128 $tbcols = $this->table();
1129 foreach(array('firstname','lastname') as $k) {
1130 if (isset($tbcols[$k])) {
1131 $props[] = "{$tn_p}.{$k}";
1138 $str = $x->toSQL(array(
1139 'default' => $props,
1141 'company' => 'join_company_id_id.name',
1142 //'country' => 'Clipping.country',
1143 // 'media' => 'Clipping.media_name',
1145 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1150 $this->whereAdd($str); /*
1151 $tn_p.name LIKE '%$s%' OR
1152 $tn_p.email LIKE '%$s%' OR
1153 $tn_p.role LIKE '%$s%' OR
1154 $tn_p.phone LIKE '%$s%' OR
1155 $tn_p.remarks LIKE '%$s%'
1160 // project directory rules -- this may distrupt things.
1161 $p = DB_DataObject::factory('ProjectDirectory');
1162 // if project directories are set up, then we can apply project query rules..
1165 $pids = $p->projects($au);
1166 if (isset($q['query']['project_id'])) {
1167 $pid = (int)$q['query']['project_id'];
1168 if (!in_array($pid, $pids)) {
1169 $roo->jerr("Project not in users valid projects");
1171 $pids = array($pid);
1174 //if (empty($q['_anyrole'])) { // should be project_directry_role
1175 // $p->whereAdd("{$p->tableName()}.role != ''");
1177 if (!empty($q['query']['role'])) { // should be project_directry_role
1178 $role = $this->escape($q['query']['role']);
1180 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1184 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1185 $peps = $p->people($pids);
1186 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1190 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1191 if (isset($q['query']['ticket_id'])) {
1192 // find out what state the ticket is in.
1193 $t = DB_DataObject::Factory('mtrack_ticket');
1195 $t->get($q['query']['ticket_id']);
1197 if (!$this->checkPerm('S', $au)) {
1198 $roo->jerr("permssion denied to query state of ticket");
1201 $p = DB_DataObject::factory('ProjectDirectory');
1202 $pids = array($t->project_id);
1204 $peps = $p->people($pids);
1206 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1208 //$this->whereAdd('join_prole != ''");
1213 * Seems we never expose oath_key / passwd, so...
1216 if($this->tableName() == 'core_person'){
1217 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1220 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1221 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1224 if (isset($q['_with_group_membership'])) {
1225 $this->selectAddGroupMemberships();
1230 function selectAddGroupMemberships()
1236 GROUP_CONCAT( CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name END separator '\n')
1242 core_group.id = core_group_member.group_id
1244 core_group_member.user_id = core_person.id
1246 core_group.display_name ASC
1247 ), '') as member_of");
1250 function setFromRoo($ar, $roo)
1252 $this->setFrom($ar);
1254 if(!empty($ar['_enable_oath_key'])){
1255 $oath_key = $this->generateOathKey();
1258 if (!empty($ar['passwd1'])) {
1259 $this->setPassword($ar['passwd1']);
1263 ($this->email == $roo->old->email)&&
1264 ($this->company_id == $roo->old->company_id)
1268 if (empty($this->email)) {
1271 // this only applies to our owner company..
1272 $c = $this->company();
1273 if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1278 $xx = DB_Dataobject::factory($this->tableName());
1280 'email' => $this->email,
1281 // 'company_id' => $x->company_id
1285 return "Duplicate Email found";
1292 * before Delete - delete significant dependancies..
1293 * this is called after checkPerm..
1296 function beforeDelete($dependants_array, $roo)
1298 //delete group membership except for admin group..
1299 // if they are a member of admin group do not delete anything.
1300 $default_admin = false;
1302 $e = DB_DataObject::Factory('Events');
1303 $e->whereAdd('person_id = ' . $this->id);
1305 $g = DB_DataObject::Factory('core_group');
1306 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1308 $p = DB_DataObject::Factory('core_group_member');
1310 'user_id' => $this->id,
1311 'group_id' => $g->id
1315 $roo->jerr("Please remove this user from the Administrator group before deleting");
1319 $p = DB_DataObject::Factory('core_group_member');
1320 $p->user_id = $this->id;
1321 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1322 $e->logDeletedRecord($mem);
1324 foreach($mem as $p) {
1328 $e = DB_DataObject::Factory('Events');
1329 $e->person_id = $this->id;
1330 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1332 $e->logDeletedRecord($eve);
1333 foreach($eve as $e) {
1344 * Check if the a user has access to modify this item.
1345 * @param String $lvl Level (eg. Core.Projects)
1346 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1347 * @param boolean $changes alllow changes???
1349 * @return false if no access..
1351 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1354 // do we have an empty system..
1355 if ($au && $au->id == -1) {
1358 // if not authenticated... do not allow in???
1363 // determine if it's staff!!!
1364 $owncomp = DB_DataObject::Factory('core_company');
1365 $owncomp->get('comptype', 'OWNER');
1366 $isStaff = ($au->company_id == $owncomp->id);
1371 // - can not change company!!!
1373 isset($changes['company_id']) &&
1374 $changes['company_id'] != $au->company_id) {
1377 // can only set new emails..
1379 !empty($this->email) &&
1380 isset($changes['email']) &&
1381 $changes['email'] != $this->email) {
1386 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1387 // ???? do we want this?
1389 // edit self... - what about other staff members...
1391 //return $this->company_id == $au->company_id;
1395 // yes, only owner company can mess with this...
1401 // extra case change passwod?
1402 case 'P': //??? password
1403 // standard perms -- for editing + if the user is dowing them selves..
1404 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1405 return $ret || $au->id == $this->id;
1408 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1414 function beforeInsert($req, $roo)
1416 $p = DB_DataObject::factory('core_person');
1417 if ($roo->authUser->id > -1 || $p->count() > 1) {
1420 $c = DB_DataObject::Factory('core_company');
1423 if (!$tc || $tc> 1) {
1424 $roo->jerr("can not create initial user as multiple companies already exist");
1427 $this->company_id = $c->id;
1428 $this->email = trim($this->email);
1432 function onInsert($req, $roo)
1435 $p = DB_DataObject::factory('core_person');
1436 if ($roo->authUser->id < 0 && $p->count() == 1) {
1437 // this seems a bit risky...
1439 $g = DB_DataObject::factory('core_group');
1443 $g->get('name', 'Administrators');
1445 $p = DB_DataObject::factory('core_group_member');
1446 $p->group_id = $g->id;
1447 $p->user_id = $this->id;
1450 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1454 if (!empty($req['project_id_addto'])) {
1455 $pd = DB_DataObject::factory('ProjectDirectory');
1456 $pd->project_id = $req['project_id_addto'];
1457 $pd->person_id = $this->id;
1459 $pd->office_id = $this->office_id;
1460 $pd->company_id = $this->company_id;
1466 function importFromArray($roo, $persons, $opts)
1468 if (empty($opts['prefix'])) {
1469 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1472 if (!is_array($persons) || empty($persons)) {
1473 $roo->jerr("error in the person data. - empty on not valid");
1475 DB_DataObject::factory('core_group')->initGroups();
1477 foreach($persons as $person){
1478 $p = DB_DataObject::factory('core_person');
1479 if($p->get('name', $person['name'])){
1482 $p->setFrom($person);
1484 $companies = DB_DataObject::factory('core_company');
1485 if(!$companies->get('comptype', 'OWNER')){
1486 $roo->jerr("Missing OWNER companies!");
1488 $p->company_id = $companies->pid();
1489 // strip the 'spaces etc.. make lowercase..
1490 $name = strtolower(str_replace(' ', '', $person['name']));
1491 $p->setPassword("{$opts['prefix']}{$name}");
1494 // if $person->groups is set.. then
1495 // add this person to that group eg. groups : [ 'Administrator' ]
1496 if(!empty($person['groups'])){
1497 $groups = DB_DataObject::factory('core_group');
1498 if(!$groups->get('name', $person['groups'])){
1499 $roo->jerr("Missing groups : {$person['groups']}");
1501 $gm = DB_DataObject::factory('core_group_member');
1502 $gm->change($p, $groups, true);
1505 $p->onInsert(array(), $roo);
1509 // this is for the To: "{getEmailName()}" <email@address>
1510 // not good for Dear XXXX, - use {person.firstname} for that.
1511 function getEmailName()
1515 if(!empty($this->honor)){
1516 array_push($name, $this->honor);
1519 if(!empty($this->name)){
1520 array_push($name, $this->name);
1522 return implode(' ', $name);
1525 if(!empty($this->firstname) || !empty($this->lastname)){
1526 array_push($name, $this->firstname);
1527 array_push($name, $this->lastname);
1529 $name = array_filter($name);
1531 return implode(' ', $name);
1534 return $this->email;
1537 function sesPrefix()
1539 $ff= HTML_FlexyFramework::get();
1541 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1543 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1545 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1550 function loginPublic() // used where???
1552 $this->isAuth(); // force session start..
1554 $db = $this->getDatabaseConnection();
1556 $ff = HTML_FlexyFramework::get();
1558 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1562 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1564 $p = DB_DAtaObject::Factory($this->tableName());
1565 $p->get($this->pid());
1567 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1572 function beforeUpdate($old, $q, $roo)
1574 $this->email = trim($this->email);
1577 function generateOathKey()
1579 require 'Base32.php';
1581 $base32 = new Base32();
1583 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1586 function generateQRCode($hash)
1589 empty($this->email) &&
1595 $issuer = rawurlencode($this->qrCodeIssuer());
1597 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1599 require_once 'Image/QRCode.php';
1601 $qrcode = new Image_QRCode();
1603 $image = $qrcode->makeCode($uri, array(
1604 'output_type' => 'return'
1609 $base64 = base64_encode(ob_get_contents());
1612 return "data:image/png;base64,{$base64}";
1615 function qrCodeIssuer()
1617 $pg= HTML_FlexyFramework::get()->page;
1619 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1624 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1626 $ff = HTML_FlexyFramework::get();
1627 $person = DB_DataObject::Factory('core_person');
1631 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1632 'person' => $person,
1633 'authFrom' => 'FAKE_LINK',
1634 'authKey' => 'FAKE_KEY',
1636 'rcpts' => $to->email,