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'])}%' OR $tn.title LIKE '%{$this->escape($q['search']['filename'])}%'
42 if(!empty($q['_to_base64']) && !empty($q['image_id'])) {
43 $i = DB_DataObject::factory("Images");
44 $i->get($q['image_id']);
45 $roo->jok($i->toBase64());
51 function checkPerm($lvl, $au)
53 // default permissons are to
54 // allow create / edit / if the user has
62 if ($o && method_exists($o, 'checkPerm')) {
63 // edit permissions on related object needed...
64 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
68 return true; //// ??? not really that safe...
72 function beforeInsert($q, $roo)
74 if (isset($q['_remote_upload'])) {
75 require_once 'System.php';
77 $tmpdir = System::mktemp("-d remote_upload");
79 $path = $tmpdir . '/' . basename($q['_remote_upload']);
81 if(!file_exists($path)){
82 file_put_contents($path, file_get_contents($q['_remote_upload']));
85 $imageInfo = getimagesize($path);
87 require_once 'File/MimeType.php';
88 $y = new File_MimeType();
89 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
91 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
92 rename($path,$path.".".$ext);
96 if (!$this->createFrom($path)) {
97 $roo->jerr("erro making image" . $q['_remote_upload']);
100 if(!empty($q['_return_after_create'])){
104 $roo->addEvent("ADD", $this, $this->toEventString());
106 $r = DB_DataObject::factory($this->tableName());
111 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
118 * create an email from file.
119 * these must have been set first.
123 function createFrom($file, $filename=false)
125 // copy the file into the storage area..
126 if (!file_exists($file) || !filesize($file)) {
127 $this->err = "File $file did not exist or is 0 size";
131 $filename = empty($filename) ? $file : $filename;
133 if (empty($this->mimetype)) {
134 require_once 'File/MimeType.php';
135 $y = new File_MimeType();
136 $this->mimetype = $y->fromFilename($filename);
139 $this->mimetype = strtolower($this->mimetype);
141 $mta = explode('/', $this->mimetype);
142 if (array_shift($mta) == 'image') {
144 $imgs = @getimagesize($file);
146 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
149 list($this->width , $this->height) = $imgs;
153 if($this->mimetype == 'application/pdf'){
154 $this->no_of_pages = $this->getPdfPages($file);
157 $this->filesize = filesize($file);
158 $this->created = date('Y-m-d H:i:s');
161 if (empty($this->filename)) {
162 $this->filename = basename($filename);
165 //DB_DataObject::debugLevel(1);
174 $f = $this->getStoreName();
176 if (!file_exists($dest)) {
177 // currently this is 0775 due to problems using shared hosing (FTP)
178 // it makes all the files unaccessable..
179 // you can normally solve this by giving the storedirectory better perms
180 // if needed on a dedicated server..
181 $oldumask = umask(0);
182 mkdir($dest, 0775, true);
193 // $this->createThumbnail(0,50);
199 * Calculate target file name
201 * @return - target file name
203 function getStoreName()
205 $opts = HTML_FlexyFramework::get()->Pman;
206 $fn = preg_replace('/[^a-z0-9_\.]+/i', '_', $this->filename);
207 return implode( '/', array(
208 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
214 * does the files exist?
219 //var_dump($this->getStoreName());
220 $ret = file_exists($this->getStoreName());
222 return $this->canFix();
227 * the getStorename code got changed, and some old files may not end up with the correct name anymore.
228 * this tries to fix it.
232 // look for the image in the folder, with matching id.
233 // this is problematic..
234 $fn = $this->getStoreName();
235 if (file_exists($fn . '-really-missing')) {
238 if (!file_exists(dirname($fn))) {
241 foreach( scandir(dirname($fn)) as $n) {
242 if (empty($n) || $n[0] == '.') {
245 $bits = explode('-', $n);
246 if ($bits[0] != $this->id) {
249 if (preg_match('/\.[0-9]+x[0-9]]+\.jpeg$/', $n)) {
252 copy(dirname($fn). '/'. $n, $fn);
256 // fixme - flag it as bad
257 touch($fn . '-really-missing');
262 * deletes all the image instances of it...
266 function beforeDelete($dependants_array, $roo)
269 if (!empty($dependants_array)) {
273 $opts = HTML_FlexyFramework::get()->Pman;
274 $deldir = $opts['storedir']. '/_deleted_images_';
276 if (!file_exists( $deldir )) {
277 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
280 $fn = $this->getStoreName();
283 if (file_exists($fn)) {
285 if (file_exists($deldir . '/'. $b)) {
288 rename($fn, $deldir .'/'. $b);
296 if (file_exists($d)) {
299 while (false !== ($fn = readdir($dh))) {
300 if (substr($fn, 0, strlen($b)) == $b) {
302 if (file_exists($deldir . '/'. $fn)) {
303 unlink($d. '/'. $fn);
306 if (file_exists($d. '/'. $fn)) {
307 rename($d. '/'. $fn, $deldir .'/'. $fn);
316 * check mimetype against type
317 * - eg. img.is(#image#)
322 if (empty($this->mimetype)) {
325 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
329 * onUpload (singlely attached image to a table)
332 function onUploadWithTbl($tbl, $fld)
334 if ( $tbl->__table == 'Images') {
335 return; // not upload to self...
337 if (empty($_FILES['imageUpload']['tmp_name']) ||
338 empty($_FILES['imageUpload']['name']) ||
339 empty($_FILES['imageUpload']['type'])
344 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
346 $image = DB_DataObject::factory('Images');
347 $image->get($tbl->$fld);
348 $image->beforeDelete();
352 $image = DB_DataObject::factory('Images');
353 $image->onid = $tbl->id;
354 $image->ontable = $tbl->__table;
355 $image->filename = $_FILES['imageUpload']['name'];
356 $image->mimetype = $_FILES['imageUpload']['type'];
358 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
362 $tbl->$fld = $image->id;
369 function onUpload($roo, $table = false, $file = false)
372 if ($table !== false) {
373 $this->ontable = $table->tableName();
374 $this->onid = $table->pid();
377 if ($file === false) {
378 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
381 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
382 if (empty($file['tmp_name']) ||
383 empty($file['name']) ||
388 0=>"There is no error, the file uploaded with success",
389 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
390 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
391 3=>"The uploaded file was only partially uploaded",
392 4=>"No file was uploaded",
393 6=>"Missing a temporary folder"
395 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
396 $this->err = "Missing file details : Error=". $estr;
401 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
403 $this->beforeDelete();
405 if ( empty($this->ontable)) {
406 $this->err = "Missing ontable";
410 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
411 // then its an upload
412 $img = DB_DataObject::factory('Images');
413 $img->onid = $this->onid;
414 $img->ontable = $this->ontable;
415 $img->imgtype = $this->imgtype;
418 while ($img->fetch()) {
419 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
421 $img->beforeDelete();
429 require_once 'File/MimeType.php';
430 $y = new File_MimeType();
431 $this->mimetype = $file['type'];
432 if (in_array($this->mimetype, array(
434 'application/octet-stream',
435 'image/x-png', // WTF does this?
436 'image/pjpeg', // WTF does this?
437 'application/x-apple-msg-attachment', /// apple doing it's magic...
438 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
439 'application/csv-tab-delimited-table', // windows again!!?
440 ))) { // weird tyeps..
441 $inf = pathinfo($file['name']);
442 $this->mimetype = $y->fromExt($inf['extension']);
446 $ext = $y->toExt(trim((string) $this->mimetype ));
448 $this->filename = empty($this->filename) ?
449 $file['name'] : ($this->filename .'.'. $ext);
453 if (!$this->createFrom($file['tmp_name'])) {
454 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
464 * return a list of images for an object, optionally with a mime regex.
465 * eg. '%/pdf' or 'image/%'
469 * $i = DB_DataObject::factory('Images');
470 * $i->imgtype = 'LOGO';
471 * $ar = $i->gather($somedataobject, 'image/%');
473 * @param {DB_DataObject} dataobject = the object to gather data on.
474 * @param {String} mimelike LIKE query to use for search
477 function gather($obj, $mime_like='', $opts=array())
479 //DB_DataObject::debugLevel(1);
480 if (empty($obj->id)) {
485 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
488 if (!empty($mime_like)) {
489 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
491 $c->orderBy('created DESC');
493 return $c->fetchAll();
498 * set or get the dataobject this image is associated with
499 * @param DB_DataObject $obj An object to associate this image with
500 * (does not store it - you need to call update() to do that)
501 * @return DB_DataObject the dataobject this image is attached to.
503 function object($obj=false)
505 if ($obj === false) {
506 if (empty($this->ontable) || empty($this->onid)) {
509 $ret = DB_DataObject::factory($this->ontable);
510 $ret->get($this->onid);
515 $this->ontable = $obj->tableName();
516 $this->onid = $obj->id; /// assumes our nice standard of using ids..
521 function toRooArray($req)
524 $ret= $this->toArray();
527 $ff = HTML_FlexyFramework::get();
530 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
531 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
533 if (!empty($req['query']['imagesize'])) {
534 // query/imageBaseURL ... depricated...? -- set it in config?
536 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
538 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
540 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
542 if (!empty($req['query']['imagesize'])) {
543 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
548 $ret['shorten_name'] = $this->shorten_name();
554 * URL - create a url for the image.
555 * size - use -1 to show full size.
556 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
560 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
563 return 'about:blank';
565 if (!$this->exists()) {
566 return 'about:missing';
569 $shorten_name = $this->shorten_name();
571 $ff = HTML_FlexyFramework::get();
572 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
573 if (preg_match('#^http[s]*://#', $provider)) {
578 $provider = preg_replace('#/Thumb$#', '', $provider);
580 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
583 //$size = max(100, (int) $size);
584 //$size = min(1024, (int) $size);
585 // the size should 200x150 to convert
586 $sizear = preg_split('/(x|c)/', $size);
587 if(!isset($sizear[1])){
588 $sizear[1] = 0; // 0x with '0' is a box? why
591 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
593 $fc = $this->toFileConvert();
596 $mt = $this->mimetype;
597 if (!preg_match('#^image/#i',$mt)) {
601 $fc->convert($mt, $size);
603 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
607 * tries to get an image from then URL - not always has based... - also from the normal url
609 function getFromHashURL($url)
612 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
614 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
616 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
618 } else if (preg_match('#images[^/]+/([0-9]+)/#i', $url, $matches)) {
619 // supports images.xxxxx.com/{number}/name...
622 if ($id === false || $id < 1) {
626 $img = DB_DAtaObject::Factory('images');
627 if ($img->get($id)) {
634 function shorten_name()
636 if(empty($this->filename)) {
640 $filename = explode('.', $this->filename);
641 $ext = array_pop($filename);
642 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
644 if(strlen($name) > 32) {
645 $name = substr($name, 0, 32);
648 $shorten_name = "{$name}.{$ext}";
650 return $shorten_name;
653 * size could be 123x345
657 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
662 $sz = explode('x', $size);
665 if (!$this->id || empty($this->width)) {
667 $this->width = empty($sz[1]) ? $sx : $sz[1];
671 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
672 $sy = intval($ratio * $sx);
678 if (strlen($this->title)) {
679 $extra = ' title="'. htmlspecialchars($this->title) . '"';
682 return '<img src="' . $this->URL($size, $provider) . '"' .
684 ' width="'. $sx . '"' .
685 ' height="'. $sy . '">';
692 * #2142 [new] CMS - image link urls
697 function toLinkHTML($size, $provider = '/Images/Thumb')
699 if(empty($this->linkurl)){
700 return $this->toHTML($size, $provider = '/Images/Thumb');
703 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
709 * to Fileconvert object..
714 function toFileConvert()
716 $fn = $this->getStoreName();
718 require_once 'File/Convert.php';
719 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
726 require_once 'File/MimeType.php';
728 $y = new File_MimeType();
729 return $y->toExt($this->mimetype);
741 function setFromRoo($ar, $roo)
743 // not sure why we do this..
745 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
746 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
749 if ($this->find(true)) {
750 $roo->old = clone($this);
755 if (!empty($ar['_copy_from'])) {
757 if (!$this->checkPerm( 'A' , $roo->authUser)) {
758 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
761 $copy = DB_DataObject::factory('Images');
762 $copy->get($ar['_copy_from']);
763 $this->setFrom($copy->toArray());
765 $this->createFrom($copy->getStoreName());
767 $roo->addEvent("ADD", $this, $this->toEventString());
769 $r = DB_DataObject::factory($this->tableName());
775 $roo->jok($r->toRooArray($ar));
782 // FIXME - we should be checking perms here...
784 // this should be doign update
787 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
788 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
792 if (!isset($_FILES['imageUpload'])) {
793 return; // standard update...
797 // print_r(!$this->onUpload($this));
799 if ( !$this->onUpload($this)) {
800 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
803 $this->addEvent($ar, $roo);
805 $r = DB_DataObject::factory($this->tableName());
810 $roo->jok($r->toRooArray($ar));
814 function addEvent($ar, $roo)
816 $roo->addEvent("ADD", $this, $this->toEventString());
819 function toEventString()
822 //$p = DB_DataObject::factory($this->ontable);
824 // return "ERROR unknown table? {$this->ontable}";
828 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
829 //$p->toEventString();
832 function onUploadFromData($data, $roo)
835 $this->err = "Missing file details";
840 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
842 $this->beforeDelete();
845 if (empty($this->ontable)) {
846 $this->err = "Missing ontable";
850 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
851 // then its an upload
852 $img = DB_DataObject::factory('Images');
853 $img->onid = $this->onid;
854 $img->ontable = $this->ontable;
855 $img->imgtype = $this->imgtype;
858 while ($img->fetch()) {
859 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
861 $img->beforeDelete();
867 require_once 'File/MimeType.php';
868 $y = new File_MimeType();
870 if (in_array($this->mimetype, array(
872 'application/octet-stream',
873 'image/x-png', // WTF does this?
874 'image/pjpeg', // WTF does this?
875 'application/x-apple-msg-attachment', /// apple doing it's magic...
876 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
877 'application/csv-tab-delimited-table', // windows again!!?
878 ))) { // weird tyeps..
879 $inf = pathinfo($this->filename);
880 $this->mimetype = $y->fromExt($inf['extension']);
883 $ext = $y->toExt(trim((string) $this->mimetype ));
885 $explode_filename = explode('.', $this->filename);
886 if(array_pop($explode_filename) != $ext){
887 $this->filename = $this->filename .'.'. $ext;
890 if (!$this->createFromData($data)) {
898 function createFromData($data)
901 if (0 === strpos($data, "data:")) {
902 // data:image/png;base64,
903 $data = substr($data,5);
904 $bits = explode(";", $data);
905 $this->mimetype = $bits[0];
908 if (empty($this->filename)) {
909 require_once 'File/MimeType.php';
910 $y = new File_MimeType();
911 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
915 $this->mimetype = strtolower($this->mimetype);
916 if ($this->mimetype == 'image/jpg') {
917 $this->mimetype = 'image/jpeg';
921 $explode_mimetype = explode('/', $this->mimetype);
923 if (array_shift($explode_mimetype) == 'image') {
925 $imgs = @getimagesize('data://'. $data);
927 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
928 list($this->width , $this->height) = $imgs;
932 $this->created = date('Y-m-d H:i:s');
940 $f = $this->getStoreName();
942 if (!file_exists($dest)) {
943 $oldumask = umask(0);
944 mkdir($dest, 0775, true);
948 file_put_contents($f, file_get_contents("data://" . $data));
952 $this->filesize = filesize($f);
954 if($this->mimetype == 'application/pdf'){
955 $this->no_of_pages = $this->getPdfPages($f);
964 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
966 if(!preg_match('/^image\//', $this->mimetype)){
970 $file = $this->getStoreName();
972 if(!file_exists($file)){
976 $data = file_get_contents($file);
978 if(!empty($scaleWidth) || !empty($scaleHeight)){
979 $data = $this->scale(false, $scaleWidth, $scaleHeight);
983 $data = $this->rotate($data);
986 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
991 function getPdfPages($file)
993 require_once 'System.php';
997 $pdfinfo = System::which('pdfinfo');
999 if (!file_exists($file) || empty($pdfinfo)) {
1003 $cmd = "{$pdfinfo} {$file}";
1007 $info = explode("\n", $ret);
1009 foreach ($info as $i){
1011 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
1015 $page = (empty($matches[1])) ? 0 : $matches[1];
1021 function rotate($imageBlob = false)
1023 if(empty($imageBlob)){
1024 $imagick = new Imagick($this->getStoreName());
1026 $imagick = new Imagick();
1027 $imagick->readImageBlob($imageBlob);
1030 $orientation = $imagick->getImageOrientation();
1032 switch($orientation) {
1033 case Imagick::ORIENTATION_BOTTOMRIGHT:
1034 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
1037 case Imagick::ORIENTATION_RIGHTTOP:
1038 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
1041 case Imagick::ORIENTATION_LEFTBOTTOM:
1042 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
1046 return $imagick->getImageBlob();
1049 function scale($imageBlob = false, $width = 0, $height = 0)
1051 if(empty($imageBlob)){
1052 $imagick = new Imagick($this->getStoreName());
1054 $imagick = new Imagick();
1055 $imagick->readImageBlob($imageBlob);
1058 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1060 return $imagick->getImageBlob();