6 * - base application setup (variables etc to javascript)
8 * - authentication and permission info about user / application
9 * - json output methods.
10 * - file upload error checking - checkFileUploadError
11 * - logging to event table
12 * - sendTemplate code (normally use the Person version for sending to specific people..)
14 * - doc managment code?? - remarks and tracking??? - MOVEME
15 * - authentication link checking?? MOVEME?
16 * - authentication reset password ?? MOVEME?
17 * ?? arrayClean.. what's it doing here?!? ;)
22 class Pman extends HTML_FlexyFramework_Page
25 var $appShortName= "";
26 var $appVersion = "1.8";
38 * ------------- Standard getAuth/get/post methods of framework.
43 function getAuth() // everyone allowed in!!!!!
45 $this->loadOwnerCompany();
53 if (isset($this->_hasInit)) {
57 $this->_hasInit = true;
59 if (method_exists('HTML_FlexyFramework', 'get')) {
61 $boot = HTML_FlexyFramework::get();
62 // echo'<PRE>';print_R($boot);exit;
63 $this->appName= $boot->appName;
64 $this->appNameShort= $boot->appNameShort;
65 $this->appModules= $boot->enable;
66 $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
67 $this->appDisable = $boot->disable;
68 $this->version = $boot->version;
73 $opts = PEAR::getStaticProperty('Pman', 'options');
75 $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
77 $this->appName= empty($opts['appName']) ? '' : $opts['appName'];
78 $this->appNameShort= empty($opts['appNameShort']) ? '' : $opts['appNameShort'];
79 $this->appModules= $opts['enable'];
80 $this->appDisable = $opts['disable'];
81 $this->version = isset($opts['version']) ? $this->version : $opts['version'];
89 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
90 $bits = explode('/', $base);
92 if ($bits[0] == 'Link') {
93 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
94 header('Content-type: text/html; charset=utf-8');
97 if ($bits[0] == 'PasswordReset') {
98 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
99 header('Content-type: text/html; charset=utf-8');
104 if ($this->getAuthUser()) {
105 $this->addEvent("RELOAD");
110 $this->addEvent("BADURL", false, $base);
111 $this->jerr("invalid url");
114 if (isset($_GET['onloadTrack'])) {
115 $this->onloadTrack = (int)$_GET['onloadTrack'];
117 // getting this to work with xhtml is a nightmare
118 // = nbsp / <img> issues screw everyting up.
120 //header('Content-type: application/xhtml+xml; charset=utf-8');
121 header('Content-type: text/html; charset=utf-8');
124 function post($base) {
125 return $this->get($base);
129 * ------------- Authentication and permission info about logged in user!!!
134 function loadOwnerCompany()
136 $this->company = DB_DataObject::Factory('Companies');
137 if ($this->company) { // non-core pman projects
140 $this->company->get('comptype', 'OWNER');
143 function staticGetAuthUser()
145 $ff = HTML_FlexyFramework::get();
146 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
148 $u = DB_DataObject::factory($tbl);
152 return $u->getAuthUser();
154 function getAuthUser()
156 if (!empty($this->authUser)) {
157 return $this->authUser;
159 $ff = HTML_FlexyFramework::get();
160 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
162 $u = DB_DataObject::factory( $tbl );
166 $this->authUser =$u->getAuthUser();
167 return $this->authUser ;
169 function hasPerm($name, $lvl) // do we have a permission
171 static $pcache = array();
172 $au = $this->getAuthUser();
173 return $au->hasPerm($name,$lvl);
176 function hasModule($name)
179 if (!strpos( $name,'.') ) {
180 // use enable / disable..
183 $enabled = array('Core') ;
184 $enabled = !empty($this->appModules) ?
185 array_merge($enabled, explode(',', $this->appModules)) :
187 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
191 return in_array($name, $enabled) && !in_array($name, $disabled);
194 $x = DB_DataObject::factory('Group_Rights');
195 $ar = $x->defaultPermData();
196 if (empty($ar[$name]) || empty($ar[$name][0])) {
206 * ---------------- Global Tools ---------------
212 * send a template to the user
213 * rcpts are read from the resulting template.
215 * @arg $templateFile - the file in mail/XXXXXX.txt
216 * @arg $args - variables available to the form as {t.*} over and above 'this'
221 function sendTemplate($templateFile, $args)
226 $content = clone($this);
228 foreach((array)$args as $k=>$v) {
231 $content->msgid = md5(time() . rand());
233 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
234 /* use the regex compiler, as it doesnt parse <tags */
235 require_once 'HTML/Template/Flexy.php';
236 $template = new HTML_Template_Flexy( array(
237 'compiler' => 'Regex',
238 'filters' => array('SimpleTags','Mail'),
242 // this should be done by having multiple template sources...!!!
244 $template->compile('mail/'. $templateFile.'.txt');
246 /* use variables from this object to ouput data. */
247 $mailtext = $template->bufferedOutputObject($content);
248 //echo "<PRE>";print_R($mailtext);
250 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
251 require_once 'Mail/mimeDecode.php';
252 require_once 'Mail.php';
254 $decoder = new Mail_mimeDecode($mailtext);
255 $parts = $decoder->getSendArray();
256 if (PEAR::isError($parts)) {
258 //echo "PROBLEM: {$parts->message}";
261 list($recipents,$headers,$body) = $parts;
262 ///$recipents = array($this->email);
263 $mailOptions = PEAR::getStaticProperty('Mail','options');
264 $mail = Mail::factory("SMTP",$mailOptions);
265 $headers['Date'] = date('r');
266 if (PEAR::isError($mail)) {
269 $oe = error_reporting(E_ALL ^ E_NOTICE);
270 $ret = $mail->send($recipents,$headers,$body);
271 error_reporting($oe);
277 function checkFileUploadError() // check for file upload errors.
280 empty($_FILES['File'])
281 || empty($_FILES['File']['name'])
282 || empty($_FILES['File']['tmp_name'])
283 || empty($_FILES['File']['type'])
284 || !empty($_FILES['File']['error'])
285 || empty($_FILES['File']['size'])
287 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
293 * generate a tempory file with an extension (dont forget to delete it)
296 function tempName($ext)
298 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
300 return $x .'.'. $ext;
303 * ------------- Authentication testing ------ ??? MOVEME?
307 function linkAuth($trid, $trkey)
309 $tr = DB_DataObject::factory('Documents_Tracking');
310 if (!$tr->get($trid)) {
311 return "Invalid URL";
313 if (strtolower($tr->authkey) != strtolower($trkey)) {
314 $this->AddEvent("ERROR-L", false, "Invalid Key");
315 return "Invalid KEY";
318 $this->onloadTrack = (int) $tr->doc_id;
319 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
320 $this->AddEvent("ERROR-L", false, "Key Expired");
321 return "Key Expired";
323 // user logged in and not
324 $au = $this->getAuthUser();
325 if ($au && $au->id && $au->id != $tr->person_id) {
328 return "Logged Out existing Session\n - reload to log in with correct key";
330 if ($au) { // logged in anyway..
331 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
332 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
337 // authenticate the user...
339 $u = DB_DataObject::factory('Person');
341 $u->get($tr->person_id);
343 $this->AddEvent("LOGIN", false, "With Key");
345 // we need to redirect out - otherwise refererer url will include key!
346 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
358 * ------------- Authentication password reset ------ ??? MOVEME?
364 function resetPassword($id,$t, $key)
367 $au = $this->getAuthUser();
369 return "Already Logged in - no need to use Password Reset";
372 $u = DB_DataObject::factory('Person');
373 //$u->company_id = $this->company->id;
375 if (!$u->get($id) || !strlen($u->passwd)) {
380 if ($key != $u->genPassKey($t)) {
381 return "invalid key";
384 $u->no_reset_sent = 0;
387 if ($t < strtotime("NOW - 1 DAY")) {
390 $this->showNewPass = implode("/", array($id,$t,$key));
396 * ---------------- Standard JSON outputers. - used everywhere
399 function jerr($str, $errors=array()) // standard error reporting..
401 require_once 'Services/JSON.php';
402 $json = new Services_JSON();
404 if (!empty($_REQUEST['returnHTML']) ||
405 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
407 header('Content-type: text/html');
408 echo "<HTML><HEAD></HEAD><BODY>";
409 echo $json->encodeUnsafe(array(
412 'message' => $str, // compate with exeption / loadexception.
414 'errors' => $errors ? $errors : true, // used by forms to flag errors.
415 'authFailure' => !empty($errors['authFailure']),
417 echo "</BODY></HTML>";
421 echo $json->encode(array(
425 'message' => $str, // compate with exeption / loadexception.
426 'errors' => $errors ? $errors : true, // used by forms to flag errors.
427 'authFailure' => !empty($errors['authFailure']),
435 require_once 'Services/JSON.php';
436 $json = new Services_JSON();
438 if (!empty($_REQUEST['returnHTML']) ||
439 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
442 header('Content-type: text/html');
443 echo "<HTML><HEAD></HEAD><BODY>";
444 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
445 echo "</BODY></HTML>";
450 echo $json->encode(array('success'=> true, 'data' => $str));
454 function jdata($ar,$total=false, $extra=array())
456 // should do mobile checking???
457 if ($total == false) {
460 $extra= $extra ? $extra : array();
461 require_once 'Services/JSON.php';
462 $json = new Services_JSON();
463 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
473 * ---------------- Page output?!?!?
477 function hasBg($fn) // used on front page to check if logos exist..
479 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
482 function outputJavascriptIncludes() // includes on devel version..
485 $mods = explode(',', $this->appModules);
486 array_unshift($mods, 'Core');
487 $mods = array_unique($mods);
489 foreach($mods as $mod) {
490 // add the css file..
492 $files = $this->moduleJavascriptList($mod.'/widgets');
493 foreach($files as $f) {
494 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
497 $files = $this->moduleJavascriptList($mod);
498 foreach($files as $f) {
499 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
506 function outputCSSIncludes() // includes on CSS links.
509 $mods = explode(',', $this->appModules);
510 array_unshift($mods, 'Core');
511 $mods = array_unique($mods);
513 foreach($mods as $mod) {
514 // add the css file..
515 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
516 if (file_exists( $css)){
517 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
518 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
529 function moduleJavascriptList($mod)
531 $dir = $this->rootDir.'/Pman/'. $mod;
533 $path = $this->rootURL."/Pman/$mod/";
534 $base = dirname($_SERVER['SCRIPT_FILENAME']);
535 $cfile = realpath($base .'/_compiled_/' . $mod . '.js');
536 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
538 if (!file_exists($dir)) {
545 if (file_exists($cfile)) {
546 // $ctime = max(filemtime($cfile), filectime($cfile));
547 // otherwise use compile dfile..
548 $files = array( $this->rootURL."/_compiled_/". basename($cfile));
549 if (file_exists($lfile)) {
550 array_push($files, $this->rootURL."/_translations_/$mod.js");
554 // works out if stuff has been updated..
555 // technically the non-dev version should output compiled only?!!?
556 while (false !== ($f = readdir($dh))) {
557 if (!preg_match('/\.js$/', $f)) {
560 // got the 'module file..'
562 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
563 $files[] = $path . $f;
568 // var_dump(array($maxtime , $ctime));
569 //if ($maxtime > $ctime) {
570 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
571 usort($files, $lsort);
572 // if (file_exists($lfile)) {
573 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
583 * ---------------- Logging ---------------
590 function addEvent($act, $obj = false, $remarks = '') {
591 $au = $this->getAuthUser();
592 $e = DB_DataObject::factory('Events');
593 $e->person_name = $au ? $au->name : '';
594 $e->person_id = $au ? $au->id : '';
595 $e->event_when = date('Y-m-d H:i:s');
596 $e->ipaddr = $_SERVER["REMOTE_ADDR"];
598 $e->on_table = $obj ? $obj->tableName() : '';
599 $e->on_id = $obj ? $obj->id : 0;
600 $e->remarks = $remarks;