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