Esempio n. 1
1
function getCamera($id)
{
    $bdd = getBDD();
    $req = $bdd->query("SELECT * FROM at_cameras WHERE id = {$id}");
    $data = $req->fetch();
    if (!$data) {
        http_response_code(404);
        return;
    }
    saveImage($data);
    $path = __DIR__ . "/home/cameras/{$id}.png";
    if (file_exists($path)) {
        http_response_code(202);
        $img = fopen($path, 'rb');
        header("Content-Type: image/png");
        header("Content-Length: " . filesize($path));
        header("Timestamp: " . filemtime($path));
        header("Source: Atlantis");
        fpassthru($img);
    } else {
        http_response_code(404);
    }
}
function callImage()
{
    if (isset($_POST['addImg'])) {
        $info = getimagesize($_FILES['image']['tmp_name']);
        if ($info == FALSE) {
            //if(getimagesize($_FILES['image']['tmp_name']) == FALSE ){
            //$part = $_FILES['image']['tmp_name'];
            echo 'Vantar mynd';
        } else {
            echo ' Tad tokst ';
            $image = addslashes($_FILES['image']['tmp_name']);
            $name = addslashes($_FILES['image']['name']);
            $image = file_get_contents($image);
            $image = base64_encode($image);
            saveImage($name, $image);
        }
    } else {
        echo '';
    }
}
Esempio n. 3
0
function uploadImage()
{
    global $error;
    if (isset($_POST['submit'])) {
        $filename = $_FILES['image']['tmp_name'];
        if ($filename) {
            $check = getimagesize($_FILES['image']['tmp_name']);
            if ($check) {
                //Image can be no larger than 500 kb.
                if ($_FILES['image']['size'] < 500000) {
                    $image = addslashes($_FILES['image']['tmp_name']);
                    $name = addslashes($_FILES['image']['name']);
                    $image = file_get_contents($image);
                    $image = base64_encode($image);
                    saveImage($name, $image);
                } else {
                    $error = "<br>Pepe too large! Size:" . $_FILES['image']['size'];
                }
            }
        } else {
            $error = "<br>No pepe selected.";
        }
    }
}
Esempio n. 4
0
define("FIELD_DELIMITER", ",");
$recordsProcessed = 0;
//open input file
$fileHandle = fopen($inputFile, 'r');
$link = @mysqli_connect(Config::getDatabaseServer(), Config::getDatabaseUser(), Config::getDatabasePassword(), Config::getDatabase());
if (!$link) {
    mydie("Error connecting to Database \n" . "Error No:" . mysqli_connect_errno() . "\n Error = " . mysqli_connect_error() . "\n using database server = " . Config::getDatabaseServer() . "\n Database User = "******"\n Database Password = "******"\n Database = " . Config::getDatabase() . "\n");
}
while (!feof($fileHandle)) {
    $recordsProcessed++;
    //read a record and parse into array
    $line = fgets($fileHandle, 4096);
    $lineArray = split(FIELD_DELIMITER, $line);
    $teamName = $lineArray[0];
    $imageURL = $lineArray[1];
    $fullSavePath = saveImage($teamName, $imageURL);
    //echo $line;
}
fclose($fileHandle);
//close input file
$link->close();
//close database
exit;
/* Saved image will be in the following format
   [IMAGE_RAW_DIRECTORY]/[NormalizedteamName].[extension]
*/
function saveImage($teamName, $img)
{
    $normalizedTeamName = strtolower(str_replace(' ', '', $teamName));
    $fullSavePath = null;
    $baseName = basename($img);
Esempio n. 5
0
</div>



    <?php 
if (isset($_POST['insert_template'])) {
    if (insert_template($_POST['title'], $_POST['description'], $_FILES['image_preview']['name'], $_FILES['image_swatch']['name'], $_POST['price'])) {
        $title = '';
        $description = '';
        $image_preview = '';
        $image_swatch = '';
        $price = '';
        if (!saveImage('image_preview')) {
            $error = 'зображення велике не завантажиломь';
        }
        if (!saveImage('image_swatch')) {
            $error = 'зображення мале не завантажився';
        }
    } else {
        $error = "Помилка перехоплена {$sql}. " . mysqli_error($link);
    }
}
?>

    <div class="insert">
        <p class="error"><?php 
echo $error;
?>
</p>

        <form method="post"  enctype="multipart/form-data">
Esempio n. 6
0
/** 댓글 수정
 * @class write
 * @param
		$data: 댓글 data, 이미 check와 가공이 끝난 데이터여야 함
		$board_data: 게시판 설정 data
		-id: 게시판 아이디. 게시판 설정 data가 없을 때 아이디를 토대로 설정을 로드한다.
		-no: 대상 댓글번호 지정. (댓글 번호를 지정할 수 있다. 없다면 data에 저장되어 있는 자료를 수정)
		-is_update: 회원정보 업데이트 여부
		-is_ex: 이전정보 로드 여부
		-is_check: 입력변수 체크 여부
  */
function editCmt(&$data, $board_data = '', $param = '')
{
    global $mini;
    $param = param($param);
    iss($param['id']);
    iss($param['no']);
    iss($data['no']);
    def($param['is_update'], 1);
    def($param['is_ex'], 1);
    def($param['is_check'], 1);
    $trackback = $trackback_excerpt = $trackback_charset = '';
    if (!empty($data['trackback'])) {
        $trackback = $data['trackback'];
    }
    if (!empty($data['trackback_excerpt'])) {
        $trackback_excerpt = $data['trackback_excerpt'];
    }
    if (!empty($data['trackback_charset'])) {
        $trackback_charset = $data['trackback_charset'];
    }
    $is_saveImage = !empty($data['saveImage']) ? 1 : 0;
    unset($data['pass']);
    unset($data['target_member']);
    unset($data['report']);
    unset($data['ip']);
    unset($data['vote']);
    unset($data['hate']);
    unset($data['download']);
    unset($data['date']);
    unset($data['date_last']);
    unset($data['parent']);
    unset($data['history_vote']);
    unset($data['point_count']);
    unset($data['point_sum']);
    if (empty($mini['member']['level_admin'])) {
        unset($data['is_del']);
        unset($data['trackback']);
        unset($data['ment_advice']);
        unset($data['is_lock']);
        unset($data['admit_file']);
        unset($data['admit_post']);
    }
    //// 게시판 설정
    if (!is_array($board_data)) {
        if ($param['id']) {
            $board_data = getBoard($param['id'], 1);
        } else {
            __error('게시판 설정이 없습니다');
        }
    }
    //// 게시물 번호
    $no = $param['no'] ? $param['no'] : $data['no'];
    unset($data['no']);
    check($no, "type:num, name:댓글번호");
    //// 데이터 로드
    if ($param['is_ex']) {
        $data_ex = sql("SELECT * FROM {$board_data['table_cmt']} WHERE no={$no}");
        if (!is_array($data_ex)) {
            __error('해당 댓글이 존재하지 않습니다');
        }
    }
    //// 잠긴댓글
    if (empty($mini['member']['level_admin']) && !empty($data_ex['is_lock'])) {
        __error('댓글이 잠겨 있어 수정, 삭제를 할 수 없습니다');
    }
    //// 회원정보 로드
    if (!empty($data_ex['target_member'])) {
        $mdata = sql("SELECT * FROM {$mini['name']['member']} WHERE no={$data_ex['target_member']}");
        // 회원정보 업데이트 여부
        if ($param['is_update'] && $param['is_ex'] && $data_ex['target_member']) {
            if (is_array($mdata)) {
                parseMember($mdata);
                $data['name'] = $mdata['name'];
            } else {
                $data_ex['target_member'] = $data['target_member'] = 0;
                $data['pass'] = md5();
            }
        }
    }
    //// 권한 체크
    if (empty($data_ex['trackback'])) {
        if (!empty($data_ex['target_member'])) {
            if (empty($mini['log'])) {
                __error('권한이 없습니다. [로그인이 필요합니다]');
            }
            if (empty($mini['member']['level_admin']) && $mdata['no'] != $mini['member']['no']) {
                __error('권한이 없습니다. [자신이 쓴 댓글만 수정할 수 있습니다]');
            }
            if (!empty($mini['member']['level_admin']) && $mdata['no'] != $mini['member']['no'] && $mdata['level_admin'] >= $mini['member']['level_admin']) {
                __error('권한이 없습니다. [자신보다 높거나 같은 권한의 관리자가 쓴 댓글 입니다]');
            }
        } else {
            if (empty($mini['member']['level_admin'])) {
                if (empty($data['pass_encode'])) {
                    __error('비밀번호가 없습니다');
                }
                if (!empty($mini['log']) && empty($mini['member']['level_admin'])) {
                    __error('권한이 없습니다. [비회원이 쓴댓글 입니다]');
                }
                if (empty($mini['member']['level_admin']) && $data['pass_encode'] != md5("{$data_ex['pass']}|{$mini['ip']}|" . session_id())) {
                    __error("권한이 없습니다. [비밀번호가 일치하지 않습니다]");
                }
            }
        }
    }
    //// 추가필드 권한 체크
    if (!empty($board_data['field'])) {
        foreach ($board_data['field'] as $key => $val) {
            if (!empty($data['field'][$key]) && !empty($val['is_admin']) && empty($mini['member']['level_admin'])) {
                __error("[{$val['name']}]은 관리자만 입력하실 수 있습니다");
            }
            if (empty($data['field'][$key]) && !empty($val['is_req'])) {
                __error("[{$val['name']}]을 입력해 주세요");
            }
        }
    }
    //// 수정 시간제한
    if (!empty($board_data['limit_edit_comment']) && empty($mini['member']['level_admin'])) {
        if (!empty($data_ex) && strtotime($data_ex['date']) + $board_data['limit_edit_comment'] * 60 < $mini['time']) {
            __error("작성 후 {$board_data['limit_edit_comment']}분이 지난 댓글을 수정할 수 없습니다");
        }
    }
    //// 대상 게시물 정보 로드
    check($data['target_post'], "type:num, name:대상게시물번호");
    $data_post = sql("SELECT * FROM {$board_data['table']} WHERE no={$data['target_post']}");
    //// 답변 댓글일 때 원본 댓글 정보 로드
    if (!empty($data_ex['parent'])) {
        $data_reply = sql("SELECT * FROM {$board_data['table_cmt']} WHERE no=" . end(getStr($data_ex['parent'])));
        if (is_array($data_reply)) {
            // 원본 댓글이 비밀일 때 답변들도 비밀 유지
            if (!empty($data_reply['secret'])) {
                $data['secret'] = 1;
            }
            // 공지댓글에 댓글 금지
            if (!empty($data_reply['notice'])) {
                __error('공지댓글에는 댓글을 달 수 없습니다');
            }
        }
    }
    //// 입력정보 체크
    if (isset($data['name'])) {
        check($data['name'], "min:1, max:16, name:이름");
    }
    if (isset($data['mail'])) {
        check($data['mail'], "type:mail, name:메일, is_not:1");
    }
    //// 입력변수 체크
    if ($param['is_check']) {
        // 입력변수 체크
        checkField($data, $board_data['table_cmt'], $param);
        // 글 가공
        checkPost($data, $board_data, 'cmt');
    }
    //// 직접 수정이 안되는 정보는 제외시킨다
    unset($data['no']);
    unset($data['reply']);
    unset($data['pass']);
    unset($data['vote']);
    unset($data['hate']);
    unset($data['ip']);
    unset($data['date']);
    unset($data['target_member']);
    //// trackback
    if (!empty($param['trackback'])) {
        $data['trackback'] = $param['trackback'];
    }
    //+ 권한별로 제외하는 필드를 지정한다. (이를테면 target_member 같은거 바꿀 수 없으니깐)
    //// 쿼리
    sql("UPDATE {$board_data['table_cmt']} SET " . query($data, 'update') . " WHERE no={$no}");
    $data['no'] = $data_ex['no'];
    //// 검색어 수정
    if ($param['is_ex']) {
        if (!empty($data['ment']) && $data_ex['ment'] != $data['ment']) {
            $data_ex['ment'] = $data['ment'];
        }
        if (!empty($data['name']) && $data_ex['name'] != $data['name']) {
            $data_ex['name'] = $data['name'];
        }
        if (!empty($data['tag']) && $data_ex['tag'] != $data['tag']) {
            $data_ex['tag'] = $data['tag'];
        }
        delIndex($data_post['num'], $data_ex['no']);
        addIndex($data_ex, "\n\t\t\t\tid: {$board_data['no']}\n\t\t\t\tnum: {$data_post['num']}\n\t\t\t\tcmt_no: {$data_ex['no']}\n\t\t\t\tdate: {$data_ex['date']}\n\t\t\t\tip: {$data_ex['ip']}\n\t\t\t");
    }
    //// 트랙백 댓글 주소 설정
    if (!empty($data_reply) && !empty($data_reply['trackback'])) {
        $tmp_data = getSocket("\n\t\t\t\turl: {$data_reply['trackback']}\n\t\t\t\tskip_header: 1\n\t\t\t");
        if (!empty($tmp_data) && strpos($tmp_data, "<rdf:RDF") !== false) {
            preg_match("/\\<rdf\\:Description.+trackback\\:ping\\=\"([^\"]+)\" \\/\\>/is", $tmp_data, $mat);
            if (!empty($mat[1])) {
                $trackback = $mat[1];
            }
        }
    }
    //// 트랙백 보내기
    if (!empty($trackback)) {
        $result = '';
        $result = sendTrackback($trackback, $trackback_excerpt, $trackback_charset, $data, $board_data, 'cmt');
        if ($result) {
            __error("댓글 수정에 성공했지만 트랙백을 보내지 못했습니다. ({$result})");
        }
    }
    //// 이미지 치환
    if (!empty($is_saveImage) && !empty($data['ment'])) {
        $data['ment'] = saveImage($data_ex['no'], $data['ment'], $board_data, 'cmt');
        sql("UPDATE {$board_data['table_cmt']} SET ment='{$data['ment']}' WHERE no={$data_ex['no']}");
    }
}
Esempio n. 7
0
        $src = $fn();
        if ($src != "") {
            $download_file = download_file($src, $fname, $convert_path);
            if ($error == 1) {
                $error = 0;
                $src = "";
            }
        }
    }
    if ($src == "") {
        $error = 1;
        debuglog("  No art was found. Try the Tate Modern", "GETALBUMCOVER");
    }
}
if ($error == 0) {
    list($small_file, $big_file) = saveImage($fname, $in_collection, $stream);
}
// Now that we've attempted to retrieve an image, even if it failed,
// we need to edit the cached albums list so it doesn't get searched again
// and edit the URL so it points to the correct image if one was found
if ($in_collection) {
    // We only put small_file in the image db. The rest can be calculated from that.
    update_image_db($fname, $error, $small_file);
} else {
    if ($error == 0 && $stream != "") {
        update_stream_image($stream, $big_file);
    }
}
if ($download_file != "" && file_exists($download_file)) {
    debuglog("Removing downloaded file " . $download_file, "GETALBUMCOVER");
    unlink($download_file);
Esempio n. 8
0
 /**
  * Updates a event or stores a new one
  * 
  * @param array $p The $_POST superglobal
  * @return
  */
 public function updateEvent($p)
 {
     /*PREPARING DATA*/
     //handle date
     list($day, $month, $year) = split('[/.-]', $p['sortdate']);
     $date = $year . "-" . $month . "-" . $day;
     //handle tickets at door
     $ticketsatdoorValue = isset($p['ticketsatdoor']) ? TRUE : FALSE;
     //handle coverimage
     $filenameCoverimage = "";
     //if clause prevent execution if project was edited(id exists) and no new image was added (image is not empty)
     if (empty($p['id']) || $_FILES['coverimage']['name'] != '') {
         try {
             $filenameCoverimage = saveImage($_FILES['coverimage']);
         } catch (Exception $e) {
             //if an error occurred, output your custom error message
             die($e->getMessage());
         }
     }
     //handle image gallery
     $galleryimages = array();
     //1.Check if there were existing gallery images; add them to the galleryimages array
     if (!empty($p["existingGalleryImages"])) {
         foreach ($p["existingGalleryImages"] as $key => $value) {
             array_push($galleryimages, $value);
         }
     }
     //2.check if there are new gallery images, then loop through them and add them to the array
     if (!empty($_FILES['imagegallery']['name'][0])) {
         //loop through gallery images
         foreach ($_FILES["imagegallery"]["name"] as $key => $tmp_name) {
             try {
                 $filename = saveImage(array($_FILES['imagegallery']['name'][$key], $_FILES['imagegallery']['type'][$key], $_FILES['imagegallery']['tmp_name'][$key], $_FILES['imagegallery']['error'][$key], $_FILES['imagegallery']['size'][$key]));
             } catch (Exception $e) {
                 //if an error occurred, output your custom error message
                 die($e->getMessage());
             }
             //add filename to array
             array_push($galleryimages, $filename);
         }
     }
     //3.serialize arrayvalue into single string
     $galleryimagesSerialized = count($galleryimages) > 0 ? serialize($galleryimages) : "";
     /*UPLOADING DATA*/
     //if an id was passed, edit the existing entry
     if (!empty($p['id'])) {
         //the coverimage and gallery images are optional when editing events
         //that's why we append these fields to the sql query only if they have a new value
         $appendSQL = "";
         $appendSTMT = array();
         //check if new image was added, add some stuff to the query if it is
         if ($_FILES['coverimage']['name'] != '') {
             $appendSQL .= ", coverimage=?";
             $appendSTMT = array($filenameCoverimage);
         }
         //append galleryimages to the query (used to be conditional, that's why its seperated - T.
         $appendSQL .= ", galleryimages=?";
         array_push($appendSTMT, $galleryimagesSerialized);
         //prepare the sql query and append a part if we're adding images
         $sql = "UPDATE events SET title=?, tags=?, sortdate=?, hour=?, address=?, venue=?, venueurl=?, ticketsurl=?, ticketsatdoor=?, facebookurl=?, preview=?, body=?" . $appendSQL . " WHERE id=? LIMIT 1";
         if ($stmt = $this->db->prepare($sql)) {
             $A = array_merge(array_merge(array($p['title'], $p['tags'], $date, $p['hour'], $p['address'], $p['venue'], $p['venueurl'], $p['ticketsurl'], $ticketsatdoorValue, $p['facebookurl'], $p['event_preview'], $p['event_body']), $appendSTMT), array($p['id']));
             $stmt->execute($A);
             $stmt->closeCursor();
             //get the ID of the entry that was just edited
             $this->id = $p['id'];
         }
     } else {
         $sql = "INSERT INTO events (title, tags, sortdate, hour, address, venue, venueurl, ticketsurl, ticketsatdoor, facebookurl, coverimage, preview, body, galleryimages) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
         if ($stmt = $this->db->prepare($sql)) {
             $stmt->execute(array($p['title'], $p['tags'], $date, $p['hour'], $p['address'], $p['venue'], $p['venueurl'], $p['ticketsurl'], $ticketsatdoorValue, $p['facebookurl'], $filenameCoverimage, $p['event_preview'], $p['event_body'], $galleryimagesSerialized));
             $stmt->closeCursor();
             //get the ID of the entry that was just saved
             $id_obj = $this->db->query("SELECT LAST_INSERT_ID()");
             //gets unique ID generated for last entry into database
             $new_id = $id_obj->fetch();
             //pass data to the $id variable (array with the id in index [0])
             $id_obj->closeCursor();
             $this->id = $new_id[0];
         }
     }
     return $this->id;
 }
 public function f_image($params)
 {
     $res = saveImage($params["id"], $params["url"]);
     $this->logPerson($params, 2);
     return $res;
 }
Esempio n. 10
0
<?php

require_once '../../models/config.php';
require_once '../../models/class.php';
require_once '../../models/class-user.php';
$id = $_POST['id'];
saveImage($_POST['img'], $id);
function saveImage($base64img, $id)
{
    define('UPLOAD_DIR', '../../uploads/');
    $base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
    $data = base64_decode($base64img);
    $file = UPLOAD_DIR . 'thuphat.jpg';
    if (file_put_contents($file, $data)) {
        $user_obj = new user();
        if ($user_obj->updateUser('', '', '', '', '', '', '', 'thuphat1231ssssss111â.jpg', $id)) {
            echo "true";
        } else {
            echo "false";
        }
    } else {
        echo "false";
    }
}
Esempio n. 11
0
function uploadResizedImage($sourceImagePath, $destinationImagePath, $imageType)
{
    $resultSave = false;
    list($width, $height) = getimagesize($sourceImagePath);
    $maximumDimension = 200;
    if ($maximumDimension >= $width && $maximumDimension >= $height) {
        // with the process of creating, resampling and saving the image, the
        // animation of an animated gif is lost. In order to keep the possible
        // animation, if the image is smaller than the maximum size, it is
        // uploaded without any processing
        $resultSave = move_uploaded_file($sourceImagePath, $destinationImagePath);
    } else {
        // the function createImageFactory raises a fatal error when trying
        // to create an image larger than 3 MB
        $sourceImage = @createImageFactory($sourceImagePath, $imageType);
        if ($width > $height) {
            $newWidth = round($maximumDimension);
            $newHeight = round($height * ($newWidth / $width));
        } else {
            $newHeight = round($maximumDimension);
            $newWidth = round($width * ($newHeight / $height));
        }
        $destinationImage = createNewImage($newWidth, $newHeight, $imageType);
        // the function imagecopyresampled is much better than the function
        // imagecopyresized, which distorts the image when resizing
        $resultResize = imagecopyresampled($destinationImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        if ($resultResize) {
            $resultSave = saveImage($destinationImage, $destinationImagePath, $imageType);
        }
    }
    return $resultSave;
}
Esempio n. 12
0
function get_sql_update_values($form_id, $table_name, $object_name, $object_id, $user_id)
{
    $sql = "SELECT * FROM form_fields WHERE form_id='{$form_id}' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE'  ";
    $result = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $tmp = '';
        $comma = '';
        switch ($row['field_type']) {
            case "IMAGE":
                if ($_FILES[$row['field_id']]['name'] != '') {
                    //echo "Image:<b>***$table_name, $object_name, $object_id, $user_id</b>";
                    $file_name = saveImage($row['field_id']);
                    $_REQUEST[$row['field_id']] = $file_name;
                    // delete the old image
                    if ($object_id != '') {
                        deleteImage($table_name, $object_name, $object_id, $row[field_id]);
                    }
                    $str .= ", `" . $row['field_id'] . "` = '" . $file_name . "' ";
                }
                break;
            case "FILE":
                if ($_FILES[$row['field_id']]['name'] != '') {
                    $file_name = saveFile($row['field_id']);
                    $mime_type = $_FILES[$row['field_id']]['type'];
                    //$_REQUEST[$row[field_id]] = $file_name;
                    // delete the old image
                    if ($object_id != '') {
                        deleteFile($table_name, $object_name, $object_id, $row['field_id']);
                    }
                    //$str .= ", `".$row['field_id']."` = '".$file_name."' , `".$row[field_id]."9193` = '".$mime_type."'";
                    $str .= ", `" . $row['field_id'] . "` = '" . $file_name . "' ";
                }
                break;
            case "DATE":
                $day = $_REQUEST[$row['field_id'] . "d"];
                $month = $_REQUEST[$row['field_id'] . "m"];
                $year = $_REQUEST[$row['field_id'] . "y"];
                $_REQUEST[$row['field_id']] = $year . "-" . $month . "-" . $day;
                $str .= ", `" . $row['field_id'] . "` = '" . $_REQUEST[$row['field_id']] . "' ";
                break;
            case "DATE_CAL":
                $temp_time = strtotime($_REQUEST[$row['field_id']] . " GMT");
                $day = date('d', $temp_time);
                $month = date('m', $temp_time);
                $year = date('y', $temp_time);
                $str .= ", `" . $row['field_id'] . "` = '" . $year . "-" . $month . "-" . $day . "' ";
                break;
            case "CHECK":
                $selected_codes = array();
                $selected_codes = $_REQUEST[$row['field_id']];
                // the field comes in as an array
                for ($i = 0; $i < sizeof($selected_codes); $i++) {
                    if ($i > 0) {
                        $comma = ',';
                    }
                    $tmp .= $comma . $selected_codes[$i] . "";
                }
                $_REQUEST[$row['field_id']] = $tmp;
                $str .= ", `" . $row['field_id'] . "` = '" . $_REQUEST[$row['field_id']] . "' ";
                break;
            case "MSELECT":
                $selected_codes = array();
                $selected_codes = $_REQUEST[$row['field_id']];
                // the field comes in as an array
                for ($i = 0; $i < sizeof($selected_codes); $i++) {
                    if ($i > 0) {
                        $comma = ',';
                    }
                    $tmp .= $comma . $selected_codes[$i] . "";
                }
                $_REQUEST[$row['field_id']] = $tmp;
                $str .= ", `" . $row['field_id'] . "` = '" . $_REQUEST[$row['field_id']] . "' ";
                break;
            case "SKILL_MATRIX":
                save_skill_matrix_data($row['field_id'], $object_id, $user_id);
                $str .= ", `" . $row['field_id'] . "` = '" . $_REQUEST[$row['field_id']] . "' ";
                break;
            case "TEXT":
                $str .= ", `" . $row['field_id'] . "` = '" . html_entity_decode($_REQUEST[$row['field_id']]) . "' ";
                break;
            default:
                $str .= ", `" . $row['field_id'] . "` = '" . $_REQUEST[$row['field_id']] . "' ";
                break;
        }
    }
    //echo "$str<br>";
    return $str;
}
Esempio n. 13
0
require_once __DIR__ . '/../classes/connexion.php';
require_once __DIR__ . '/../classes/Settings.php';
$settings = new Settings();
$photos_number = $settings->getSettings('Security', 'photosNumber');
$photos_interval = $settings->getSettings('Security', 'photosSeconds');
$cameras = array();
$bdd = getBDD();
$req = $bdd->query('SELECT * FROM at_cameras');
while ($data = $req->fetch()) {
    $cameras[] = array('id' => $data['id'], 'ip' => $data['ip'], 'image' => $data['image'], 'username' => $data['username'], 'password' => $data['password']);
}
$size = count($cameras);
for ($i = 0; $i < $photos_number; $i++) {
    for ($j = 0; $j < $size; $j++) {
        saveImage($cameras[$j]);
    }
    sleep($photos_interval);
}
function saveImage($arr)
{
    if (isset($arr['ip'], $arr['image'])) {
        $url = 'http://' . $arr['ip'] . '/' . $arr['image'];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        if (isset($arr['username'], $arr['password'])) {
            $username = $arr['username'];
            $password = $arr['password'];
            curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
Esempio n. 14
0
function createThum($image_dic, $image_file_name, $width, $height)
{
    print "Creating Thum<br>";
    $image = loadImage($image_dic . $image_file_name);
    print "Creating Thum<br>";
    $thum = createImageTrueColor($width, $height);
    print "Creating Thum<br>";
    $source_imagex = imagesx($image);
    $source_imagey = imagesy($image);
    imagecopyresized($thum, $image, 0, 0, 0, 0, $width, $height, $source_imagex, $source_imagey);
    print "Creating Thum<br>";
    saveImage($thum, $image_dic . "thum_" . $image_file_name);
    print "Creating Thum<br>";
    return $image_dic . "thum_" . $image_file_name;
}
Esempio n. 15
0
 if ($item['sender'] != $config['username']) {
     //if not sent from yourself
     if (!is_banned($item['sender'])) {
         $snapchat->addFriend($item['sender']);
         //add sender as friend if not already
         if ($item['media_type'] == 0) {
             //if still image
             if ($config['picturesallowed']) {
                 $data = $snapchat->getMedia($item['id']);
                 //get received snap
                 if ($data != "") {
                     if ($config['moderation'] == false) {
                         postManualImage($data, $item['sender']);
                         saveImage($data, $item['sender'], $item['id'], 1);
                     } else {
                         saveImage($data, $item['sender'], $item['id'], 0);
                         $snapchat->sendMessage($item['sender'], "Your submission has been received! Please be patient while moderators review it.");
                     }
                 }
             }
         } elseif ($item['media_type'] == 1) {
             //if moving video
             if ($config['videosallowed']) {
                 $data = $snapchat->getMedia($item['id']);
                 //get received snap
                 if ($data != "") {
                     if ($config['moderation'] == false) {
                         postManualVideo($data, $item['sender']);
                         saveVideo($data, $item['sender'], $item['id'], 1);
                     } else {
                         saveVideo($data, $item['sender'], $item['id'], 0);
Esempio n. 16
0
    $saveto = $dir . '/' . array_pop(explode('/', $url));
    if (file_exists($saveto)) {
        unlink($saveto);
    }
    $fp = fopen($saveto, 'x');
    fwrite($fp, $raw);
    fclose($fp);
}
if (isset($argv[1]) && isset($argv[2]) && is_int(intval($argv[2]))) {
    require_once "reddit.php";
    $reddit = new reddit('basic');
    $count = 0;
    $params = array('limit' => 50);
    while ($count < $argv[2]) {
        $response = $reddit->getListing($argv[1], $params);
        if (is_array($response->data->children)) {
            foreach ($response->data->children as $link) {
                $url = $link->data->url;
                if (preg_match('/\\.(jpg|jpeg|png|gif)(?:[\\?\\#].*)?$/i', $url) === 1) {
                    saveImage($url);
                    ++$count;
                }
                $params['after'] = $link->data->name;
            }
        } else {
            echo "Something didn't work.\n";
        }
    }
} else {
    echo "Usage: php reddit_imgs.php SUBREDDIT NUMBER_OF_IMAGES\n";
}
Esempio n. 17
0
     save_batchupload();
     break;
 case 'upload':
     uploadImage($option);
     break;
 case 'save_upload':
     saveUploadedImage($option);
     break;
 case 'edit':
     editImage($option, $cid[0]);
     break;
 case 'editA':
     editImage($option, $id);
     break;
 case 'save':
     saveImage($option);
     break;
 case 'remove':
     removeImages($cid, $option);
     break;
 case 'publish':
     publishImages($cid, 1, $option);
     break;
 case 'unpublish':
     publishImages($cid, 0, $option);
     break;
 case 'approve':
     break;
 case 'cancel':
     cancelImage($option);
     break;
Esempio n. 18
0
flush();
session_write_close(); */
//fastcgi_finish_request();
ignore_user_abort(true);
//exit();
$cfg['menu'] = 'config';
$action = getpost('action');
$flag = (int) getpost('flag');
if (PHP_SAPI == 'cli') {
    cliUpdate();
} elseif ($action == 'update') {
    update();
} elseif ($action == 'imageUpdate') {
    imageUpdate($flag);
} elseif ($action == 'saveImage') {
    saveImage($flag);
} elseif ($action == 'selectImageUpload') {
    selectImageUpload($flag);
} elseif ($action == 'imageUpload') {
    imageUpload($flag);
} else {
    message(__FILE__, __LINE__, 'error', '[b]Unsupported input value for[/b][br]action');
}
exit;
//  +------------------------------------------------------------------------+
//  | Update                                                                 |
//  +------------------------------------------------------------------------+
function update()
{
    global $cfg, $db, $lastGenre_id, $getID3, $dirsCounter, $filesCounter, $curFilesCounter, $curDirsCounter;
    authenticate('access_admin', false, true);
Esempio n. 19
0
<?php

require_once "functions/functions.php";
if (isset($_POST['url']) && isset($_POST['message'])) {
    echo saveImage($_POST['url'], $_POST['message']);
}
?>



Esempio n. 20
0
function parseRecipe($html, $url)
{
    $parsedRecipe = RecipeParser::parse($html, $url);
    $recipe = new Recipe();
    $recipe->RecipeName = $parsedRecipe->title;
    $recipe->ServingCount = getNumberFromString($parsedRecipe->yield);
    $recipe->PrepTimeMinute = $parsedRecipe->time['prep'];
    $recipe->CookTimeMinute = $parsedRecipe->time['cook'];
    $recipe->RecipeNote = $parsedRecipe->url;
    $directions = '';
    foreach ($parsedRecipe->instructions[0]['list'] as $key => $n) {
        if ($directions != '') {
            $directions .= "\n\n";
        }
        $directions .= $parsedRecipe->instructions[0]['list'][$key];
    }
    $recipe->Directions = $directions;
    $recipe->save();
    foreach ($parsedRecipe->ingredients[0]['list'] as $key => $n) {
        $ingredient = new RecipeIngredient();
        $ingredient->RecipeId = $recipe->RecipeId;
        $origText = $parsedRecipe->ingredients[0]['list'][$key];
        try {
            $text = trim($origText);
            preg_match('~[a-z]~i', $text, $match, PREG_OFFSET_CAPTURE);
            $count = substr($text, 0, $match[0][1]);
            $countEncode = urlencode($count);
            $countEncode = str_replace("%C2%BC", " 1/4", $countEncode);
            $countEncode = str_replace("%C2%BD", " 1/2", $countEncode);
            $countEncode = str_replace("%C2%BE", " 3/4", $countEncode);
            $count = urldecode($countEncode);
            $count = str_replace("-", " ", $count);
            $count = fractionToDecimal($count);
            $text = trim(substr($text, $match[0][1]));
            $size = getItemSize(substr($text, 0, strpos($text, " ")));
            if (!isNullOrEmptyString($size)) {
                $text = trim(substr($text, strpos($text, " ")));
            }
            $ingredient->ItemCount = $count;
            $ingredient->ItemSize = $size;
            $ingredient->RecipeIngredientName = $text;
            //$ingredient->RecipeIngredientNote = $origText;
        } catch (Exception $e) {
            $ingredient->RecipeIngredientName = $origText;
            $ingredient->RecipeIngredientNote = $e->getMessage();
        }
        // save the Tag on the Post
        $recipe->ingredients()->save($ingredient);
    }
    if (!isNullOrEmptyString($parsedRecipe->photo_url)) {
        saveImage($recipe, $parsedRecipe->photo_url);
    }
    return $recipe;
}
Esempio n. 21
0
    if ($user_exist) {
        $image = $db_login->value_for_id("users", "image", "phone", $user_phone);
        if ($image) {
            $imagePath = substr($image, strlen(Config::$web_host) + 1);
            file_put_contents("imageUpload.txt", $imagePath);
            $result = @unlink($imagePath);
        }
        $imageData = hex2bin($image_data);
        $imagePath = "./images/" . $image_name;
        file_put_contents($imagePath, $imageData);
        $web_host = Config::$web_host;
        $image_name = "{$web_host}/images/" . $image_name;
        $sql = "update users set image='{$image_name}' where phone='{$user_phone}'";
        $db_login->query($sql);
        $data['data'] = "Hello";
        $data['result'] = 200;
        $data['msg'] = '图片保存成功!';
    } else {
        //echo $image;
        $data['data'] = "Hello";
        $data['result'] = 201;
        $data['msg'] = '图片保存失败!';
    }
    return json_encode($data);
}
$params = array();
$params["userPhone"] = $_POST["userPhone"];
$params["imageName"] = $_POST["imageName"];
$params["imageData"] = $_POST["imageData"];
exit(saveImage($params));
Esempio n. 22
0
function createThumbnail($source, $destination, $newwidth, $newheight, $action = 'strict', $type = 2)
{
    $img = $out = loadImage($source, $type);
    $ims = getimagesize($source);
    $width = $ims[0];
    $height = $ims[1];
    $width_rate = $newwidth / $width;
    $height_rate = $newheight / $height;
    switch ($action) {
        case 'max':
            if ($width_rate > $height_rate) {
                $newwidth_prop = $width * $height_rate;
                $newheight_prop = $newheight;
            } else {
                $newwidth_prop = $newwidth;
                $newheight_prop = $height * $width_rate;
            }
            if ($newwidth_prop > $width || $newheight_prop > $height) {
                return false;
            }
            $out = imagecreatetruecolor($newwidth_prop, $newheight_prop);
            imagecopyresampled($out, $img, 0, 0, 0, 0, $newwidth_prop, $newheight_prop, $width, $height);
            break;
        case 'maxsize':
            if ($width_rate > $height_rate) {
                $newwidth_prop = $width * $height_rate;
                $newheight_prop = $newheight;
            } else {
                $newwidth_prop = $newwidth;
                $newheight_prop = $height * $width_rate;
            }
            $newwidth_prop = $newwidth_prop > $width ? $width : $newwidth_prop;
            $newheight_prop = $newheight_prop > $height ? $height : $newheight_prop;
            $dst_x = $newwidth / 2 - $newwidth_prop / 2;
            $dst_y = $newheight / 2 - $newheight_prop / 2;
            $out = imagecreatetruecolor($newwidth, $newheight);
            $background = imagecolorallocate($out, 255, 255, 255);
            imagefilledrectangle($out, 0, 0, $newwidth, $newheight, $background);
            imagecopyresampled($out, $img, $dst_x, $dst_y, 0, 0, $newwidth_prop, $newheight_prop, $width, $height);
            break;
        case 'crop':
            if ($newwidth > $width && $newheight > $height) {
                return false;
            }
            if ($width_rate > $height_rate) {
                $newwidth_prop_crop = $newwidth;
                $newheight_prop_crop = $height * $width_rate;
                $src_x = 0;
                $src_y = ($height - $newheight / $newheight_prop_crop * $height) / 2;
            } else {
                $newwidth_prop_crop = $width * $height_rate;
                $newheight_prop_crop = $newheight;
                $src_x = ($width - $newwidth / $newwidth_prop_crop * $width) / 2;
                $src_y = 0;
            }
            $out = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($out, $img, 0, 0, $src_x, $src_y, $newwidth_prop_crop, $newheight_prop_crop, $width, $height);
            break;
        case 'exact':
        case 'strict':
            if ($newwidth > $width || $newheight > $height) {
                return false;
            }
            $out = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($out, $img, 0, 0, 0, 0, $newheight, $newwidth, $width, $height);
            break;
    }
    saveImage($out, $destination, $type);
    imagedestroy($img);
    return true;
}
$username = $data->userName;
$password = $data->password;
$cpassword = $data->cpassword;
$email = $data->email;
$contactno = $data->contactno;
$country = $data->country->displayName;
$state = $data->state->displayName;
$city = $data->city->displayName;
$fileImg = $data->file;
$path = $data->path;
$time = time();
$dataFileVal = array();
function saveImage($base64img)
{
    global $fileImg, $time, $dataFileVal;
    define('UPLOAD_DIR', '/mnt/backup/home/ssipolya/public_html/Angular Js/programs/curdByShivangi/img/');
    // $base64img = str_replace('data:image/png;base64,', '', $base64img);
    foreach ($fileImg as $fileImg1) {
        $dataPath[] = $base64img;
        $dataFile = $time . '_' . $fileImg1;
        $dataFileVal[] = $dataFile;
        $file = UPLOAD_DIR . $dataFile;
        file_put_contents($file, $data);
    }
    //print_r($dataFileVal);
}
saveImage($path);
$ImgVal = implode(',', $dataFileVal);
// $image=$data->image;
$sql = "insert into forPracticalNg (name, username, password, cpassword,email,contactno, country,state,city, image) values('" . $name . "','" . $username . "','" . $password . "','" . $cpassword . "','" . $email . "','" . $contactno . "','" . $country . "','" . $state . "','" . $city . "','" . $ImgVal . "')";
$qry_res = mysql_query($sql, $conn);
    echo 'rand fn ';
    $file = UPLOAD_DIR . $img_url_name;
    echo 'full url';
    if (file_put_contents($file, $data)) {
        echo 'put contents in server ';
        $conn = db_conn();
        if ($conn != false) {
            echo '3rd if ';
            //echo 'connection success';
            $query = "UPDATE `video` SET `thumbnail_img`='{$img_url_name}' WHERE `id`='{$vid_id}'";
            echo 'Query ';
            $stmnt = $conn->prepare($query);
            echo 'Query prepare';
            if ($stmnt->execute()) {
                echo 'Query execute';
                echo 'updated';
            } else {
                echo 'sql error';
            }
        } else {
            echo 'conn error';
        }
    }
}
saveImage($base);
echo 'save img called ';
//$base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
//$dir="thumbnail/54.jpg";
//echo $base64img;
// file_put_contents($dir, $binary);
// echo 'done';
Esempio n. 25
0
<?php

function saveImage($base64img)
{
    define('UPLOAD_DIR', 'thumbnail/');
    $base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
    $data = base64_decode($base64img);
    $file = UPLOAD_DIR . '123123123.jpg';
    file_put_contents($file, $data);
}
saveImage('data:image/jpeg;base64,
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');
Esempio n. 26
0
function check_album_image()
{
    // This archives stuff with getRemoteImage, which will mostly come from the
    // last.FM importer
    global $album, $albumartist, $error, $download_file, $convert_path, $image;
    $imagekey = md5($albumartist . " " . $album);
    if (preg_match('#^getRemoteImage\\.php#', $image) && !file_exists('albumart/small/' . $imagekey . '.jpg')) {
        $u = get_base_url();
        $u = preg_replace('#backends/sql#', '', $u);
        $convert_path = find_executable('convert');
        $download_file = download_file($u . $image, $imagekey, $convert_path);
        if ($error !== 1) {
            list($image, $a) = saveImage($imagekey, true, "");
        }
    }
}
Esempio n. 27
0
 function update_quiz_guide()
 {
     $quiz_guide_id = $this->uri->segment(4);
     if (isset($quiz_guide_id)) {
         $data['first_aid_details'] = $this->admin_model->get('tbl_quiz_guide', '*', array('id' => $quiz_guide_id));
         $data['course'] = $this->admin_model->get('tbl_course', '*');
         $data['quiz_list'] = $this->admin_model->quize_quide_details();
         $this->load->view('admin/update_quiz_guide', $data);
     }
     if (isset($_POST['update_guide'])) {
         unset($_POST['update_guide']);
         $guide_id = $this->uri->segment(4);
         $_POST['image'] = saveImage('guide_image', 'image_name');
         if (!empty($_POST['image'])) {
             $affected_rows = $this->admin_model->update('tbl_quiz_guide', $_POST, array('id' => $guide_id));
         } else {
             unset($_POST['image']);
             $affected_rows = $this->admin_model->update('tbl_quiz_guide', $_POST, array('id' => $guide_id));
         }
         if ($affected_rows > 0) {
             $this->session->set_flashdata('green_message', 'Updated successfully!');
         } else {
             $this->session->set_flashdata('red_message', 'Not Updated successfully!');
         }
         redirect('admin/user/quiz_guide');
     }
 }
Esempio n. 28
0
 /**
  * Updates a blogpost or stores a new one
  * 
  * @param array $p The $_POST superglobal
  * @return
  */
 public function updateBlogpost($p)
 {
     /*PREP DATA*/
     //handle date
     list($day, $month, $year) = split('[/.-]', $p['sortdate']);
     $date = $year . "-" . $month . "-" . $day;
     //handle coverimage
     $filename = "";
     //if clause prevent execution if no new image was added (image is not empty)
     if ($_FILES['coverimage']['name'] != '') {
         try {
             $filename = saveImage($_FILES['coverimage']);
         } catch (Exception $e) {
             //if an error occurred, output your custom error message
             die($e->getMessage());
         }
     }
     /*UPLOADING DATA*/
     //if an id was passed, edit the existing entry
     if (!empty($p['id'])) {
         $appendSQL = "";
         $appendSTMT = array();
         //check if new image was added, or if an image was deleted, and add some stuff to the query if it is
         if ($_FILES['coverimage']['name'] != '' || $p['existingCoverImage'] == "true") {
             $appendSQL .= ", coverimage=?";
             $appendSTMT = $p['existingCoverImage'] == "true" ? array("") : array($filename);
             //if we deleted the image, replace image path by empty string
         }
         //prepare the sql query and append a part if we're adding images
         $sql = "UPDATE blogposts SET title=?, tags=?, sortdate=?, youtubecover=?, body=?" . $appendSQL . " WHERE id=? LIMIT 1";
         if ($stmt = $this->db->prepare($sql)) {
             $A = array_merge(array_merge(array($p['title'], $p['tags'], $date, $p['youtubecover'], $p['body']), $appendSTMT), array($p['id']));
             $stmt->execute($A);
             $stmt->closeCursor();
             //get the ID of the entry that was just edited
             $this->id = $p['id'];
         }
     } else {
         $sql = "INSERT INTO blogposts (title, tags, sortdate, coverimage, youtubecover, body) VALUES (?, ?, ?, ?, ?, ?)";
         if ($stmt = $this->db->prepare($sql)) {
             $stmt->execute(array($p['title'], $p['tags'], $date, $filename, $p['youtubecover'], $p['body']));
             $stmt->closeCursor();
             //get the ID of the entry that was just saved
             $id_obj = $this->db->query("SELECT LAST_INSERT_ID()");
             //gets unique ID generated for last entry into database
             $new_id = $id_obj->fetch();
             //pass data to the $id variable (array with the id in index [0])
             $id_obj->closeCursor();
             $this->id = $new_id[0];
         }
     }
     return $this->id;
 }
Esempio n. 29
0
        }
    }
    closedir($handle);
}
require_once __DIR__ . '/protected/config/config.php';
if (!isset($_POST['password']) || $_POST['password'] !== PASSKEY) {
    die("error,e-401");
}
if (!(filesize($_FILES['file']['tmp_name']) && $_FILES['file']['type'] == "image/png" || $_FILES['file']['type'] == "image/jpeg" || $_FILES['file']['type'] == "image/gif" || $_FILES['file']['type'] == "video/mp4" || $_FILES['file']['type'] == "video/webm")) {
    die("error,e-418");
}
if ($_FILES['file']['error'] > 0) {
    die("error,e-503");
}
$dir = __DIR__ . '/i/';
saveImage($_FILES['file']['type'], $_FILES['file']['tmp_name']);
function generateNewHash($type)
{
    $an = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    $str = "";
    for ($i = 0; $i < 8; $i++) {
        $str .= substr($an, rand(0, strlen($an) - 1), 1);
    }
    if (!file_exists(__DIR__ . "/images/{$str}")) {
        return $str;
    } else {
        return generateNewHash($type);
    }
}
function saveImage($mimeType, $tempName)
{
Esempio n. 30
0
            echo "<div class='error_msg'>Please Enter Valid Other Email. You Entered {$_POST['other_email']}</div>";
        }
        if ($urlValidate == true) {
            echo "<div class='error_msg'>Please Enter Valid URL using \"http://www.\" format. You Entered: {$_POST['website']}</div>";
        }
    } else {
        //set $_POST data variables
        $firstName = $_POST['first_name'];
        $lastName = $_POST['last_name'];
        $phoneNum = $_POST['phone'];
        $primEmail = $_POST['prim_email'];
        $otherEmail = $_POST['other_email'];
        $otherEmail = $_POST['other_email'];
        $website = $_POST['website'];
        $notes = $_POST['comments'];
        $image = saveImage();
        //insert binded data collected from form into database
        $stmt = $dbh->prepare("insert into contacts(firstname, lastname, contactPhone, contactEmail, altEmail, contactWebsite, contactImage, contactNotes) values(:firstname, :lastname, :phone, :email, :altEmail, :website, :image, :notes)");
        $stmt->bindParam(':firstname', $firstName);
        $stmt->bindParam(':lastname', $lastName);
        $stmt->bindParam(':phone', $phoneNum);
        $stmt->bindParam(':email', $primEmail);
        $stmt->bindParam(':altEmail', $otherEmail);
        $stmt->bindParam(':website', $website);
        $stmt->bindParam(':notes', $notes);
        $stmt->bindParam(':image', $image);
        $stmt->execute();
    }
}
//end logic
?>