/**
  * GIF/JPEG/PNG のみ対象
  * @param String $filepath
  * @return bool
  */
 function isValidImageFile($filepath)
 {
     try {
         // WARNING, NOTICE が発生する可能性有り
         $img_info = getimagesize($filepath);
         switch ($img_info[2]) {
             case IMAGETYPE_GIF:
             case IMAGETYPE_JPEG:
             case IMAGETYPE_PNG:
                 // getimagesize関数はマジックバイトを見ているだけ
                 // イメージリソースが生成できるかどうかでファイルの中身を判定する。
                 // データに問題がある場合、WARNING が発生する可能性有り
                 if (imagecreatefromstring(file_get_contents($filepath)) !== false) {
                     return true;
                 }
         }
     } catch (\ErrorException $e) {
         $err_msg = sprintf("%s(%d): %s (%d) filepath = %s", __METHOD__, $e->getLine(), $e->getMessage(), $e->getCode(), $filepath);
         switch ($e->getSeverity()) {
             case E_WARNING:
                 \Log::warning($err_msg);
                 break;
             case E_NOTICE:
                 \Log::notice($err_msg);
                 break;
             default:
                 \Log::error($err_msg);
         }
     }
     return false;
 }
 public function LogAction()
 {
     Log::fatal('something');
     Log::warn('something');
     Log::notice('something');
     Log::debug('something');
     Log::sql('something');
     echo '请到Log文件夹查看效果。如果是SAE环境,可以在日志中心的DEBUG日志查看。';
 }
