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?!? ;)
20 * DB_DataObject*:*toEventString (for logging - this is generically prefixed to all database operations.)
21 * - any data object where this method exists, the result will get prefixed to the log remarks
24 class Pman extends HTML_FlexyFramework_Page
28 var $appShortName= "";
29 var $appVersion = "1.8";
36 var $appDisabled = array(); // array of disabled modules..
37 // (based on config option disable)
39 var $authUser; // always contains the authenticated user..
41 var $disable_jstemplate = false; /// disable inclusion of jstemplate code..
45 * ------------- Standard getAuth/get/post methods of framework.
50 function getAuth() // everyone allowed in!!!!!
52 $this->loadOwnerCompany();
60 if (isset($this->_hasInit)) {
63 $this->_hasInit = true;
64 // move away from doing this ... you can access bootLoader.XXXXXX in the master template..
65 $boot = HTML_FlexyFramework::get();
66 // echo'<PRE>';print_R($boot);exit;
67 $this->appName= $boot->appName;
68 $this->appNameShort= $boot->appNameShort;
71 $this->appModules= $boot->enable;
73 // echo $this->arrayToJsInclude($files);
74 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
76 $this->appDisable = $boot->disable;
77 $this->appDisabled = explode(',', $boot->disable);
78 $this->version = $boot->version;
79 $this->uiConfig = empty($boot->Pman['uiConfig']) ? false : $boot->Pman['uiConfig'];
81 if (!empty($ff->Pman['local_autoauth']) &&
82 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
83 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
88 // if a file Pman_{module}_Pman exists.. and it has an init function... - call that..
90 //var_dump($this->appModules);
96 * module init is only loaded on main page call, and includes checks for configuration settings.
98 function initModules()
100 foreach(explode(',',$this->appModules) as $m) {
101 $cls = 'Pman_'. $m . '_Pman';
103 //echo $this->rootDir . '/'.str_replace('_','/', $cls). '.php';
105 if (!file_exists($this->rootDir . '/'.str_replace('_','/', $cls). '.php')) {
108 require_once str_replace('_','/', $cls). '.php';
110 if (method_exists($c,'init')) {
122 $this->initModules();
125 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
126 $bits = explode('/', $base);
128 if ($bits[0] == 'Link') {
129 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
130 header('Content-type: text/html; charset=utf-8');
134 // should really be moved to Login...
136 if ($bits[0] == 'PasswordReset') {
137 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
138 header('Content-type: text/html; charset=utf-8');
142 $au = $this->getAuthUser();
144 $ff= HTML_FlexyFramework::get();
146 if (!empty($ff->Pman['auth_comptype']) && $au->id > 0 &&
147 ( !$au->company_id || ($ff->Pman['auth_comptype'] != $au->company()->comptype))) {
151 $this->jerr("Login not permited to outside companies - please reload");
153 $this->addEvent("RELOAD");
158 $this->addEvent("BADURL", false, $base);
159 $this->jerr("invalid url");
162 if (isset($_GET['onloadTrack'])) {
163 $this->onloadTrack = (int)$_GET['onloadTrack'];
165 // getting this to work with xhtml is a nightmare
166 // = nbsp / <img> issues screw everyting up.
167 //var_dump($this->isDev);
168 // force regeneration on load for development enviroments..
170 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
172 //header('Content-type: application/xhtml+xml; charset=utf-8');
176 if ($this->company && $this->company->logo_id) {
177 $im = DB_DataObject::Factory('Images');
178 $im->get($this->company->logo_id);
179 $this->appLogo = $this->baseURL . '/Images/Thumb/300x100/'. $this->company->logo_id .'/' . $im->filename;
182 header('Content-type: text/html; charset=utf-8');
185 function post($base) {
186 return $this->get($base);
190 // --------------- AUTHENTICATION or system information
193 * finds the compay with comptype=='OWNER'
195 * @return {Pman_Core_DataObjects_Companies} the owner company
197 function loadOwnerCompany()
199 // only applies if authtable is person..
200 $ff = HTML_FlexyFramework::get();
201 if (!empty($ff->Pman['authTable']) && $ff->Pman['authTable'] != 'Person') {
205 $this->company = DB_DataObject::Factory('Companies');
206 if (!is_a($this->company, 'DB_DataObject')) { // non-core pman projects
209 $this->company->get('comptype', 'OWNER');
210 return $this->company;
216 * getAuthUser: - get the authenticated user..
218 * @return {DB_DataObject} of type Pman[authTable] if authenticated.
221 function getAuthUser()
223 if (!empty($this->authUser)) {
224 return $this->authUser;
226 $ff = HTML_FlexyFramework::get();
227 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
229 $u = DB_DataObject::factory( $tbl );
233 $this->authUser =$u->getAuthUser();
234 return $this->authUser ;
238 * wrapper arround authuser->hasPerm
239 * @see Pman_Core_DataObjects_User::hasPerm
241 * @param {String} $name The permission name (eg. Projects.List)
242 * @param {String} $lvl eg. (C)reate (E)dit (D)elete ... etc.
245 function hasPerm($name, $lvl) // do we have a permission
247 static $pcache = array();
248 $au = $this->getAuthUser();
249 return $au && $au->hasPerm($name,$lvl);
254 * modulesList: List the modules in the application
256 * @return {Array} list of modules
258 function modulesList()
260 $boot = HTML_FlexyFramework::get();
261 // echo'<PRE>';print_R($boot);exit;
264 $mods = explode(',', $boot->enable);
265 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
266 array_unshift($mods, 'Core');
269 if (in_array($boot->appNameShort,$mods)) { // Project has to be the last modules loaded as it contains Pman.js
270 unset($mods[array_search($boot->appNameShort, $mods)]);
271 $mods[] = $boot->appNameShort;
274 $mods = array_unique($mods);
276 $disabled = explode(',', $boot->disable ? $boot->disable : '');
278 foreach($mods as $mod) {
279 // add the css file..
280 if (in_array($mod, $disabled)) {
291 function hasModule($name)
294 print_R($this->modules());exit;
295 if (!strpos( $name,'.') ) {
296 // use enable / disable..
297 return in_array($name, $this->modules());
300 $x = DB_DataObject::factory('Group_Rights');
301 $ar = $x->defaultPermData();
302 if (empty($ar[$name]) || empty($ar[$name][0])) {
317 * ---------------- Global Tools ---------------
319 function checkFileUploadError() // check for file upload errors.
322 empty($_FILES['File'])
323 || empty($_FILES['File']['name'])
324 || empty($_FILES['File']['tmp_name'])
325 || empty($_FILES['File']['type'])
326 || !empty($_FILES['File']['error'])
327 || empty($_FILES['File']['size'])
329 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
335 * generate a tempory file with an extension (dont forget to delete it)
338 function tempName($ext)
340 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
342 return $x .'.'. $ext;
345 * ------------- Authentication testing ------ ??? MOVEME?
349 function linkAuth($trid, $trkey)
351 $tr = DB_DataObject::factory('Documents_Tracking');
352 if (!$tr->get($trid)) {
353 return "Invalid URL";
355 if (strtolower($tr->authkey) != strtolower($trkey)) {
356 $this->AddEvent("ERROR-L", false, "Invalid Key");
357 return "Invalid KEY";
360 $this->onloadTrack = (int) $tr->doc_id;
361 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
362 $this->AddEvent("ERROR-L", false, "Key Expired");
363 return "Key Expired";
365 // user logged in and not
366 $au = $this->getAuthUser();
367 if ($au && $au->id && $au->id != $tr->person_id) {
370 return "Logged Out existing Session\n - reload to log in with correct key";
372 if ($au) { // logged in anyway..
373 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
374 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
379 // authenticate the user...
381 $u = DB_DataObject::factory('Person');
383 $u->get($tr->person_id);
385 $this->AddEvent("LOGIN", false, "With Key");
387 // we need to redirect out - otherwise refererer url will include key!
388 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
400 * ------------- Authentication password reset ------ ??? MOVEME?
406 function resetPassword($id,$t, $key)
409 $au = $this->getAuthUser();
411 return "Already Logged in - no need to use Password Reset";
414 $u = DB_DataObject::factory('Person');
415 //$u->company_id = $this->company->id;
417 if (!$u->get($id) || !strlen($u->passwd)) {
422 if ($key != $u->genPassKey($t)) {
423 return "invalid key";
426 $u->no_reset_sent = 0;
429 if ($t < strtotime("NOW - 1 DAY")) {
432 $this->showNewPass = implode("/", array($id,$t,$key));
437 * jerrAuth: standard auth failure - with data that let's the UI know..
441 $au = $this->authUser();
443 // is it an authfailure?
444 $this->jerr("Permission denied to view this resource", array('authFailure' => true));
446 $this->jerr("Not authenticated", array('authFailure' => true));
452 * ---------------- Standard JSON outputers. - used everywhere
453 * JSON error - simple error with logging.
457 function jerr($str, $errors=array(), $content_type = false) // standard error reporting..
459 return $this->jerror('ERROR', $str,$errors,$content_type);
462 * Recomended JSON error indicator
465 * @param string $type - normally 'ERROR' - you can use this to track error types.
466 * @param string $message - error message displayed to user.
467 * @param array $errors - optioanl data to pass to front end.
468 * @param string $content_type - use text/plain to return plan text - ?? not sure why...
472 function jerror($type, $str, $errors=array(), $content_type = false) // standard error reporting..
474 if ($type !== false) {
475 $this->addEvent($type, false, $str);
478 $cli = HTML_FlexyFramework::get()->cli;
480 echo "ERROR: " .$str . "\n";
485 if ($content_type == 'text/plain') {
486 header('Content-Disposition: attachment; filename="error.txt"');
487 header('Content-type: '. $content_type);
488 echo "ERROR: " .$str . "\n";
494 require_once 'Services/JSON.php';
495 $json = new Services_JSON();
500 if (!empty($_REQUEST['returnHTML']) ||
501 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
503 header('Content-type: text/html');
504 echo "<HTML><HEAD></HEAD><BODY>";
505 echo $json->encodeUnsafe(array(
508 'message' => $str, // compate with exeption / loadexception.
510 'errors' => $errors ? $errors : true, // used by forms to flag errors.
511 'authFailure' => !empty($errors['authFailure']),
513 echo "</BODY></HTML>";
517 if (isset($_REQUEST['_debug'])) {
518 echo '<PRE>'.htmlspecialchars(print_r(array(
522 'message' => $str, // compate with exeption / loadexception.
523 'errors' => $errors ? $errors : true, // used by forms to flag errors.
524 'authFailure' => !empty($errors['authFailure']),
530 echo $json->encode(array(
534 'message' => $str, // compate with exeption / loadexception.
535 'errors' => $errors ? $errors : true, // used by forms to flag errors.
536 'authFailure' => !empty($errors['authFailure']),
545 $cli = HTML_FlexyFramework::get()->cli;
547 echo "OK: " .$str . "\n";
550 require_once 'Services/JSON.php';
551 $json = new Services_JSON();
553 if (!empty($_REQUEST['returnHTML']) ||
554 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
557 header('Content-type: text/html');
558 echo "<HTML><HEAD></HEAD><BODY>";
559 // encode html characters so they can be read..
560 echo str_replace(array('<','>'), array('\u003c','\u003e'),
561 $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
562 echo "</BODY></HTML>";
567 echo $json->encode(array('success'=> true, 'data' => $str));
573 * output data for grids or tree
574 * @ar {Array} ar Array of data
575 * @total {Number|false} total number of records (or false to return count(ar)
576 * @extra {Array} extra key value list of data to pass as extra data.
579 function jdata($ar,$total=false, $extra=array(), $cachekey = false)
581 // should do mobile checking???
582 if ($total == false) {
585 $extra= $extra ? $extra : array();
586 require_once 'Services/JSON.php';
587 $json = new Services_JSON();
588 if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
590 header('Content-type: text/html');
591 echo "<HTML><HEAD></HEAD><BODY>";
592 // encode html characters so they can be read..
593 echo str_replace(array('<','>'), array('\u003c','\u003e'),
594 $json->encodeUnsafe(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra));
595 echo "</BODY></HTML>";
600 // see if trimming will help...
601 if (!empty($_REQUEST['_pman_short'])) {
604 foreach($ar as $as) {
606 foreach($as as $k=>$v) {
607 if (is_string($v) && !strlen(trim($v))) {
619 $ret = $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
621 if (!empty($cachekey)) {
623 $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
624 if (!file_exists(dirname($fn))) {
625 mkdir(dirname($fn), 0777,true);
627 file_put_contents($fn, $ret);
635 /** a daily cache **/
636 function jdataCache($cachekey)
638 $fn = ini_get('session.save_path') . '/json-cache'.date('/Y/m/d').'.'. $cachekey . '.cache.json';
639 if (file_exists($fn)) {
640 header('Content-type: application/json');
641 echo file_get_contents($fn);
651 * ---------------- OUTPUT
653 function hasBg($fn) // used on front page to check if logos exist..
655 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
658 * outputJavascriptIncludes:
660 * output <script....> for all the modules in the applcaiton
663 function outputJavascriptIncludes()
666 $mods = $this->modulesList();
668 foreach($mods as $mod) {
669 // add the css file..
672 $files = $this->moduleJavascriptList($mod.'/widgets');
673 foreach($files as $f) {
674 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
677 $files = $this->moduleJavascriptList($mod);
678 foreach($files as $f) {
679 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
683 if (empty($this->disable_jstemplate)) {
684 // and finally the JsTemplate...
685 echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
692 * output <link rel=stylesheet......> for all the modules in the applcaiton
695 * This could css minify as well.
697 function outputCSSIncludes() // includes on CSS links.
700 $mods = $this->modulesList();
703 foreach($mods as $mod) {
704 // add the css file..
705 $dir = $this->rootDir.'/Pman/'.$mod;
706 $ar = glob($dir . '/*.css');
707 foreach($ar as $fn) {
708 $css = $this->rootURL .'/Pman/'.$mod.'/'.basename($fn) . '?ts=' . filemtime($fn);
709 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
718 * Gather infor for javascript files..
720 * @param {String} $mod the module to get info about.
721 * @return {StdClass} details about module.
723 function moduleJavascriptFilesInfo($mod)
726 static $cache = array();
728 if (isset($cache[$mod])) {
733 $ff = HTML_FlexyFramework::get();
735 $base = dirname($_SERVER['SCRIPT_FILENAME']);
736 $dir = $this->rootDir.'/Pman/'. $mod;
737 $path = $this->rootURL ."/Pman/$mod/";
739 $ar = glob($dir . '/*.js');
745 foreach($ar as $fn) {
747 // got the 'module file..'
748 $mtime = filemtime($dir . '/'. $f);
749 $maxtime = max($mtime, $maxtime);
750 $arfiles[$fn] = $mtime;
751 $files[] = $path . $f . '?ts='.$mtime;
754 ksort($arfiles); // just sort by name so it's consistant for serialize..
756 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
757 $basedir = $compile ? $ff->Pman['public_cache_dir'] : false;
758 $baseurl = $compile ? $ff->Pman['public_cache_url'] : false;
760 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
761 usort($files, $lsort);
763 $smod = str_replace('/','.',$mod);
765 $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
768 // why are translations done like this - we just build them on the fly frmo the database..
769 $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
770 ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
772 $cache[$mod] = (object) array(
773 'smod' => $smod, // module name without '/'
774 'files' => $files, // list of all files.
775 'filesmtime' => $arfiles, // map of mtime=>file
776 'maxtime' => $maxtime, // max mtime
777 'compile' => $this->isDev ? false : $compile,
778 'translation_file' => $base .'/_translations_/' . $smod . '.js',
779 'translation_mtime' => $tmtime,
781 'translation_data' => preg_replace('/\.js$/', '.__translation__.js', $output),
782 'translation_base' => $dir .'/', //prefix of filename (without moudle name))
783 'basedir' => $basedir,
784 'baseurl' => $baseurl,
785 'module_dir' => $dir,
792 * moduleJavascriptList: list the javascript files in a module
794 * The original version of this.. still needs more thought...
796 * Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
797 * Translations are in Pman/_translations_/{$mod}.js
799 * if that stuff does not exist just list files in Pman/{$mod}/*.js
801 * Compiled could be done on the fly..
805 * @param {String} $mod the module to look at - eg. Pman/{$mod}/*.js
806 * @return {Array} list of include paths (either compiled or raw)
812 function moduleJavascriptList($mod)
816 $dir = $this->rootDir.'/Pman/'. $mod;
819 if (!file_exists($dir)) {
820 echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
824 $info = $this->moduleJavascriptFilesInfo($mod);
828 if (empty($info->files)) {
831 // finally sort the files, so they are in the right order..
833 // only compile this stuff if public_cache is set..
837 // public_cache_dir = /var/www/myproject_cache
838 // public_cache_url = /myproject_cache (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
841 if (!$info->compile) {
842 echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
846 // where are we going to write all of this..
847 // This has to be done via a
848 if (!file_exists($info->basedir.'/'.$info->output) || !filesize($info->basedir.'/'.$info->output)) {
849 require_once 'Pman/Core/JsCompile.php';
850 $x = new Pman_Core_JsCompile();
852 $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
854 echo "<!-- file exists not exist: {$info->basedir}/{$info->output} -->\n";
857 if (file_exists($info->basedir.'/'.$info->output) &&
858 filesize($info->basedir.'/'.$info->output)) {
861 $info->baseurl.'/'. $info->output,
864 // output all the ava
865 // fixme - this needs the max datetime for the translation file..
866 $ret[] = $this->baseURL."/Admin/InterfaceTranslations/".$mod.".js"; //?ts=".$info->translation_mtime;
868 //if ($info->translation_mtime) {
869 // $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
876 // give up and output original files...
886 * PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
889 static $permitError = false;
891 function onPearError($err)
893 static $reported = false;
898 if (Pman::$permitError) {
906 $out = $err->toString();
909 //print_R($bt); exit;
912 foreach($err->backtrace as $b) {
913 $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' . @$b['class'] . '::' . @$b['function'];
919 //convert the huge backtrace into something that is readable..
920 $out .= "\n" . implode("\n", $ret);
931 * ---------------- Logging ---------------
936 * Log an action (only if it has not been logged already.
938 * @param {String} action - group/name of event
939 * @param {DataObject|false} obj - dataobject action occured on.
940 * @param {String} any remarks
941 * @return {false|DB_DataObject} Event object.,
944 function addEventOnce($act, $obj = false, $remarks = '')
946 if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
949 $e = DB_DataObject::factory('Events');
950 $e->init($act,$obj,$remarks);
951 if ($e->find(true)) {
954 return $this->addEvent($act, $obj, $remarks);
960 * @param {String} action - group/name of event
961 * @param {DataObject|false} obj - dataobject action occured on.
962 * @param {String} any remarks
963 * @return {DB_DataObject} Event object.,
966 function addEvent($act, $obj = false, $remarks = '')
969 if (!empty(HTML_FlexyFramework::get()->Pman['disable_events'])) {
972 $au = $this->getAuthUser();
974 $e = DB_DataObject::factory('Events');
975 $e->init($act,$obj,$remarks);
977 $e->event_when = date('Y-m-d H:i:s');
981 // fixme - this should be in onInsert..
982 $wa = DB_DataObject::factory('core_watch');
983 if (method_exists($wa,'notifyEvent')) {
984 $wa->notifyEvent($e); // trigger any actions..
988 $e->onInsert(isset($_REQUEST) ? $_REQUEST : array() , $this);
994 // ------------------ DEPERCIATED ----------------------------
996 // DEPRECITAED - use moduleslist
997 function modules() { return $this->modulesList(); }
999 // DEPRECIATED.. - use getAuthUser...
1000 function staticGetAuthUser() { $x = new Pman(); return $x->getAuthUser(); }
1003 // DEPRICATED USE Pman_Core_Mailer
1005 function emailTemplate($templateFile, $args)
1008 require_once 'Pman/Core/Mailer.php';
1009 $r = new Pman_Core_Mailer(array(
1010 'template'=>$templateFile,
1011 'contents' => $args,
1014 return $r->toData();
1017 // DEPRICATED - USE Pman_Core_Mailer
1018 // WHAT Part about DEPRICATED Does no one understand??
1019 function sendTemplate($templateFile, $args)
1021 require_once 'Pman/Core/Mailer.php';
1022 $r = new Pman_Core_Mailer(array(
1023 'template'=>$templateFile,
1024 'contents' => array(),