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