Example #3
0
 function createMedium($url, $filename, $width, $height)
 {
     # Function creates a smaller version of a photo when its size is bigger than a preset size
     # Excepts the following:
     # (string) $url = Path to the photo-file
     # (string) $filename = Name of the photo-file
     # (int) $width = Width of the photo
     # (int) $height = Height of the photo
     # Returns the following
     # (boolean) true = Success
     # (boolean) false = Failure
     # Set to true when creation of medium-photo failed
     global $settings;
     $error = false;
     # Size of the medium-photo
     # When changing these values,
     # also change the size detection in the front-end
     global $newWidth;
     global $newHeight;
     # Check permissions
     if (hasPermissions(LYCHEE_UPLOADS_MEDIUM) === false) {
         # Permissions are missing
         $error = true;
         echo 'Not enough persmission on the medium folder' . "\n";
     }
     # Is photo big enough?
     # Is Imagick installed and activated?
     if ($error === false && ($width > $newWidth || $height > $newHeight) && (extension_loaded('imagick') && $settings['imagick'] === '1')) {
         $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename;
         # Read image
         $medium = new Imagick();
         $medium->readImage(LYCHEE . $url);
         # Adjust image
         $medium->scaleImage($newWidth, $newHeight, true);
         # Save image
         try {
             $medium->writeImage($newUrl);
         } catch (ImagickException $err) {
             Log::notice($database, __METHOD__, __LINE__, 'Could not save medium-photo: ' . $err->getMessage());
             $error = true;
             echo 'Imagick Exception:' . "\n";
             var_dump($e);
         }
         $medium->clear();
         $medium->destroy();
     } else {
         # Photo too small or
         # Imagick not installed
         $error = true;
     }
     if ($error === true) {
         return false;
     }
     return true;
 }
 public function discard($days)
 {
     $discardedEventCount = ProcessorEventMatchstate::discardOld($this->tDbh, $days);
     Log::notice(sprintf("%u old event(s) discarded", $discardedEventCount));
     QueryLoghost::discardUnused($this->tDbh);
     QueryUser::discardUnused($this->tDbh);
     QueryHostipNetwork::discardUnused($this->tDbh);
     QueryHostip::discardUnused($this->tDbh);
     QueryHostmac::discardUnused($this->tDbh);
     QueryService::discardUnused($this->tDbh);
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param StoreBoardsRequest|Request $request
  * @return \Illuminate\Http\Response
  */
 public function store(StoreBoardsRequest $request)
 {
     $input = $request->all();
     if ($input['type']['board'] == true) {
         $this->boards->createNewBoard($request);
     } else {
         $this->categories->createNewCategory($request);
     }
     \Log::notice(\Auth::user()->name . ' created a new board with the name of ' . $input['name']);
     \Session::flash("flash_success", "The Forum has been created.");
     return response()->json(['result' => 'Success']);
 }
 /** @inheritdoc */
 public function __construct(Request $request)
 {
     //  require auth'd users
     $this->middleware('auth');
     if (\Auth::guest() && null !== ($_subGuid = $request->input('submissionGuid'))) {
         //  Make sure the request is from hubspot...
         if (false !== stripos($_ref = $request->get('http-referrer'), 'info.dreamfactory.com')) {
             \Log::notice('bogus referrer on inbound from landing page: ' . $_ref);
         }
         $this->autoLoginRegistrant($_subGuid, $request->input('pem'));
     }
 }
 /**
  * 受け取ったイベントをTrelloのリストにログする
  *
  * @param  MonitorableInterface  $event
  * @return void
  */
 public function handle(MonitorBaseEvent $event)
 {
     // サイト状態リスト上のカードを取得
     $url = 'https://trello.com/1/lists/' . env('TRELLO_SITES_STATUS_LIST') . '/cards' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN');
     if (false === ($result = $this->getter->get($url))) {
         \Log::notice('TrelloからWebサイト監視リストの情報が取得できませんでした。');
         return;
     }
     $cards = $this->converter->convert($result);
     foreach ($cards as $card) {
         if ($card['name'] === $event->url) {
             $updateCard = $card;
             break;
         }
     }
     if (isset($updateCard)) {
         // 既存ラベル色取得、緑と赤は削除
         $labels = array_diff(array_column($updateCard['labels'], 'color'), ['green', 'red']);
         $labelString = implode(',', $labels);
         // 既存カード更新
         if ($event instanceof SiteUpped) {
             // サイト復活時
             // ラベル色緑設定
             $url = 'https://trello.com/1/cards/' . $updateCard['id'] . '/labels' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . trim($labelString . ',green', ',');
             $result = $this->putter->put($url);
             // 説明文からダウン時間情報削除
             $url = 'https://trello.com/1/cards/' . $updateCard['id'] . '/desc' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . urlencode(trim(preg_replace('/<.+より停止中 >/u', '', $updateCard['desc'])));
             $result = $this->putter->put($url);
         } else {
             // サイトダウン時
             // ラベル色赤設定
             $url = 'https://trello.com/1/cards/' . $updateCard['id'] . '/labels' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . trim($labelString . ',red', ',');
             $result = $this->putter->put($url);
             // 説明文にダウン時間情報追加
             $url = 'https://trello.com/1/cards/' . $updateCard['id'] . '/desc' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . urlencode('< ' . $event->time->toDateTimeString() . " より停止中 >\n" . $updateCard['desc']);
             $result = $this->putter->put($url);
         }
     } else {
         // 新規カード追加
         $url = 'https://trello.com/1/cards/' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&idList=' . env('TRELLO_SITES_STATUS_LIST') . '&name=' . urlencode($event->url) . '&labels=' . ($event instanceof SiteUpped ? 'green' : 'red');
         $newCard = $this->converter->convert($this->poster->post($url));
         if ($event instanceof SiteDowned) {
             // 説明文のダウン時間情報更新
             $url = 'https://trello.com/1/cards/' . $newCard['id'] . '/desc' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . urlencode('< ' . $event->time->toDateTimeString() . " より停止中 >\n");
             $result = $this->putter->put($url);
         }
     }
 }
Example #8
0
 /**
  * @param string $template The name of the template to use for events. These are JSON files and reside in
  *                         [library]/config/schema
  *
  * @throws InternalServerErrorException
  * @return bool|array The schema in array form, FALSE on failure.
  */
 public static function initialize($template = self::SCRIPT_EVENT_SCHEMA)
 {
     if (false !== ($eventTemplate = \Cache::get('scripting.event_schema', false))) {
         return $eventTemplate;
     }
     //	Not cached, get it...
     $path = Platform::getLibraryConfigPath('/schema') . '/' . trim($template, ' /');
     if (is_file($path) && is_readable($path) && false !== ($eventTemplate = file_get_contents($path))) {
         if (false !== ($eventTemplate = json_decode($eventTemplate, true)) && JSON_ERROR_NONE == json_last_error()) {
             \Cache::add('scripting.event_schema', $eventTemplate, 86400);
             return $eventTemplate;
         }
     }
     \Log::notice('Scripting unavailable. Unable to load scripting event schema: ' . $path);
     return false;
 }
 protected function updateGame(\Morpheus\SteamGame $game, \GuzzleHttp\Psr7\Response $response)
 {
     $body = json_decode($response->getBody());
     $result = reset($body);
     if ($response->getStatusCode() == 200 && isset($result->success) && $result->success === true) {
         $game->steam_store_data = json_encode($result->data);
     } elseif ($response->getStatusCode() !== 200) {
         \Log::warning('Steam Store API call failed', ['status code' => $response->getStatusCode(), 'game' => $game]);
     } elseif (!isset($result->success)) {
         \Log::warning('Unexpected Steam Store API response', ['body' => $result, 'game' => $game]);
     } else {
         \Log::notice('Game not found in Steam Store database', ['game' => $game]);
     }
     $game->steam_store_updated = date('Y-m-d H:i:s');
     $game->save();
 }
    static function query($query, $connection = null, $file = null, $line = null)
    {
        if (self::is_logging()) {
            $query = str_replace("\n", '', $query);
            Log::notice(__FUNCTION__ . ' ' . $query, Log::frame(1));
        }

        $result = parent::query($query, $connection, $file, $line);

        if (empty($result)) {
            $backtrace = debug_backtrace(); // Retrieving information about the caller statement.
            $caller = isset($backtrace[0]) ? $backtrace[0] : array();
            $file = $caller['file'];
            $line = $caller['line'];
            $message = " sql: $query \n file: $file \n line:$line";
            Log::error($message);
        }
        return $result;
    }
 public static function authenticate($entitySignature, $identityKey, $resourceKey, $authKey, $identity, $resource)
 {
     $tag = "Sentry::authenticate()";
     Log::notice("{$tag}: <entitySignature={$entitySignature}, {$identityKey}={$identity}, {$resourceKey}={$resource}>");
     // TODO: (?) check users session for cached permissions
     try {
         $sentryBP = BlueprintReader::read($entitySignature);
         $entityDAO = new EntityDAO($sentryBP);
         $keys = array("{$identityKey}", "{$resourceKey}");
         $values = array("{$identity}", "{$resource}");
         $matches = $entityDAO->findWhere($keys, $values);
         if (0 == count($matches)) {
             Log::debug("{$tag}: No permission record was found.");
             return false;
         } else {
             if (1 == count($matches)) {
                 // found a matching permission record
                 $entity = $matches[0];
                 // extract value of $authKey field
                 $authValue = $entity->get($authKey);
                 // test for boolean values
                 if (empty($authValue) || $authValue == 0 || $authValue == "0" || strtoupper($authValue) == "NO" || strtoupper($authValue) == "FALSE") {
                     Log::debug("{$tag}: {$identityKey} {$identity} does not have permission to access {$resourceKey} {$resource}");
                     return false;
                 } else {
                     if ($authValue == 1 || $authValue == "1" || strtoupper($authValue) == "YES" || strtoupper($authValue) == "TRUE") {
                         Log::debug("{$tag}: {$identityKey} {$identity} has permission to access {$resourceKey} {$resource}");
                         return true;
                     }
                 }
             } else {
                 if (1 < count($matches)) {
                     Log::warning("{$tag}: ! More than one permission record was found.");
                     return false;
                 }
             }
         }
     } catch (Exception $e) {
         Log::error("{$tag}: " . $e->getMessage());
         return false;
     }
 }
Example #12
0
 /**
  * Sets the session values when username and password correct.
  * @return boolean Returns true when login was successful.
  */
 public function login($username, $password)
 {
     // Call plugins
     Plugins::get()->activate(__METHOD__, 0, func_get_args());
     $username_crypt = crypt($username, Settings::get()['username']);
     $password_crypt = crypt($password, Settings::get()['password']);
     // Check login with crypted hash
     if (Settings::get()['username'] === $username_crypt && Settings::get()['password'] === $password_crypt) {
         $_SESSION['login'] = true;
         $_SESSION['identifier'] = Settings::get()['identifier'];
         Log::notice(Database::get(), __METHOD__, __LINE__, 'User (' . $username . ') has logged in from ' . $_SERVER['REMOTE_ADDR']);
         return true;
     }
     // No login
     if ($this->noLogin() === true) {
         return true;
     }
     // Call plugins
     Plugins::get()->activate(__METHOD__, 1, func_get_args());
     // Log failed log in
     Log::error(Database::get(), __METHOD__, __LINE__, 'User (' . $username . ') has tried to log in from ' . $_SERVER['REMOTE_ADDR']);
     return false;
 }
 protected function updateGame(\Morpheus\SteamGame $game, \GuzzleHttp\Psr7\Response $response)
 {
     $body = json_decode($response->getBody());
     if ($response->getStatusCode() == 200 && isset($body->result) && $body->result !== false) {
         $game->metacritic_name = $body->result->name;
         $game->metacritic_score = $body->result->score;
         $game->metacritic_userscore = $body->result->userscore;
         $game->metacritic_genre = $body->result->genre[0];
         $game->metacritic_publisher = $body->result->publisher;
         $game->metacritic_developer = $body->result->developer;
         $game->metacritic_rating = $body->result->rating;
         $game->metacritic_url = $body->result->url;
         $game->metacritic_rlsdate = $body->result->rlsdate;
         $game->metacritic_summary = $body->result->summary;
     } elseif ($response->getStatusCode() !== 200) {
         \Log::warning('Metacritic API call failed', ['status code' => $response->getStatusCode(), 'game' => $game]);
     } elseif (!isset($body->result)) {
         \Log::warning('Unexpected Metacritic API response', ['body' => $body, 'game' => $game]);
     } else {
         \Log::notice('Game not found in Metacritic database', ['game' => $game]);
     }
     $game->metacritic_updated = date('Y-m-d H:i:s');
     $game->save();
 }
Example #14
0
 public function setTags($tags)
 {
     # Check dependencies
     self::dependencies(isset($this->database, $this->photoIDs));
     # Call plugins
     $this->plugins(__METHOD__, 0, func_get_args());
     # Parse tags
     $tags = preg_replace('/(\\ ,\\ )|(\\ ,)|(,\\ )|(,{1,}\\ {0,})|(,$|^,)/', ',', $tags);
     $tags = preg_replace('/,$|^,|(\\ ){0,}$/', '', $tags);
     if (strlen($tags) > 1000) {
         Log::notice($this->database, __METHOD__, __LINE__, 'Length of tags higher than 1000');
         return false;
     }
     # Set tags
     $query = Database::prepare($this->database, "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs));
     $result = $this->database->query($query);
     # Call plugins
     $this->plugins(__METHOD__, 1, func_get_args());
     if (!$result) {
         Log::error($this->database, __METHOD__, __LINE__, $this->database->error);
         return false;
     }
     return true;
 }
					if (!$singleDbForm) { //otherwise just use the main one
						iDatabase::select_db($row_course['db_name']);
					}
                    Log::notice('Course db ' . $row_course['db_name']);

					foreach ($c_q_list as $query) {
						if ($singleDbForm) {
							$query = preg_replace('/^(UPDATE|ALTER TABLE|CREATE TABLE|DROP TABLE|INSERT INTO|DELETE FROM)\s+(\w*)(.*)$/', "$1 $prefix{$row_course['db_name']}_$2$3", $query);
						}

						if ($only_test) {
							 Log::notice("iDatabase::query(".$row_course['db_name'].",$query)");
						} else {
							$res = iDatabase::query($query);
							if ($log) {
								 Log::notice("In ".$row_course['db_name'].", executed: $query");
							}
						}
					}

					$t_wiki = $row_course['db_name'].".wiki";
                    $t_wiki_conf = $row_course['db_name'].".wiki_conf";

                    if ($singleDbForm) {
                        $t_wiki = "$prefix{$row_course['db_name']}_wiki";
                        $t_wiki_conf = "$prefix{$row_course['db_name']}_wiki_conf";
                    }

                    // Update correct page_id to wiki table, actually only store 0
                    $query = "SELECT id, reflink FROM $t_wiki";
                    $res_page = iDatabase::query($query);
 public static function validate(Entity $entity)
 {
     $tag = "EntityValidator::validate()";
     Log::notice("{$tag}");
     $blueprint = $entity->blueprint();
     $errs = array();
     foreach ($blueprint->fields() as $field) {
         $key = $field->getKey();
         if ($err = EntityValidator::validateField($entity, $key)) {
             $errs["{$key}"] = $err;
         }
     }
     // log errors
     foreach ($errs as $key => $err) {
         Log::warning("{$tag}: [{$key}] {$err}");
     }
     return $errs;
 }
Example #17
0
 /**
  * Sets a new dropboxKey.
  * @return boolean Returns true when successful.
  */
 public static function setDropboxKey($dropboxKey)
 {
     if (strlen($dropboxKey) < 1 || strlen($dropboxKey) > 50) {
         Log::notice(Database::get(), __METHOD__, __LINE__, 'Dropbox key is either too short or too long');
         return false;
     }
     if (self::set('dropboxKey', $dropboxKey) === false) {
         return false;
     }
     return true;
 }
Example #18
0
 /**
  * Make sure the user has permission to do the action on this object
  *
  * Similar to [Comment::access] but this return TRUE/FALSE instead of exception
  *
  * @param   string     $action   The action `view|edit|delete` default `view`
  * @param   ORM        $comment  The comment object
  * @param   Model_User $user     The user object to check permission, defaults to loaded in user
  * @param   string     $misc     The misc element usually `id|slug` for logging purpose
  *
  * @return  boolean
  *
  * @throws  HTTP_Exception_404
  *
  * @uses    User::active_user
  * @uses    Module::event
  */
 public static function comment($action = 'view', ORM $comment, Model_User $user = NULL, $misc = NULL)
 {
     if (!in_array($action, array('view', 'edit', 'delete', 'add', 'list'), TRUE)) {
         // If the $action was not one of the supported ones, we return access denied.
         Log::notice('Unauthorized attempt to access non-existent action :act.', array(':act' => $action));
         return FALSE;
     }
     if (!$comment->loaded()) {
         // If the $action was not one of the supported ones, we return access denied.
         throw HTTP_Exception::factory(404, 'Attempt to access non-existent comment.');
     }
     // If no user object is supplied, the access check is for the current user.
     if (is_null($user)) {
         $user = User::active_user();
     }
     if (self::check('bypass comment access', $user)) {
         return TRUE;
     }
     // Allow other modules to interact with access
     Module::event('comment_access', $action, $comment);
     if ($action === 'view') {
         if ($comment->status === 'publish' and self::check('access comment', $user)) {
             return TRUE;
         } elseif ($comment->status != 'publish' and $comment->author == (int) $user->id and $user->id != 1) {
             return TRUE;
         } elseif (self::check('administer comment', $user)) {
             return TRUE;
         } else {
             return FALSE;
         }
     }
     if ($action === 'edit') {
         if (self::check('edit own comment') and $comment->author == (int) $user->id and $user->id != 1) {
             return TRUE;
         } elseif (self::check('administer comment', $user)) {
             return TRUE;
         } else {
             return FALSE;
         }
     }
     if ($action === 'delete') {
         if ((self::check('delete own comment') or self::check('delete any comment')) and $comment->author == (int) $user->id and $user->id != 1) {
             return TRUE;
         } elseif (self::check('administer comment', $user)) {
             return TRUE;
         } else {
             return FALSE;
         }
     }
     return TRUE;
 }
Example #19
0
 public function setDropboxKey($key)
 {
     # Check dependencies
     self::dependencies(isset($this->database, $key));
     if (strlen($key) < 1 || strlen($key) > 50) {
         Log::notice($this->database, __METHOD__, __LINE__, 'Dropbox key is either too short or too long');
         return false;
     }
     # Execute query
     $query = Database::prepare($this->database, "UPDATE ? SET value = '?' WHERE `key` = 'dropboxKey'", array(LYCHEE_TABLE_SETTINGS, $key));
     $result = $this->database->query($query);
     if (!$result) {
         Log::error($this->database, __METHOD__, __LINE__, $this->database->error);
         return false;
     }
     return true;
 }
Example #20
0
 public function getPublic($password)
 {
     Log::notice($this->database, __METHOD__, __LINE__, "Checking public for " . $this->photoIDs);
     # Functions checks if photo or parent album is public
     # Returns the following:
     # (int) 0 = Photo private and parent album private
     # (int) 1 = Album public, but password incorrect
     # (int) 2 = Photo public or album public and password correct
     # Check dependencies
     self::dependencies(isset($this->database, $this->photoIDs));
     # Call plugins
     $this->plugins(__METHOD__, 0, func_get_args());
     # Get photo
     $stmt = $this->database->prepare("SELECT public, album FROM " . LYCHEE_TABLE_PHOTOS . " WHERE id = ? LIMIT 1");
     $result = $stmt->execute(array($this->photoIDs));
     $photo = $stmt->fetchObject();
     # Check if public
     if ($photo->public == 1) {
         # Photo public
         return 2;
     } else {
         # Check if album public
         $album = new Album($this->database, null, null, $photo->album);
         $agP = $album->getPublic();
         $acP = $album->checkPassword($password);
         # Album public and password correct
         if ($agP === true && $acP === true) {
             return 2;
         }
         # Album public, but password incorrect
         if ($agP === true && $acP === false) {
             return 1;
         }
     }
     # Call plugins
     $this->plugins(__METHOD__, 1, func_get_args());
     # Photo private
     return 0;
 }
Example #21
0
 /**
  * @param string $apiName
  * @param array  $data
  *
  * @return array
  */
 protected static function parseSwaggerEvents($apiName, &$data)
 {
     $processEvents = [];
     $broadcastEvents = [];
     $eventCount = 0;
     foreach (ArrayUtils::get($data, 'apis', []) as $ixApi => $api) {
         $apiProcessEvents = [];
         $apiBroadcastEvents = [];
         $apiParameters = [];
         if (null === ($path = ArrayUtils::get($api, 'path'))) {
             \Log::notice('  * Missing "path" in Swagger definition: ' . $apiName);
             continue;
         }
         $path = str_replace(['{api_name}', '/'], [$apiName, '.'], trim($path, '/'));
         foreach (ArrayUtils::get($api, 'operations', []) as $ixOps => $operation) {
             if (null !== ($eventNames = ArrayUtils::get($operation, 'event_name'))) {
                 $method = strtolower(ArrayUtils::get($operation, 'method', Verbs::GET));
                 if (is_string($eventNames) && false !== strpos($eventNames, ',')) {
                     $eventNames = explode(',', $eventNames);
                     //  Clean up any spaces...
                     foreach ($eventNames as &$tempEvent) {
                         $tempEvent = trim($tempEvent);
                     }
                 }
                 if (empty($eventNames)) {
                     $eventNames = [];
                 } else {
                     if (!is_array($eventNames)) {
                         $eventNames = [$eventNames];
                     }
                 }
                 //  Set into master record
                 $data['apis'][$ixApi]['operations'][$ixOps]['event_name'] = $eventNames;
                 foreach ($eventNames as $ixEventNames => $templateEventName) {
                     $eventName = str_replace(['{api_name}', $apiName . '.' . $apiName . '.', '{action}', '{request.method}'], [$apiName, 'system.' . $apiName . '.', $method, $method], $templateEventName);
                     if (!isset($apiBroadcastEvents[$method]) || false === array_search($eventName, $apiBroadcastEvents[$method])) {
                         // should not have duplicates here.
                         $apiBroadcastEvents[$method][] = $eventName;
                     }
                     //  Set actual name in swagger file
                     $data['apis'][$ixApi]['operations'][$ixOps]['event_name'][$ixEventNames] = $eventName;
                     $eventCount++;
                 }
                 if (!isset($apiProcessEvents[$method])) {
                     $apiProcessEvents[$method][] = "{$path}.{$method}.pre_process";
                     $apiProcessEvents[$method][] = "{$path}.{$method}.post_process";
                     $parameters = ArrayUtils::get($operation, 'parameters', []);
                     foreach ($parameters as $parameter) {
                         if ('path' === ArrayUtils::get($parameter, 'paramType')) {
                             if (!empty($enums = ArrayUtils::get($parameter, 'enum'))) {
                                 $name = ArrayUtils::get($parameter, 'name', '');
                                 $apiParameters[$name] = $enums;
                             } elseif (!empty($options = ArrayUtils::get($parameter, 'options'))) {
                                 $name = ArrayUtils::get($parameter, 'name', '');
                                 $apiParameters[$name] = $options;
                             }
                         }
                     }
                 }
             }
             unset($operation);
         }
         $processEvents[str_ireplace('{api_name}', $apiName, $path)]['verb'] = $apiProcessEvents;
         $apiParameters = empty($apiParameters) ? null : $apiParameters;
         $processEvents[str_ireplace('{api_name}', $apiName, $path)]['parameter'] = $apiParameters;
         $broadcastEvents[str_ireplace('{api_name}', $apiName, $path)]['verb'] = $apiBroadcastEvents;
         unset($apiProcessEvents, $apiBroadcastEvents, $apiParameters, $api);
     }
     \Log::debug('  * Discovered ' . $eventCount . ' event(s).');
     return ['process' => $processEvents, 'broadcast' => $broadcastEvents];
 }
        }
        $pattern = '@claroline/scorm/showinframes\.php([^\s"\']*)file=([^\s"\'&]*)'.$enc_path.'@';
        if (preg_match_all($pattern, $intro, $out, PREG_SET_ORDER)) {
            foreach ($out as $results) {
                //echo "---> replace ".'/'.$results[0].'/ by newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id];
                //$intro = preg_replace('/scorm\/showinframes\.php([^\s"\']*)file=([^\s"\']*)'.$enc_path.'/', 'newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id], $intro);
                $intro = preg_replace('@claroline/scorm/showinframes\.php([^\s"\']*)file=([^\s"\'&]*)'.$enc_path.'([^\s"\']*)@','main/newscorm/lp_controller.php'.$results[1].'action=view&lp_id='.$lp_ids[$my_content_id], $intro);
            }
        } else {
            //echo "No scorm link found in intro text<br />";
        }
        if ($intro != $row_i['intro_text']) {
            //echo "<pre>Replacing ".$row_i['intro_text']."\n by \n ".$intro."</pre><br />\n";
            $sql_upd = "update $tbl_intro set intro_text = '".Database::escape_string($intro)."' WHERE id = 'course_homepage' AND intro_text = '".Database::escape_string($row_i['intro_text'])."'";
            //echo $sql_upd."<br />\n";
            fwrite($fh, $sql_upd."\n");
            fwrite($fh_revert, "UPDATE $tbl_intro set intro_text = '".$row_i['intro_text']."' WHERE id = 'course_homepage' AND intro_text = '$intro';\n");
            fwrite($fh_res, $intro."\n");
            Database::query($sql_upd);
        }
    }

    flush();
  }
}
fclose($fh);
fclose($fh_revert);
fclose($fh_res);
if ($loglevel > 0) { Log::notice("All done!"); }
//echo "</body></html>";
Example #23
0
 /**
  * @return bool|string
  */
 public function generateInstallKey()
 {
     try {
         /** @type ServiceUser $_user */
         $_user = ServiceUser::firstOrFail();
         return $_user->getHashedEmail();
     } catch (ModelNotFoundException $_ex) {
         \Log::notice('No console users found. Nothing to report.');
         return false;
     }
 }
 private static function prepareData(Blueprint $blueprint, $where = NULL, array $filters = NULL)
 {
     $tag = "EntityExporter::prepareData()";
     Log::notice("{$tag}");
     /*
     // BUILD QUERY
     */
     $query = new EntityQuery($blueprint);
     // WHERE
     if ($where != NULL) {
         $query->where($where);
     }
     // FILTERS
     if ($filters != NULL) {
         foreach ($filters as $key => $value) {
             if (ereg("^filter_(.+)_(.+)", $key, $regs)) {
                 $filter_field = $regs[1];
                 $filter_type = $regs[2];
                 $field = $blueprint->get($filter_field);
                 switch ($field->getDataType()) {
                     case "string":
                         switch ($filter_type) {
                             case "like":
                                 $query->where("{$filter_field} LIKE '%{$value}%'");
                                 break;
                             case "equals":
                                 $query->where("{$filter_field}='{$value}'");
                                 break;
                         }
                         break;
                     case "int":
                         switch ($filter_type) {
                             case "equals":
                                 $query->where("{$filter_field}={$value}");
                                 break;
                             case "min":
                                 $query->where("{$filter_field}>={$value}");
                                 break;
                             case "max":
                                 $query->where("{$filter_field}<={$value}");
                         }
                         break;
                     case "decimal":
                         switch ($filter_type) {
                             case "equals":
                                 $query->where("{$filter_field}='{$value}'");
                                 break;
                             case "min":
                                 $query->where("{$filter_field}>='{$value}'");
                                 break;
                             case "max":
                                 $query->where("{$filter_field}<='{$value}'");
                         }
                         break;
                     case "date":
                     case "datetime":
                         switch ($filter_type) {
                             case "equals":
                                 $query->where("{$filter_field}='{$value}'");
                                 break;
                             case "min":
                                 $query->where("{$filter_field}>='{$value}'");
                                 break;
                             case "max":
                                 $query->where("{$filter_field}<='{$value}'");
                         }
                         break;
                     case "enum":
                         switch ($filter_type) {
                             case "like":
                                 $query->where("{$filter_field} LIKE '%{$value}%'");
                                 break;
                             case "equals":
                                 $query->where("{$filter_field}='{$value}'");
                                 break;
                         }
                         break;
                 }
                 // END: switch($field->getDataType())
             }
             // END: if(ereg("^filter_(.+)_(.+)", $key, $regs))
         }
         // END: foreach($filters as $key=>$value)
     }
     // END: if($filters != NULL)
     // Execute Query
     $sql = new DatabaseQuery($query->toString());
     try {
         $sql->doQuery();
         $num_rows = $sql->get_num_rows();
         Log::debug("{$tag}: Exporting {$num_rows} rows");
         return $sql;
     } catch (Exception $e) {
         Log::error("{$tag}: [" . $sql->err_code . "] " . $sql->err_message);
         throw $e;
     }
 }
 * Chamilo LMS
 *
 * Updates the Dokeos files from version 1.8.4 to version 1.8.5
 * This script operates only in the case of an update, and only to change the
 * active version number (and other things that might need a change) in the
 * current configuration file.
 * As of 1.8.5, the Dokeos version has been added to configuration.php to
 * allow for edition (inc/conf is one of the directories that needs write
 * permissions on upgrade).
 * Being in configuration.php, it benefits from the configuration.dist.php
 * advantages that a new version doesn't overwrite it, thus letting the old
 * version be available until the end of the installation.
 * @package chamilo.install
 */

