3 * Table Definition for Images
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Images extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Images'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $filename; // string(255) not_null
15 public $ontable; // string(32) not_null multiple_key
16 public $onid; // int(11) not_null
17 public $mimetype; // string(64) not_null
18 public $width; // int(11) not_null
19 public $height; // int(11) not_null
20 public $filesize; // int(11) not_null
21 public $displayorder; // int(11) not_null
22 public $language; // string(6) not_null
23 public $parent_image_id; // int(11) not_null
24 public $created; // datetime(19) not_null binary
25 public $imgtype; // string(32) not_null
26 public $linkurl; // string(254) not_null
27 public $descript; // blob(65535) not_null blob
28 public $title; // string(128) not_null
30 /* the code above is auto generated do not remove the tag below */
32 function applyFilters($q, $au, $roo)
34 $tn = $this->tableName();
36 if(!empty($q['search']['filename'])){
38 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
41 echo $this->whereAdd("
42 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
47 function checkPerm($lvl, $au)
49 // default permissons are to
50 // allow create / edit / if the user has
58 if (method_exists($o, 'checkPerm')) {
59 // edit permissions on related object needed...
60 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
64 return true; //// ??? not really that safe...
68 function beforeInsert($q, $roo)
70 if (isset($q['_remote_upload'])) {
71 require_once 'System.php';
73 $tmpdir = System::mktemp("-d remote_upload");
75 $path = $tmpdir . '/' . basename($q['_remote_upload']);
77 if(!file_exists($path)){
78 file_put_contents($path, file_get_contents($q['_remote_upload']));
81 $imageInfo = getimagesize($path);
83 require_once 'File/MimeType.php';
84 $y = new File_MimeType();
85 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
87 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
88 rename($path,$path.".".$ext);
92 if (!$this->createFrom($path)) {
93 $roo->jerr("erro making image" . $q['_remote_upload']);
96 if(!empty($q['_return_after_create'])){
100 $roo->addEvent("ADD", $this, $this->toEventString());
102 $r = DB_DataObject::factory($this->tableName());
107 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
114 * create an email from file.
115 * these must have been set first.
119 function createFrom($file, $filename=false)
121 // copy the file into the storage area..
122 if (!file_exists($file) || !filesize($file)) {
123 $this->err = "File $file did not exist or is 0 size";
127 $filename = empty($filename) ? $file : $filename;
129 if (empty($this->mimetype)) {
130 require_once 'File/MimeType.php';
131 $y = new File_MimeType();
132 $this->mimetype = $y->fromFilename($filename);
135 $this->mimetype = strtolower($this->mimetype);
137 $mta = explode('/', $this->mimetype);
138 if (array_shift($mta) == 'image') {
140 $imgs = @getimagesize($file);
142 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
145 list($this->width , $this->height) = $imgs;
149 if($this->mimetype == 'application/pdf'){
150 $this->no_of_pages = $this->getPdfPages($file);
153 $this->filesize = filesize($file);
154 $this->created = date('Y-m-d H:i:s');
157 if (empty($this->filename)) {
158 $this->filename = basename($filename);
161 //DB_DataObject::debugLevel(1);
170 $f = $this->getStoreName();
172 if (!file_exists($dest)) {
173 // currently this is 0775 due to problems using shared hosing (FTP)
174 // it makes all the files unaccessable..
175 // you can normally solve this by giving the storedirectory better perms
176 // if needed on a dedicated server..
177 $oldumask = umask(0);
178 mkdir($dest, 0775, true);
189 // $this->createThumbnail(0,50);
195 * Calculate target file name
197 * @return - target file name
199 function getStoreName()
201 $opts = HTML_FlexyFramework::get()->Pman;
202 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
203 return implode( '/', array(
204 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
210 * deletes all the image instances of it...
214 function beforeDelete($dependants_array, $roo)
217 $opts = HTML_FlexyFramework::get()->Pman;
218 $deldir = $opts['storedir']. '/_deleted_images_';
219 if (!file_exists( $deldir )) {
220 mkdir($deldir, 0755);
223 $fn = $this->getStoreName();
225 if (file_exists($fn)) {
227 if (file_exists($deldir . '/'. $b)) {
230 rename($fn, $deldir .'/'. $b);
238 if (file_exists($d)) {
241 while (false !== ($fn = readdir($dh))) {
242 if (substr($fn, 0, strlen($b)) == $b) {
244 if (file_exists($deldir . '/'. $fn)) {
245 unlink($d. '/'. $fn);
248 rename($d. '/'. $fn, $deldir .'/'. $fn);
256 * check mimetype against type
257 * - eg. img.is(#image#)
262 if (empty($this->mimetype)) {
265 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
269 * onUpload (singlely attached image to a table)
272 function onUploadWithTbl($tbl, $fld)
274 if ( $tbl->__table == 'Images') {
275 return; // not upload to self...
277 if (empty($_FILES['imageUpload']['tmp_name']) ||
278 empty($_FILES['imageUpload']['name']) ||
279 empty($_FILES['imageUpload']['type'])
284 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
286 $image = DB_DataObject::factory('Images');
287 $image->get($tbl->$fld);
288 $image->beforeDelete();
292 $image = DB_DataObject::factory('Images');
293 $image->onid = $tbl->id;
294 $image->ontable = $tbl->__table;
295 $image->filename = $_FILES['imageUpload']['name'];
296 $image->mimetype = $_FILES['imageUpload']['type'];
298 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
302 $tbl->$fld = $image->id;
309 function onUpload($roo)
311 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
312 if (empty($_FILES['imageUpload']['tmp_name']) ||
313 empty($_FILES['imageUpload']['name']) ||
314 empty($_FILES['imageUpload']['type'])
318 0=>"There is no error, the file uploaded with success",
319 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
320 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
321 3=>"The uploaded file was only partially uploaded",
322 4=>"No file was uploaded",
323 6=>"Missing a temporary folder"
325 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
326 $this->err = "Missing file details : Error=". $estr;
331 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
333 $this->beforeDelete();
335 if ( empty($this->ontable)) {
336 $this->err = "Missing ontable";
340 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
341 // then its an upload
342 $img = DB_DataObject::factory('Images');
343 $img->onid = $this->onid;
344 $img->ontable = $this->ontable;
345 $img->imgtype = $this->imgtype;
348 while ($img->fetch()) {
349 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
351 $img->beforeDelete();
359 require_once 'File/MimeType.php';
360 $y = new File_MimeType();
361 $this->mimetype = $_FILES['imageUpload']['type'];
362 if (in_array($this->mimetype, array(
364 'application/octet-stream',
365 'image/x-png', // WTF does this?
366 'image/pjpeg', // WTF does this?
367 'application/x-apple-msg-attachment', /// apple doing it's magic...
368 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
369 'application/csv-tab-delimited-table', // windows again!!?
370 ))) { // weird tyeps..
371 $inf = pathinfo($_FILES['imageUpload']['name']);
372 $this->mimetype = $y->fromExt($inf['extension']);
376 $ext = $y->toExt(trim((string) $this->mimetype ));
378 $this->filename = empty($this->filename) ?
379 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
383 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
384 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
394 * return a list of images for an object, optionally with a mime regex.
395 * eg. '%/pdf' or 'image/%'
399 * $i = DB_DataObject::factory('Images');
400 * $i->imgtype = 'LOGO';
401 * $ar = $i->gather($somedataobject, 'image/%');
403 * @param {DB_DataObject} dataobject = the object to gather data on.
404 * @param {String} mimelike LIKE query to use for search
407 function gather($obj, $mime_like='', $opts=array())
409 //DB_DataObject::debugLevel(1);
410 if (empty($obj->id)) {
415 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
418 if (!empty($mime_like)) {
419 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
421 $c->orderBy('created DESC');
423 return $c->fetchAll();
428 * set or get the dataobject this image is associated with
429 * @param DB_DataObject $obj An object to associate this image with
430 * (does not store it - you need to call update() to do that)
431 * @return DB_DataObject the dataobject this image is attached to.
433 function object($obj=false)
435 if ($obj === false) {
436 if (empty($this->ontable) || empty($this->onid)) {
439 $ret = DB_DataObject::factory($this->ontable);
440 $ret->get($this->onid);
445 $this->ontable = $obj->tableName();
446 $this->onid = $obj->id; /// assumes our nice standard of using ids..
451 function toRooArray($req) {
453 $ret= $this->toArray();
457 $ff = HTML_FlexyFramework::get();
460 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
461 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
463 if (!empty($req['query']['imagesize'])) {
464 // query/imageBaseURL ... depricated...? -- set it in config?
466 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
468 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
470 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
472 if (!empty($req['query']['imagesize'])) {
473 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
483 * URL - create a url for the image.
484 * size - use -1 to show full size.
485 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
489 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
492 return 'about:blank';
496 $ff = HTML_FlexyFramework::get();
497 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
498 if (preg_match('#^http[s]*://#', $provider)) {
503 $provider = preg_replace('#/Thumb$#', '', $provider);
505 return $baseURL . $provider . "/{$this->id}/{$this->filename}";
508 //$size = max(100, (int) $size);
509 //$size = min(1024, (int) $size);
510 // the size should 200x150 to convert
511 $sizear = preg_split('/(x|c)/', $size);
512 if(empty($sizear[1])){
515 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
517 $fc = $this->toFileConvert();
520 $mt = $this->mimetype;
521 if (!preg_match('#^image/#i',$mt)) {
525 $fc->convert($mt, $size);
527 return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
530 * size could be 123x345
534 function toHTML($size, $provider = '/Images/Thumb')
539 $sz = explode('x', $size);
542 if (!$this->id || empty($this->width)) {
544 $this->width = empty($sz[1]) ? $sx : $sz[1];
548 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
555 if (strlen($this->title)) {
556 $extra = ' title="'. htmlspecialchars($this->title) . '"';
559 return '<img src="' . $this->URL($size, $provider) . '"' .
561 ' width="'. $sx . '"' .
562 ' height="'. $sy . '">';
569 * #2142 [new] CMS - image link urls
574 function toLinkHTML($size, $provider = '/Images/Thumb')
576 if(empty($this->linkurl)){
577 return $this->toHTML($size, $provider = '/Images/Thumb');
580 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
586 * to Fileconvert object..
591 function toFileConvert()
593 require_once 'File/Convert.php';
594 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
601 require_once 'File/MimeType.php';
603 $y = new File_MimeType();
604 return $y->toExt($this->mimetype);
616 function setFromRoo($ar, $roo)
618 // not sure why we do this..
620 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
621 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
624 if ($this->find(true)) {
625 $roo->old = clone($this);
630 if (!empty($ar['_copy_from'])) {
632 if (!$this->checkPerm( 'A' , $roo->authUser)) {
633 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
636 $copy = DB_DataObject::factory('Images');
637 $copy->get($ar['_copy_from']);
638 $this->setFrom($copy->toArray());
640 $this->createFrom($copy->getStoreName());
642 $roo->addEvent("ADD", $this, $this->toEventString());
644 $r = DB_DataObject::factory($this->tableName());
649 $roo->jok($r->toArray());
656 // FIXME - we should be checking perms here...
658 // this should be doign update
661 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
662 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
667 if (!isset($_FILES['imageUpload'])) {
668 return; // standard update...
672 // print_r(!$this->onUpload($this));
674 if ( !$this->onUpload($this)) {
675 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
678 $this->addEvent($ar, $roo);
680 $r = DB_DataObject::factory($this->tableName());
685 $roo->jok($r->toArray());
689 function addEvent($ar, $roo)
691 $roo->addEvent("ADD", $this, $this->toEventString());
694 function toEventString()
697 //$p = DB_DataObject::factory($this->ontable);
699 // return "ERROR unknown table? {$this->ontable}";
703 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
704 //$p->toEventString();
707 function onUploadFromData($data, $roo)
710 $this->err = "Missing file details";
715 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
717 $this->beforeDelete();
720 if (empty($this->ontable)) {
721 $this->err = "Missing ontable";
725 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
726 // then its an upload
727 $img = DB_DataObject::factory('Images');
728 $img->onid = $this->onid;
729 $img->ontable = $this->ontable;
730 $img->imgtype = $this->imgtype;
733 while ($img->fetch()) {
734 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
736 $img->beforeDelete();
742 require_once 'File/MimeType.php';
743 $y = new File_MimeType();
745 if (in_array($this->mimetype, array(
747 'application/octet-stream',
748 'image/x-png', // WTF does this?
749 'image/pjpeg', // WTF does this?
750 'application/x-apple-msg-attachment', /// apple doing it's magic...
751 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
752 'application/csv-tab-delimited-table', // windows again!!?
753 ))) { // weird tyeps..
754 $inf = pathinfo($this->filename);
755 $this->mimetype = $y->fromExt($inf['extension']);
758 $ext = $y->toExt(trim((string) $this->mimetype ));
760 if(array_pop(explode('.', $this->filename)) != $ext){
761 $this->filename = $this->filename .'.'. $ext;
764 if (!$this->createFromData($data)) {
772 function createFromData($data)
775 $this->mimetype= strtolower($this->mimetype);
777 if (array_shift(explode('/', $this->mimetype)) == 'image') {
779 $imgs = @getimagesize($data);
781 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
782 list($this->width , $this->height) = $imgs;
786 $this->created = date('Y-m-d H:i:s');
794 $f = $this->getStoreName();
796 if (!file_exists($dest)) {
797 $oldumask = umask(0);
798 mkdir($dest, 0775, true);
802 file_put_contents($f, file_get_contents("data://" . $data));
806 $this->filesize = filesize($f);
808 if($this->mimetype == 'application/pdf'){
809 $this->no_of_pages = $this->getPdfPages($f);
820 if(!preg_match('/^image\//', $this->mimetype)){
824 $file = $this->getStoreName();
826 if(!file_exists($file)){
830 $data = file_get_contents($file);
832 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
837 function getPdfPages($file)
839 require_once 'System.php';
843 $pdfinfo = System::which('pdfinfo');
845 if (!file_exists($file) || empty($pdfinfo)) {
849 $cmd = "{$pdfinfo} {$file}";
853 $info = explode("\n", $ret);
855 foreach ($info as $i){
857 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
861 $page = (empty($matches[1])) ? 0 : $matches[1];