DataObjects/Core_company.php
[Pman.Core] / DataObjects / Core_company.php
1 <?php
2 /**
3  * Table Definition for Companies
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_Company extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_company';                       // table name
13     public $code;                            // string(32)  not_null
14     public $name;                            // string(128)  
15     public $remarks;                         // blob(65535)  blob
16     public $owner_id;                        // int(11)  not_null
17     public $address;                         // blob(65535)  blob
18     public $tel;                             // string(32)  
19     public $fax;                             // string(32)  
20     public $email;                           // string(128)  
21     public $id;                              // int(11)  not_null primary_key auto_increment
22     public $isOwner;                         // int(11)  
23     public $logo_id;                         // int(11)  not_null
24     public $background_color;                // string(8)  not_null
25     public $comptype;                        // string(8)  not_null
26     public $url;                             // string(254)  not_null
27     public $main_office_id;                  // int(11)  not_null
28     public $created_by;                      // int(11)  not_null
29     public $created_dt;                      // datetime(19)  not_null binary
30     public $updated_by;                      // int(11)  not_null
31     public $updated_dt;                      // datetime(19)  not_null binary
32     public $passwd;                          // string(64)  not_null
33     public $dispatch_port;                   // string(255)  not_null
34     public $province;                        // string(255)  not_null
35     public $country;                         // string(4)  not_null
36     public $is_system;                       // int(2)
37     
38     /* the code above is auto generated do not remove the tag below */
39     ###END_AUTOCODE
40     
41     function applyFilters($q, $au)
42     {
43         
44         $tn = $this->tableName();
45         $this->selectAdd("i18n_translate('c' , {$tn}.country, 'en') as country_display_name ");
46       
47         $tn = $this->tableName();
48         //DB_DataObject::debugLevel(1);
49         $x = DB_DataObject::factory('core_company');
50         $x->comptype= 'OWNER';
51         $x->find(true);
52         
53         if (!empty($q['query']['company_project_id'])) {
54             $add = '';
55             if (!empty($q['query']['company_include_self'])) {
56                 $add = " OR {$tn}.id = {$x->id}";
57             }
58             if (!empty($q['query']['company_not_self'])) {
59                 $add = " AND {$tn}.id != {$x->id}";
60             }
61             $pids = array();
62             $pid = $q['query']['company_project_id'];
63             if (strpos($pid, ',')) {
64                 $bits = explode(',', $pid);
65                 foreach($bits as $b) {
66                     $pids[] = (int)$b;
67                 }
68             } else {
69                 $pids = array($pid);
70             }
71             
72             
73             $pids = implode(',', $pids);
74             $this->whereAdd("{$tn}.id IN (
75                 SELECT distinct(company_id) FROM ProjectDirectory where project_id IN ($pids)
76             ) $add" );
77              
78         }
79         if (!empty($q['query']['comptype'])) {
80            
81             $this->whereAddIn('comptype', explode(',', $q['query']['comptype']), 'string');
82             
83         }
84         
85         // depricated - should be moved to module specific (texon afair)
86         
87          if (!empty($q['query']['province'])) {
88              $prov = $this->escape($q['query']['province']);
89             $this->whereAdd("province LIKE '$prov%'");
90             
91             
92         }
93         // ADD comptype_display name.. = for combos..
94         $this->selectAdd("
95             (SELECT display_name
96                 FROM
97                     core_enum
98                 WHERE
99                     etype='comptype'
100                     AND
101                     name={$tn}.comptype
102                 LIMIT 1
103                 ) as comptype_display_name
104         ");
105         
106         if(!empty($q['search']['name'])){
107             $s = $this->escape($q['search']['name']);
108             $this->whereAdd("
109                 {$tn}.name LIKE '%$s%'
110             ");
111         }
112         if(!empty($q['search']['name_starts'])){
113             $s = $this->escape($q['search']['name_starts']);
114             $this->whereAdd("
115                 {$tn}.name LIKE '$s%'
116             ");
117         }
118     }
119     
120     function toEventString() {
121         return $this->name;
122     }
123     
124     // ---------- AUTHENTICATION
125     // not sure where authetnication via company is used?? posibly media-outreach
126     
127     function isAuth()
128     {
129         $db = $this->getDatabaseConnection();
130         $sesPrefix = $db->dsn['database'];
131         @session_start();
132         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
133             // in session...
134             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
135             $u = DB_DataObject::factory('core_company');
136             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
137                 return true;
138             }
139             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
140             
141         }
142         // not in session or not matched...
143         
144         
145         return false;
146         
147     }
148     function getAuthUser()
149     {
150         if (!$this->isAuth()) {
151             return false;
152         }
153         $db = $this->getDatabaseConnection();
154         $sesPrefix = $db->dsn['database'];
155         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
156             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
157             
158             $u = DB_DataObject::factory('core_company');
159             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
160                 return clone($u);
161             }
162              
163         }
164         
165         
166         return false;
167     }     
168     function login()
169     {
170         $this->isAuth(); // force session start..
171          $db = $this->getDatabaseConnection();
172         $sesPrefix = $db->dsn['database'];
173         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
174         
175     }
176     function logout()
177     {
178         $this->isAuth(); // force session start..
179         $db = $this->getDatabaseConnection();
180         $sesPrefix = $db->dsn['database'];
181         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
182         
183     }    
184     // ---------- AUTHENTICATION
185     function checkPassword($val)
186     {
187         //echo '<pre>'.$val .  print_R($this,true);
188         if (substr($this->passwd,0,1) == '$') {
189             return crypt($val,$this->passwd) == $this->passwd ;
190         }
191         // old style md5 passwords...- cant be used with courier....
192         return md5($val) == $this->passwd;
193     }
194     function setPassword($value) 
195     {
196         $salt='';
197         while(strlen($salt)<9) {
198             $salt.=chr(rand(64,126));
199             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
200         }
201         $this->passwd = crypt($value, '$1$'. $salt. '$');
202        
203     }      
204     function onUpload($controller)
205     {
206         $image = DB_DataObject::factory('Images');
207         return $image->onUploadWithTbl($this, 'logo_id');
208          
209     }
210     function  onUpdate($old, $req,$roo) 
211     {
212         if (!empty($req['password1'])) {
213             $this->setPassword($req['password1']);
214             $this->update();
215         }
216     }
217     function onInsert($req, $roo)
218     {
219         if (!empty($this->logo_id)) { // update images table to sycn with this..
220             $img = DB_DataObject::factory('Images');
221             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
222                 $img->onid = $this->id;
223                 $img->update();
224             }
225         }
226         if (!empty($req['password1'])) {
227             $this->setPassword($req['password1']);
228             $this->update();
229         }
230         $img = DB_DataObject::factory('Images');
231         $img->onid= 0;
232         
233         $img->ontable = $this->tableName();
234         $img->imgtype = 'LOGO';
235         // should check uploader!!!
236         if ($img->find()) {
237             while($img->fetch()) {
238                 $ii = clone($img);
239                 $ii->onid = $this->id;
240                 $ii->update();
241                 $this->logo_id = $ii->id;
242             }
243             $this->update();
244         }
245         
246     }
247     
248     function beforeInsert($q, $roo)
249     {
250         if(!empty($q['_check_name'])){
251             if($this->checkName()){
252                 $roo->jok('OK');
253             }
254             
255             $roo->jerr('EXIST');
256         }
257     }
258     
259     function beforeUpdate($old, $q,$roo)
260     {
261         if(!empty($q['_check_name'])){
262             if($this->checkName()){
263                 $roo->jok('OK');
264             }
265             
266             $roo->jerr('EXIST');
267         }
268         
269         if(!empty($q['_merge_id'])){
270             $this->merge($q['_merge_id'], $roo);
271         }
272         
273         if(!empty($this->is_system) && 
274             ($old->code != $this->code  ) // used to be not allowed to change name..
275         ){
276             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
277         }
278     }
279     
280     function beforeDelete($req, $roo)
281     {
282         // should check for members....
283         if(!empty($this->is_system) && 
284             ($old->code != $this->code || $old->name != $this->name)
285         ){
286             $roo->jerr('This company is not allow to delete');
287         }
288     }
289     function onDelete($req, $roo)
290     {
291         $img = DB_DataObject::factory('Images');
292         $img->ontable = $this->tableName();
293         $img->onid = $this->id;
294         $img->find();
295         while ($img->fetch()) {
296             $img->beforeDelete();
297             $img->delete();
298         }
299         return true;
300         
301          
302     }
303     /**
304      * check who is trying to access this. false == access denied..
305      */
306     function checkPerm($lvl, $au, $changes = false) 
307     {
308         
309         // do we have an empty system..
310         if ($au && $au->id == -1) {
311             return true;
312         }
313         
314         
315         
316         if ($au->company()->comptype != 'OWNER') {
317             
318             // hacking!
319             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
320                 return false;
321             }
322             
323             return $this->id == $au->company_id;
324         }
325         
326         return $au->hasPerm("Core.Companies", $lvl);    
327     }
328     
329     function logoImageToHTML($size)
330     {
331         $i = DB_DataObject::factory('Images');
332         if (!$this->logo_id || !$i->get($this->logo_id)) {
333             return '';
334         }
335         return $i->toHTML($size);
336         
337     }
338      function firstImage($filter='image/%')
339     {
340         $i = DB_DataObject::factory('Images');
341         //DB_DataObject::debugLevel(1);
342         $im = $i->gather($this, $filter);
343         if (empty($im)) {
344             return false;
345         }
346         return $im[0];
347     }
348     
349     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
350     {
351         $fm = $this->firstImage($filter);
352          if (empty($fm)) {
353             return '';
354         }
355         return $fm->toHTML($size, $base);
356     }
357     
358     function toRooSingleArray($authUser, $request)
359     {
360         $ret = $this->toArray();
361        // DB_DataObject::debugLevel(1);
362         // get the comptype display
363         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
364         
365         $ret['comptype_display'] = $ret['comptype'];
366         if ($e   && !empty($e->name_display)) {
367             $ret['comptype_display'] = $e->name_display;
368         }
369         
370         
371         return $ret;
372     }
373     
374     /**
375      * # 2028 
376      * create the suppliers...
377      * 
378      * @param object $roo
379      * @param array $data
380      * 
381      */
382     function initCompaniesArray($roo, $data)
383     {
384         $tn = $this->tableName();
385         
386         foreach($data as $d){
387             $com = DB_DataObject::factory($tn);
388             $com->setFrom($d);
389             if(!$com->find(true)){
390                 $com->created_dt = Date('Y-m-d H:i:s');
391                 $com->updated_dt = Date('Y-m-d H:i:s');
392                 $com->is_system = 1;// new column.. block the user changing the code and name..
393                 $com->insert();
394             }
395         }
396         
397         
398     }
399     
400     
401     function initCompanies($roo, $opts)
402     {
403         $companies = DB_DataObject::factory('core_company');
404         
405         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
406         
407         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
408         
409         if (empty($enum)) {
410             $roo->jerr("invalid company type '$ctype'");
411         }
412         if ($ctype =='OWNER') {
413             $companies = DB_DataObject::factory('core_company');
414             $companies->comptype_id = $enum;
415             if ($companies->count()) {
416                 $roo->jerr("Owner  company already exists");
417             }
418         }
419         $companies = DB_DataObject::factory('core_company');
420         
421         // check that 
422         $companies->setFrom(array(
423             'name' => $opts['add-company'],
424             'comptype' => $ctype,
425             'comptype_id' => $enum,
426         ));
427         if ($companies->find(true)) {
428             $roo->jerr("company already exists");
429         }
430         $companies->setFrom(array(
431             'background_color' => '',
432             'created_dt' => $this->sqlValue('NOW()'),
433             'updated_dt' => $this->sqlValue('NOW()')
434         ));
435         
436         
437         $companies->insert();
438         $companies->onInsert(array(), $roo);
439     }
440     static function lookupOwner()
441     {
442         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
443         $companies = DB_DataObject::factory('core_company');
444         $companies->comptype_id = $enum;
445         if ($companies->find(true)) {
446             return $companies;
447         }
448         return false;
449     }
450     
451     function merge($merge_to, $roo)
452     {
453         $affects  = array();
454         
455         $all_links = $this->databaseLinks();
456         
457         foreach($all_links as $tbl => $links) {
458             foreach($links as $col => $totbl_col) {
459                 $to = explode(':', $totbl_col);
460                 if ($to[0] != $this->tableName()) {
461                     continue;
462                 }
463                 
464                 $affects[$tbl .'.' . $col] = true;
465             }
466         }
467         
468         foreach($affects as $k => $true) {
469             $ka = explode('.', $k);
470
471             $chk = DB_DataObject::factory($ka[0]);
472             
473             if (!is_a($chk,'DB_DataObject')) {
474                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
475             }
476             
477             $chk->{$ka[1]} = $this->id;
478
479             foreach ($chk->fetchAll() as $c){
480                 $cc = clone ($c);
481                 $c->{$ka[1]} = $merge_to;
482                 $c->update($cc);
483             }
484         }
485         
486         $this->delete();
487         
488         $roo->jok('Merged');
489         
490     }
491     
492     function checkName()
493     {
494         $company = DB_DataObject::factory('core_company');
495         $company->setFrom(array(
496             'name' => $this->name
497         ));
498         
499         if(!empty($this->id)){
500             $company->whereAdd("id != {$this->id}");
501         }
502         
503         if(!$company->find(true)){
504             return true;
505         }
506         
507         return false;
508     }
509 }