Log::notice('Entering file');

if (defined('SYSTEM_INSTALLATION')) {

	// Edit the configuration file
	$file = file(api_get_path(CONFIGURATION_PATH).'configuration.php');
	$fh = fopen(api_get_path(CONFIGURATION_PATH).'configuration.php', 'w');
	$found_version = false;
	$found_stable = false;
	foreach ($file as $line) {
		$ignore = false;
		if (stripos($line, '$_configuration[\'dokeos_version\']') !== false) {
			$found_version = true;
			$line = '$_configuration[\'dokeos_version\'] = \''.$new_version.'\';'."\r\n";
		} elseif (stripos($line, '$_configuration[\'dokeos_stable\']') !== false) {
			$found_stable = true;
Example #26
0
 static function prepare($database, $query, $data)
 {
     # Check dependencies
     Module::dependencies(isset($database, $query, $data));
     # Count the number of placeholders and compare it with the number of arguments
     # If it doesn't match, calculate the difference and skip this number of placeholders before starting the replacement
     # This avoids problems with placeholders in user-input
     # $skip = Number of placeholders which need to be skipped
     $skip = 0;
     $num = array('placeholder' => substr_count($query, '?'), 'data' => count($data));
     if ($num['data'] - $num['placeholder'] < 0) {
         Log::notice($database, __METHOD__, __LINE__, 'Could not completely prepare query. Query has more placeholders than values.');
     }
     foreach ($data as $value) {
         # Escape
         $value = mysqli_real_escape_string($database, $value);
         # Recalculate number of placeholders
         $num['placeholder'] = substr_count($query, '?');
         # Calculate number of skips
         if ($num['placeholder'] > $num['data']) {
             $skip = $num['placeholder'] - $num['data'];
         }
         if ($skip > 0) {
             # Need to skip $skip placeholders, because the user input contained placeholders
             # Calculate a substring which does not contain the user placeholders
             # 1 or -1 is the length of the placeholder (placeholder = ?)
             $pos = -1;
             for ($i = $skip; $i > 0; $i--) {
                 $pos = strpos($query, '?', $pos + 1);
             }
             $pos++;
             $temp = substr($query, 0, $pos);
             # First part of $query
             $query = substr($query, $pos);
             # Last part of $query
         }
         # Replace
         $query = preg_replace('/\\?/', $value, $query, 1);
         if ($skip > 0) {
             # Reassemble the parts of $query
             $query = $temp . $query;
         }
         # Reset skip
         $skip = 0;
         # Decrease number of data elements
         $num['data']--;
     }
     return $query;
 }
 public function delete($id)
 {
     $tag = "EntityDAO: delete()";
     Log::notice("{$tag}");
     $blueprint = $this->blueprint;
     $query = "DELETE FROM " . $this->tableName() . " WHERE id=" . $id;
     $sql = new DatabaseUpdate($query, "delete");
     try {
         $sql->doUpdate();
         $id = 0;
         return $id;
     } catch (Exception $e) {
         Log::error("{$tag}: [" . $sql->err_code . "] " . $sql->err_message);
         throw $e;
     }
 }
Example #28
0
 protected function resolve()
 {
     $result = null;
     if ($this->sudo) {
         \Log::notice("Super user access invoked", ['query' => $this->query]);
     } else {
         if ($this->request === self::REQUEST_PERMISSION) {
             if (!$this->enable) {
                 $result = true;
             } else {
                 $result = $this->resolveRequestPermission();
             }
         }
     }
     $this->reset();
     return $result;
 }
Example #29
0
 public function setTags($tags)
 {
     # Functions sets the tags of a photo
     # Excepts the following:
     # (string) $tags = Comma separated list of tags with a maximum length of 1000 chars
     # Returns the following:
     # (boolean) true = Success
     # (boolean) false = Failure
     # Check dependencies
     self::dependencies(isset($this->database, $this->photoIDs));
     # Call plugins
     $this->plugins(__METHOD__, 0, func_get_args());
     # Parse tags
     $tags = preg_replace('/(\\ ,\\ )|(\\ ,)|(,\\ )|(,{1,}\\ {0,})|(,$|^,)/', ',', $tags);
     $tags = preg_replace('/,$|^,|(\\ ){0,}$/', '', $tags);
     if (strlen($tags) > 1000) {
         Log::notice($this->database, __METHOD__, __LINE__, 'Length of tags higher than 1000');
         return false;
     }
     # Set tags
     $query = Database::prepare($this->database, "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs));
     $result = $this->database->query($query);
     # Call plugins
     $this->plugins(__METHOD__, 1, func_get_args());
     if (!$result) {
         Log::error($this->database, __METHOD__, __LINE__, $this->database->error);
         return false;
     }
     return true;
 }
 public static function import($path_csv, $path_resources = null, $mapping = array())
 {
     $tag = "EntityImporter:import()";
     Log::notice("{$tag}: <{$path_csv}, {$path_resources}, {$mapping}>");
     // pseudo contants
     $IMPORT_MODE_INSERT = 0;
     $IMPORT_MODE_UPDATE = 1;
     // init results array
     $stat = array();
     $stat["attempts"] = 0;
     $stat["inserts"] = 0;
     $stat["updates"] = 0;
     $stat["warnings"] = 0;
     $stat["errors"] = 0;
     // TODO: include sub-arrays for warning messages and error messages
     // eg: $stat["warning_messages"] = array(); where array indecies reference csv row numbers
     if (!is_readable($path_csv)) {
         Log::error("{$tag}: Unable to read from path {$path_csv}");
         throw new Exception("{$tag}: Unable to read from path {$path_csv}");
     }
     if ($path_resources != null && !is_readable($path_resources)) {
         Log::error("{$tag}: Unable to read from path {$path_resources}");
         throw new Exception("{$tag}: Unable to read from path {$path_resources}");
     }
     $csv_filename = basename($path_csv);
     $blueprint_key = substr($csv_filename, 0, strpos($csv_filename, "."));
     $blueprint_signature = $blueprint_key . ".entity.xml";
     Log::debug("{$tag}: Blueprint Signature: {$blueprint_signature}");
     /*
     // Compare CSV Header with Blueprint
     // determine if mapping is required
     */
     // read blueprint (on server)
     $bp = BlueprintReader::read($blueprint_signature);
     // init csv file for parsing
     $csv = new Csv($path_csv);
     // read csv header row
     $csv_header_row = $csv->nextRow();
     // apply mappings
     for ($i = 0; $i < count($csv_header_row); $i++) {
         $import_field = $csv_header_row[$i];
         $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field);
         // skip <id> columns
         if ($import_field == "id") {
             continue;
         }
         // skip columns where mapping is _DROP
         if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
             continue;
         }
         if (array_key_exists($mapping_key, $mapping)) {
             // replace csv column header with mapped value
             $csv_header_row[$i] = $mapping["{$mapping_key}"];
         }
     }
     foreach ($csv_header_row as $import_field) {
         // skip <id> columns
         if ($import_field == "id") {
             continue;
         }
         // skip columns where mapping is _DROP
         $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field);
         if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
             continue;
         }
         if (!$bp->keyExists($import_field)) {
             throw new EntityImporterException($bp, $csv_header_row);
         }
     }
     // check for id column
     $with_ids = false;
     if (in_array("id", $csv_header_row)) {
         $with_ids = true;
         Log::debug("{$tag}: Importing with ids");
     }
     // init Entity DAO
     $entityDAO = new EntityDAO($bp);
     // Import rows from Csv
     while (($row = $csv->nextRow()) !== FALSE) {
         $stat["attempts"]++;
         // init an entity to import
         unset($entity);
         // clear previous
         $entity = null;
         // flag an import mode (insert, update)
         $import_mode = EntityImporter::$IMPORT_MODE_INSERT;
         // check <id> to see if this csv row references an existing entity
         if ($with_ids) {
             $import_id = $row[0];
             if (!empty($import_id) && $import_id != 0) {
                 // check that an entity with this id exists
                 try {
                     if ($match = $entityDAO->load($import_id)) {
                         $entity = $match;
                         $import_mode = EntityImporter::$IMPORT_MODE_UPDATE;
                         Log::debug("{$tag}: Updating an existing {$blueprint_signature} with id {$import_id}");
                     } else {
                         $entity = $bp->build();
                         $entity->setId($import_id);
                         Log::debug("{$tag}: Creating a new {$blueprint_signature} with id {$import_id}");
                     }
                 } catch (Exception $e) {
                     $stat["warnings"]++;
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $entity = $bp->build();
                     $entity->setId($import_id);
                     Log::debug("{$tag}: Creating a new {$blueprint_signature} with id {$import_id}");
                 }
             }
             // END: if( (!empty($import_id)) && ($import_id!=0) )
         }
         // END: if($with_ids)
         // if we are not working with an existing entity, build a new one
         if ($entity == null) {
             $entity = $bp->build();
             Log::debug("{$tag}: Creating a new {$blueprint_signature} without an id");
         }
         for ($i = 0; $i < count($csv_header_row); $i++) {
             // extract data from csv
             $import_field_key = $csv_header_row[$i];
             $import_field_value = $row[$i];
             // skid <id> column
             if ($import_field_key == "id") {
                 continue;
             }
             // skip columns where mapping is _DROP
             $mapping_key = "mapping_" . $bp->getKey() . "_" . str_replace(".", "_", $import_field_key);
             if (array_key_exists($mapping_key, $mapping) && $mapping[$mapping_key] == "_DROP") {
                 continue;
             }
             // extract field information from blueprint
             $field = $bp->get($import_field_key);
             switch ($field->getDataType()) {
                 case "date":
                     // reformat dates for mysql
                     $time = strtotime($import_field_value);
                     $import_field_value = date("Y-m-d", $time);
                     $entity->set($import_field_key, $import_field_value);
                     break;
                 case "binary":
                     $path_binary = $path_resources . $import_field_value;
                     Log::debug("{$tag}: Searching for binary at path {$path_binary}");
                     if (is_readable($path_binary)) {
                         Log::debug("{$tag}: Found readable binary at path {$path_binary}");
                         $binaryString = file_get_contents($path_binary);
                         $entity->set($import_field_key, $binaryString);
                     } else {
                         Log::debug("{$tag}: No readable binary at path {$path_binary}");
                     }
                     break;
                 default:
                     $entity->set($import_field_key, $import_field_value);
                     break;
             }
             // END: switch($field->getType())
         }
         // END: for($i=0; $i<count($csv_header_row); $i++)
         switch ($import_mode) {
             case EntityImporter::$IMPORT_MODE_UPDATE:
                 try {
                     $entityDAO->update($entity);
                     $stat["updates"]++;
                 } catch (Exception $e) {
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $stat["errors"]++;
                 }
                 break;
             case EntityImporter::$IMPORT_MODE_INSERT:
                 try {
                     $entityDAO->insert($entity);
                     $stat["inserts"]++;
                 } catch (Exception $e) {
                     Log::warning("{$tag}: Caught Exception: " . $e->getMessage());
                     $stat["errors"]++;
                 }
                 break;
         }
     }
     // END: while( ($row = $csv->nextRow()) !== FALSE )
     return $stat;
 }