Exemplo n.º 1
0
 public function defaultAction()
 {
     // Line chart
     $memcache = new \Memcached();
     $stats1 = $memcache->get('stats1');
     if ($stats1 === false) {
         $stats = Stat::select(DB::raw('max(`packages`) as packages'), DB::raw('sum(`added`) as added'), DB::raw('date(`created_at`) as date'))->orderBy('date', 'asc')->groupBy('date')->get();
         $stats1 = [['Date', 'Total', 'New']];
         foreach ($stats as $stat) {
             $stats1[] = [$stat->date, (int) $stat->packages, (int) $stat->added];
         }
         $memcache->set('stats1', $stats1, self::DAY);
     }
     // Domain table
     $memcache = new \Memcached();
     $stats2 = $memcache->get('stats2');
     if ($stats2 === false) {
         $stats2 = Package::select(['domain', DB::raw('count(domain) as count')])->groupBy('domain')->where('domain', '<>', '')->orderBy('count', 'desc')->get()->toArray();
         $memcache->set('stats2', $stats2, self::DAY);
     }
     // Types table
     $memcache = new \Memcached();
     $stats3 = $memcache->get('stats3');
     if ($stats3 === false || true) {
         $stats3 = Package::select(['type', DB::raw('count(type) as count')])->groupBy('type')->where('type', '<>', '')->having('count', '>', 9)->orderBy('count', 'desc')->get()->toArray();
         $memcache->set('stats3', $stats3, self::DAY);
     }
     $this->_setTitle('Stats');
     return new StatsView($stats1, $stats2, $stats3);
 }
Exemplo n.º 2
0
 function getSectorEmpresas(Request $request, Response $response)
 {
     $response = $response->withHeader('Content-type', 'application/json');
     $data = Parametros::select("*")->first();
     $km = $data["diametro_busqueda"];
     $idSector = $request->getAttribute("id");
     $lat = $request->getAttribute("latitud");
     $lng = $request->getAttribute("longitud");
     $query = "SELECT " . "(6371 * ACOS( SIN(RADIANS(su.latitud)) * SIN(RADIANS({$lat})) + COS(RADIANS(su.longitud - {$lng})) * " . "COS(RADIANS(su.latitud)) * COS(RADIANS({$lat})))) AS distancia, " . "em.id, " . "em.nit, " . "em.razonSocial, " . "em.logo, " . "'' as servicios " . "FROM sucursal su " . "INNER JOIN " . "empresa em ON (em.id = su.idEmpresa) " . "INNER JOIN " . "sectorempresa secemp ON (secemp.idEmpresa = em.id && secemp.idSector =  {$idSector}) " . "WHERE su.Estado = 'ACTIVO' AND em.estado = 'ACTIVO' " . "HAVING distancia < {$km} ORDER BY distancia ASC";
     $data = DB::select(DB::raw($query));
     for ($i = 0; $i < count($data); $i++) {
         $val = "";
         $ser = Servicio::select("nombre")->where("idEmpresa", "=", $data[$i]->id)->get();
         $tam = count($ser);
         for ($j = 0; $j < $tam; $j++) {
             $val .= $ser[$j]->nombre;
             if ($j + 1 < $tam) {
                 $val .= ",";
             }
         }
         $data[$i]->servicios = $val;
     }
     $response->getBody()->write(json_encode($data));
     return $response;
 }
Exemplo n.º 3
0
 public function scopeMostActive($query, $limit = false)
 {
     $query->select(['author.id', 'author.name', DB::raw('COUNT(plugin_author.plugin_id) as plugin_count')])->leftJoin('plugin_author', 'author.id', '=', 'plugin_author.author_id')->groupBy('author.name')->orderBy('plugin_count', 'DESC');
     if ($limit != false) {
         $query->take($limit);
     }
     return $query;
 }
Exemplo n.º 4
0
 public function create($token, $expireTime, $sessionId)
 {
     $accessToken = new AccessToken();
     $accessToken->token = $token;
     $accessToken->session_id = $sessionId;
     $accessToken->expire_time = Capsule::raw('FROM_UNIXTIME(' . $expireTime . ')');
     $accessToken->save();
 }
Exemplo n.º 5
0
 public static function insertSkipDupes($domains)
 {
     $query = sprintf('INSERT INTO domains (name) VALUES ("%s") ON DUPLICATE KEY UPDATE name=name', implode('"),("', $domains));
     $status = DB::statement($query);
     Domain::where('created_at', '0000-00-00 00:00:00')->update(['created_at' => DB::raw('NOW()')]);
     Domain::where('created_at', '0000-00-00 00:00:00')->update(['updated_at' => DB::raw('NOW()')]);
     return $status;
 }
Exemplo n.º 6
0
 public function create($token, $expireTime, $accessToken)
 {
     $accessToken = AccessToken::where('token', '=', $accessToken)->first();
     $refreshToken = new RefreshToken();
     $refreshToken->token = $token;
     $refreshToken->access_token_id = $accessToken->id;
     $refreshToken->expire_time = DB::raw('FROM_UNIXTIME(' . $expireTime . ')');
     $refreshToken->save();
 }
 /**
  * Do the migration
  */
 public function up()
 {
     //Create
     $this->schema->create('account_status', function ($table) {
         $table->increments('id');
         $table->string('value', 200);
         $table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
     });
 }
 public function promedio(Request $request, Response $response)
 {
     $response = $response->withHeader('Content-type', 'application/json');
     $idCliente = $request->getAttribute("idCliente");
     $query = "SELECT COALESCE(AVG(calificacion),0) as promedio FROM calificacioncliente WHERE idCliente = " . $idCliente;
     $data = DB::select(DB::raw($query));
     $response->getBody()->write(json_encode($data));
     return $response;
 }
Exemplo n.º 9
0
 function contasector(Request $request, Response $response)
 {
     $response = $response->withHeader('Content-type', 'application/json');
     //sum(ingresos.valor) as total,
     $id = $request->getAttribute("idSector");
     $fechainicial = $request->getAttribute("fechainicial");
     $fechafinal = $request->getAttribute("fechafinal");
     $data = DB::select(DB::raw("select sum(ingresos.valor) as total,ingresos.fecha,sectorempresa.id," . "empresa.razonSocial,sucursal.nombre" . " from sectorempresa " . "inner join empresa on empresa.id = sectorempresa.idEmpresa " . "inner join sucursal on sucursal.idEmpresa = empresa.id " . "inner join empleado on empleado.idSucursal = sucursal.id " . "inner join ingresos on ingresos.idEmpleado = empleado.id " . "where sectorempresa.idSector = " . $id . " and ingresos.fecha BETWEEN '" . $fechainicial . "' and " . "'" . $fechafinal . "' " . "GROUP BY empresa.razonSocial"));
     $response->getBody()->write(json_encode($data));
     return $response;
 }
 /**
  * Do the migration
  */
 public function up()
 {
     //Create the table
     $this->schema->create('account_verification_tokens', function ($table) {
         $table->increments('id');
         $table->integer('user_id')->unsigned();
         $table->string('token', 100);
         $table->enum('status', ['active', 'expired']);
         $table->dateTime('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
         $table->foreign('user_id')->references('id')->on('users');
     });
 }
 /**
  * Do the migration
  */
 public function up()
 {
     //Create the table
     $this->schema->create('uom_valid_ids', function ($table) {
         $table->string('id', 50);
         $table->string('first_name', 100);
         $table->string('last_name', 100);
         $table->enum('type', ['student', 'lecturer']);
         $table->timestamp('datetime')->default(DB::raw('CURRENT_TIMESTAMP'));
         $table->boolean('valide');
         $table->boolean('has_account');
         $table->primary('id');
     });
 }
Exemplo n.º 12
0
 public function getBaseQuery($limit = false, $offset = 0, $orderField = 'fRating', $desc = true, $starred = false)
 {
     $query = DB::table('deals')->select(DB::raw('fmtc_merchants.*, fmtc_deals.*'))->join('merchants', 'deals.nMerchantID', '=', 'merchants.nMerchantID')->where('dtStartDate', '<=', date('Y-m-d H:i:s'))->where('dtEndDate', '>=', date('Y-m-d H:i:s'));
     if ($starred) {
         $query->where('bStarred', 1);
     }
     $order = $desc ? 'desc' : 'asc';
     $query->orderBy($orderField, $order);
     if ($orderField !== 'fRating') {
         $query->orderBy('fRating', 'desc');
     }
     if ($limit !== false) {
         $query->skip($offset);
         $query->take($limit);
     }
     return $query;
 }
Exemplo n.º 13
0
 public function __construct($queryBuilder)
 {
     $this->queryBuilder = $queryBuilder;
     // Clone the query builder to compute
     // Collection length with a subquery
     $clone = clone $this->queryBuilder;
     $query = $clone instanceof \Illuminate\Database\Eloquent\Builder ? $clone->getQuery() : $clone;
     $this->length = \Illuminate\Database\Capsule\Manager::table(\Illuminate\Database\Capsule\Manager::raw("({$clone->toSql()}) as sub"))->mergeBindings($query)->count();
     // Parse range headers and compute
     // available range that is going
     // to be returned
     $this->parseRangeHeader();
     if (!$this->currentRange) {
         $this->page = [];
     } else {
         // If parseRangeHeader() worked,
         // we can fetch the page
         $this->page = $this->getPage();
     }
 }
 /**
  * Do the migration
  */
 public function up()
 {
     //Create the table
     $this->schema->create('users', function ($table) {
         $table->increments('id');
         $table->string('first_name', 100);
         $table->string('last_name', 100);
         $table->string('email', 200)->unique();
         $table->string('password', 100);
         $table->enum('user_type', ['student', 'lecturer']);
         $table->date('date_of_birth');
         $table->enum('gender', ['male', 'female']);
         $table->string('uom_id', 50)->unique();
         $table->integer('account_status')->unsigned();
         $table->string('remember_me', 100);
         $table->timestamp('datetime_joined')->default(DB::raw('CURRENT_TIMESTAMP'));
         //Add foreign key constrains
         $table->foreign('uom_id')->references('id')->on('uom_valid_ids');
         $table->foreign('account_status')->references('id')->on('account_status');
     });
 }
Exemplo n.º 15
0
 /**
  * This count the items returned by a SQL query
  */
 public static function preCountQuery($queryBuilder)
 {
     $qb = clone $queryBuilder;
     return \Illuminate\Database\Capsule\Manager::table(\Illuminate\Database\Capsule\Manager::raw("({$qb->toSql()}) as sub"))->mergeBindings($qb->getQuery())->count();
 }
Exemplo n.º 16
0
 /**
  * @return mixed
  */
 protected function _getData()
 {
     return Manager::table('users')->select(Manager::raw('count(country) as count, country'))->where('country', '<>', '')->groupBy('country');
 }
Exemplo n.º 17
0
 function empleadosDisponibles(Request $request, Response $response)
 {
     $response = $response->withHeader('Content-type', 'application/json');
     $idServicio = $request->getAttribute("idServicio");
     $idSucursal = $request->getAttribute("idSucursal");
     $fecha = $request->getAttribute("fecha");
     $hora = $request->getAttribute("hora");
     $cupos = $request->getAttribute("cupos");
     $dataMitiempo = ServiciosSucursal::select("minutos")->where("idServicio", "=", $idServicio)->where("idSucursal", "=", $idSucursal)->first();
     $minutos = 60;
     if ($data != null) {
         $minutos = $dataMitiempo->minutos;
     }
     $empleado = Empleado::select("*")->where("idSucursal", "=", $idSucursal)->where("idPerfil", "=", 2)->get();
     //$horaFinal = "(sec_to_time(time_to_sec('$hora') + (time_to_sec('$hora') * $cupos)))";
     $tiempo = 0;
     for ($i = 0; $i < $cupos; $i++) {
         $tiempo += $minutos;
     }
     $horaFinal = "ADDTIME('{$hora}', SEC_TO_TIME({$tiempo}*60))";
     $data = array();
     for ($i = 0; $i < count($empleado); $i++) {
         $query = "SELECT " . "tur.id " . "FROM " . "turno tur " . "WHERE " . "tur.idServicio = {$idServicio} AND " . "tur.idSucursal = {$idSucursal} AND " . "tur.idEmpleado = " . $empleado[$i]->id . " AND " . "tur.fechaReserva = '{$fecha}' AND " . "tur.reserva = 'A' AND " . "(tur.estadoTurno <> 'TERMINADO' AND tur.estadoTurno <> 'CANCELADO') AND (" . "(TIMESTAMP('{$fecha}','{$hora}') >= tur.horaReserva AND TIMESTAMP('{$fecha}','{$hora}') < tur.horaFinalReserva) OR " . "(TIMESTAMP('{$fecha}',{$horaFinal}) > tur.horaReserva AND TIMESTAMP('{$fecha}',{$horaFinal}) <= tur.horaFinalReserva))";
         //. "(TIMESTAMP('$fecha','$hora') < tur.horaReserva AND TIMESTAMP('$fecha',$horaFinal) > tur.horaReserva))";
         $disp = DB::select(DB::raw($query));
         if (count($disp) == 0) {
             $data[] = $empleado[$i];
         }
     }
     $response->getBody()->write(json_encode($data));
     return $response;
 }
Exemplo n.º 18
0
 public function scopeTrendingTop($query, $limit = 10)
 {
     $query->select(['plugin.id', 'plugin.name', 'plugin.key', 'plugin.download_count', DB::raw('COUNT(name) as recent_downloads')])->join('plugin_download', 'plugin.id', '=', 'plugin_download.plugin_id')->where('downloaded_at', '>', DB::raw('NOW() - INTERVAL 1 MONTH'))->groupBy('plugin.name')->orderBy('recent_downloads', 'DESC')->take($limit);
     return $query;
 }
Exemplo n.º 19
0
 public function scopeWithUsage($query)
 {
     $query->addSelect(['*', DB::raw('(SELECT COUNT(*) FROM plugin_tags WHERE tag_id = tag.id) as plugin_count')]);
     return $query;
 }
Exemplo n.º 20
0
 protected function createMerchantsTable()
 {
     if (!DB::schema()->hasTable('merchants')) {
         DB::schema()->create('merchants', function ($table) {
             $table->increments('id');
             $table->integer('nMerchantID')->index();
             $table->integer('nMasterMerchantID');
             $table->integer('nSkimlinksID');
             $table->string('cName', 255);
             $table->string('cNetwork', 3);
             $table->integer('cProgramID');
             $table->string('cNetworkNotes', 32);
             $table->integer('bDual');
             $table->string('aDualMerchants');
             $table->integer('nParentMerchantID');
             $table->text('cAffiliateURL');
             $table->text('cSkimlinksURL');
             $table->text('cFMTCURL');
             $table->string('cHomepageURL', 255);
             $table->string('cStatus', 6);
             $table->string('dtCreated', 25);
             $table->string('dtLastUpdated', 25);
             $table->integer('bSelected');
             $table->integer('bRelationshipExists');
             $table->string('cPrimaryCountry', 2);
             $table->string('aShipToCountries');
             $table->integer('bAPOFPO');
             $table->string('cPrimaryCategory', 20);
             $table->string('aCategories');
             $table->integer('bMobileCertified');
             $table->text('aLogos');
             $table->string('aPaymentOptions');
             $table->string('cCustomMerchantLogo', 10);
             $table->string('cCustomMerchantDescription', 10);
             $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
             $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
         });
     }
 }
Exemplo n.º 21
0
 public function updatePlugin($plugin, $xml, $new_crc)
 {
     if (strlen($plugin->name) == 0) {
         echo "first time update, found name \"" . $xml->name . "\"...";
         $firstTimeUpdate = true;
     } else {
         if ($plugin->name != $xml->name) {
             echo "\"" . $plugin->name . "\" going to become \"" . $xml->name . "\" ...";
         } else {
             echo "\"" . $xml->name . "\" going to be updated ...";
         }
     }
     // Updating basic infos
     $plugin->logo_url = $xml->logo;
     $plugin->name = $xml->name;
     $plugin->key = $xml->key;
     $plugin->homepage_url = $xml->homepage;
     $plugin->download_url = $xml->download;
     $plugin->issues_url = $xml->issues;
     $plugin->readme_url = $xml->readme;
     $plugin->license = $xml->license;
     // reading descriptions,
     // mapping type=>lang relation to lang=>type
     $descriptions = [];
     foreach ($xml->description->children() as $type => $descs) {
         if (in_array($type, ['short', 'long'])) {
             foreach ($descs->children() as $_lang => $content) {
                 $descriptions[$_lang][$type] = (string) $content;
             }
         }
     }
     // Delete current descriptions
     $plugin->descriptions()->delete();
     // Refreshing descriptions
     foreach ($descriptions as $lang => $_type) {
         $description = new PluginDescription();
         $description->lang = $lang;
         foreach ($_type as $type => $html) {
             $description[$type . '_description'] = $html;
         }
         $description->plugin_id = $plugin->id;
         $description->save();
     }
     // Refreshing authors
     $plugin->authors()->detach();
     $clean_authors = [];
     foreach ($xml->authors->children() as $author) {
         $_clean_authors = $this->fixParseAuthors((string) $author);
         foreach ($_clean_authors as $author) {
             $clean_authors[] = $author;
         }
     }
     foreach ($clean_authors as $_author) {
         $found = Author::where('name', '=', $_author)->first();
         if (sizeof($found) < 1) {
             $author = new Author();
             $author->name = $_author;
             $author->save();
         } else {
             $author = $found;
         }
         if (!$plugin->authors->find($author->id)) {
             $plugin->authors()->attach($author);
         }
     }
     // Refreshing versions
     $plugin->versions()->delete();
     foreach ($xml->versions->children() as $_version) {
         foreach ($_version->compatibility as $compat) {
             $version = new PluginVersion();
             $version->num = trim((string) $_version->num);
             $version->compatibility = trim((string) $compat);
             $version->plugin_id = $plugin->id;
             $version->save();
         }
     }
     // Refreshing screenshots
     if (isset($xml->screenshots)) {
         $plugin->screenshots()->delete();
         foreach ($xml->screenshots->children() as $url) {
             $screenshot = new PluginScreenshot();
             $screenshot->url = (string) $url;
             $screenshot->plugin_id = $plugin->id;
             $screenshot->save();
         }
     }
     // Reassociating plugin to tags
     $plugin->tags()->detach();
     foreach ($xml->tags->children() as $lang => $tags) {
         foreach ($tags->children() as $_tag) {
             $found = Tag::where('tag', '=', (string) $_tag)->where('lang', '=', $lang)->first();
             if (sizeof($found) < 1) {
                 $tag = new Tag();
                 $tag->tag = (string) $_tag;
                 $tag->lang = $lang;
                 $tag->key = Tool::getUrlSlug((string) $_tag);
                 $tag->save();
             } else {
                 $tag = $found;
             }
             $tag->plugins()->attach($plugin);
         }
     }
     // new crc
     $plugin->xml_crc = $new_crc;
     // new timestamp
     if (!isset($firstTimeUpdate)) {
         $plugin->date_updated = DB::raw('NOW()');
     }
     $plugin->save();
     echo " OK\n";
 }
Exemplo n.º 22
0
                case 'subject':
                    if (gettype($body->contact->subject) != 'string' || strlen($body->contact->subject) > 280) {
                        throw new InvalidField('subject');
                    }
                    break;
                case 'message':
                    if (gettype($body->contact->message) != 'string' || strlen($body->contact->message) > 16000) {
                        throw new InvalidField('message');
                    }
                    break;
            }
        }
    }
    // Sending mail
    $mailer = new Mailer();
    $mailer->sendMail('user_message.html', Tool::getConfig()['msg_alerts']['local_admins'], '[MSG] ' . $body->contact->subject, ['firstname' => $body->contact->firstname, 'lastname' => $body->contact->lastname, 'email' => $body->contact->email, 'message' => $body->contact->message], [$body->contact->email => $body->contact->firstname . ' ' . $body->contact->lastname]);
    // also saving message in database
    $message = new Message();
    $message->first_name = $body->contact->firstname;
    $message->last_name = $body->contact->lastname;
    $message->email = $body->contact->email;
    $message->subject = $body->contact->subject;
    $message->message = $body->contact->message;
    $message->sent = DB::raw('NOW()');
    $message->save();
    Tool::endWithJson(["success" => true]);
});
// HTTP REST Map
$app->post('/message', $send);
$app->options('/message', function () {
});
Exemplo n.º 23
0
 static function raw($string)
 {
     return Capsule::raw($string);
 }
Exemplo n.º 24
0
 * This REST module hooks on
 * following URLs
 *
 * /download/:plugin_id
 */
use API\Core\Tool;
use API\Model\Plugin;
use API\Model\PluginDownload;
use Illuminate\Database\Capsule\Manager as DB;
use API\OAuthServer\OAuthHelper;
$download = Tool::makeEndpoint(function ($key) use($app) {
    $plugin = Plugin::where('key', '=', $key)->first();
    $plugin->download_count = DB::raw('download_count + 1');
    $plugin->save();
    $plugin_download = new PluginDownload();
    $plugin_download->downloaded_at = DB::raw('NOW()');
    $plugin_download->plugin_id = $plugin->id;
    $plugin_download->save();
    /**
     * @MonkeyPatch
     * @todo remove this as soon as possible once
     * all our famous, star, since-day-one
     * contributors took the time
     * to update their XML file.
     */
    $indepnetFixSearchPattern = '/https:\\/\\/forge\\.indepnet\\.net/';
    if (preg_match($indepnetFixSearchPattern, $plugin->download_url)) {
        $plugin->download_url = preg_replace($indepnetFixSearchPattern, 'https://forge.glpi-project.org', $plugin->download_url);
    }
    $app->redirect($plugin->download_url, 301);
});
Exemplo n.º 25
0
 function contaempleadosucursal(Request $request, Response $response)
 {
     $response = $response->withHeader('Content-type', 'application/json');
     $id = $request->getAttribute("idsucursal");
     $fechainicial = $request->getAttribute("fechainicial");
     $fechafinal = $request->getAttribute("fechafinal");
     $data = DB::select(DB::raw("select CONCAT(empleado.nombres,' ',empleado.apellidos) as empleado," . "empleado.identificacion,sucursal.nombre,ingresos.idEmpleado,sum(ingresos.valor) as total," . "empleado.email,empleado.telefono,empleado.estado " . "from sucursal " . "inner join empleado on empleado.idSucursal = sucursal.id " . "inner join ingresos on ingresos.idEmpleado = empleado.id " . "where sucursal.id = " . $id . " and ingresos.fecha BETWEEN '" . $fechainicial . "' and " . "'" . $fechafinal . "'" . "GROUP BY ingresos.idEmpleado"));
     $response->getBody()->write(json_encode($data));
     return $response;
 }
Exemplo n.º 26
0
 /**
  * Task : updatePlugin()
  *
  * Note: This function does direct output,
  * in fact it builds the log string
  * that concerns the update of a
  * plugin.
  */
 private function updatePlugin($plugin, $index = null, $length = null, $subtasks)
 {
     // Displaying index / length
     $this->outputStr('Plugin (' . $index . '/' . $length . ') (id #' . $plugin->id . '): ');
     $update = false;
     // This can be used to detect the state
     // in some way (think about it)
     $this->currentXml = null;
     $this->currentPluginState = null;
     // fetching via http
     $unableToFetch = false;
     $httpClient = new GuzzleHttpClient();
     try {
         $pluginXmlRequest = $httpClient->get($plugin->xml_url, ["headers" => ["User-Agent" => Tool::getConfig()['glpi_plugin_directory_user_agent']]]);
     } catch (\GuzzleHttp\Exception\ConnectException $e) {
         $unableToFetch = true;
     } finally {
         if ($unableToFetch || !$unableToFetch && $pluginXmlRequest->getStatusCode() != 200) {
             if ($this->pluginMaxConsecutiveXmlFetchFails) {
                 $fetchFailCount = $plugin->incrementXmlFetchFailCount();
                 if ($fetchFailCount == $this->pluginMaxConsecutiveXmlFetchFails) {
                     $this->triggerPluginXmlStateChange($plugin, 'bad_xml_url', true, in_array('alert_plugin_team_on_xml_state_change', $subtasks));
                     $plugin->resetXmlFetchFailCount();
                 }
             } else {
                 $this->triggerPluginXmlStateChange($plugin, 'bad_xml_url', true, in_array('alert_plugin_team_on_xml_state_change', $subtasks));
             }
             $this->outputStr($plugin->xml_url . "\" Cannot get XML file via HTTP, Skipping.\n");
             if ($this->throwsExceptions) {
                 throw new InvalidXML('url', $plugin->xml_url);
             }
             return false;
         } else {
             $plugin->resetXmlFetchFailCount();
         }
     }
     $xml = $pluginXmlRequest->getBody();
     $this->currentXml = (string) $xml;
     $crc = md5($xml);
     // compute crc
     if ($plugin->xml_crc != $crc || $plugin->name == NULL) {
         $update = true;
         // if we got
         // missing name or changing
         // crc, then we're going to
         // update that one.
         // missing name means it's
         // the first time the plugin
         // is updated
     } else {
         $this->outputStr("\"" . $plugin->name . "\" Already up-to-date, Skipping.\n");
         $this->triggerPluginXmlStateChange($plugin, 'passing', true, in_array('alert_plugin_team_on_xml_state_change', $subtasks));
         return false;
     }
     try {
         $xml = new ValidableXMLPluginDescription($xml);
         $xml->validate();
     } catch (\API\Exception\InvalidXML $e) {
         $_unreadable = '';
         if (isset($xml->contents) && $xml->contents->name && sizeof($xml->contents->name->children()) < 1 && strlen((string) $xml->contents->name) < 80) {
             $_unreadable .= '"' . (string) $xml->contents->key . '" ';
         } elseif ($plugin->name) {
             $_unreadable .= '"' . $plugin->name . '" ';
         }
         $this->triggerPluginXmlStateChange($plugin, 'xml_error', true, in_array('alert_plugin_team_on_xml_state_change', $subtasks));
         $_unreadable .= "Unreadable/Non validable XML, error: " . $e->getRepresentation() . " Skipping.\n";
         $this->outputStr($_unreadable);
         if ($this->throwsExceptions) {
             throw $e;
         }
         return false;
     }
     $xml = $xml->contents;
     if (!$plugin->name) {
         $this->outputStr("first time update, found name \"" . $xml->name . "\"...");
         if (Plugin::where('name', '=', $xml->name)->first()) {
             $this->outputStr(" already exists. skipping.");
             // this would be amazing to alert the administrators
             // of that. new Mailer; ?
             return false;
         }
         $firstTimeUpdate = true;
     } else {
         if ($plugin->name != $xml->name) {
             $this->outputStr(" requested name change to \"" . $xml->name . "\" ...");
             if (Plugin::where('name', '=', $xml->name)->first()) {
                 $this->outputStr(" but name already exists. skipping.");
                 // this would be amazing to alert the administrators
                 // of that. new Mailer; ?
                 return false;
             }
         }
         $firstTimeUpdate = false;
         $this->outputStr("\"" . $plugin->name . "\"");
     }
     $this->outputStr(" going to be synced with xml ...");
     $this->triggerPluginXmlStateChange($plugin, 'passing', true, in_array('alert_plugin_team_on_xml_state_change', $subtasks));
     // Updating basic infos
     $plugin->logo_url = $xml->logo;
     $plugin->name = $xml->name;
     $plugin->key = $xml->key;
     $plugin->homepage_url = $xml->homepage;
     $plugin->download_url = $xml->download;
     $plugin->issues_url = $xml->issues;
     $plugin->readme_url = $xml->readme;
     $plugin->license = $xml->license;
     // reading descriptions,
     // mapping type=>lang relation to lang=>type
     $descriptions = [];
     foreach ($xml->description->children() as $type => $descs) {
         if (in_array($type, ['short', 'long'])) {
             foreach ($descs->children() as $_lang => $content) {
                 $descriptions[$_lang][$type] = (string) $content;
             }
         }
     }
     // Delete current descriptions
     $plugin->descriptions()->delete();
     // Refreshing descriptions
     foreach ($descriptions as $lang => $_type) {
         $description = new PluginDescription();
         $description->lang = $lang;
         foreach ($_type as $type => $html) {
             $description[$type . '_description'] = $html;
         }
         $description->plugin_id = $plugin->id;
         $description->save();
     }
     // Refreshing authors
     $plugin->authors()->detach();
     $clean_authors = [];
     foreach ($xml->authors->children() as $author) {
         $_clean_authors = Author::fixKnownDuplicates((string) $author);
         foreach ($_clean_authors as $author) {
             $clean_authors[] = $author;
         }
     }
     foreach ($clean_authors as $_author) {
         $found = Author::where('name', '=', $_author)->first();
         if (sizeof($found) < 1) {
             $author = new Author();
             $author->name = $_author;
             $author->save();
         } else {
             $author = $found;
         }
         if (!$plugin->authors->find($author->id)) {
             $plugin->authors()->attach($author);
         }
     }
     // Refreshing versions
     $plugin->versions()->delete();
     foreach ($xml->versions->children() as $_version) {
         foreach ($_version->compatibility as $compat) {
             $version = new PluginVersion();
             $version->num = trim((string) $_version->num);
             $version->compatibility = trim((string) $compat);
             $version->plugin_id = $plugin->id;
             $version->save();
         }
     }
     // Refreshing screenshots
     if (isset($xml->screenshots)) {
         $plugin->screenshots()->delete();
         foreach ($xml->screenshots->children() as $url) {
             $screenshot = new PluginScreenshot();
             $screenshot->url = (string) $url;
             $screenshot->plugin_id = $plugin->id;
             $screenshot->save();
         }
     }
     // Reassociating plugin to tags
     $plugin->tags()->detach();
     foreach ($xml->tags->children() as $lang => $tags) {
         foreach ($tags->children() as $_tag) {
             $found = Tag::where('tag', '=', (string) $_tag)->where('lang', '=', $lang)->first();
             if (sizeof($found) < 1) {
                 $tag = new Tag();
                 $tag->tag = (string) $_tag;
                 $tag->lang = $lang;
                 $tag->key = Tool::getUrlSlug((string) $_tag);
                 $tag->save();
             } else {
                 $tag = $found;
             }
             $tag->plugins()->attach($plugin);
         }
     }
     // Reassociating plugin to langs
     $plugin->langs()->detach();
     foreach ($xml->langs->children() as $lang) {
         $lang = (string) $lang;
         $_lang = PluginLang::where('lang', '=', $lang)->first();
         if (!$_lang) {
             $_lang = new PluginLang();
             $_lang->lang = $lang;
             $_lang->save();
         }
         $_lang->plugins()->attach($plugin);
     }
     // new crc
     $plugin->xml_crc = $crc;
     // new updated timestamp
     $plugin->date_updated = \Illuminate\Database\Capsule\Manager::raw('NOW()');
     $plugin->save();
     $this->outputStr(" OK.");
     if (in_array('alert_watchers', $subtasks)) {
         $this->alertWatchers($plugin);
         $this->outputStr("\n");
     } else {
         $this->outputStr("\n");
     }
 }
Exemplo n.º 27
0
 function calificarServicio(Request $request, Response $response)
 {
     $response = $response->withHeader('Content-type', 'application/json');
     $idServicio = $request->getAttribute("idServicio");
     $data = json_decode($request->getBody(), true);
     try {
         $query = "INSERT INTO " . "calificacionservicio (idServicio,idEmpleado,idSucursal,calificacion) " . "VALUES (" . "{$idServicio}," . "" . $data['idEmpleado'] . "," . "" . $data['idSucursal'] . "," . "" . $data['calificacion'] . ")";
         DB::statement(DB::raw($query));
         $respuesta = json_encode(array('msg' => "Guardado correctamente", "std" => 1));
         $response = $response->withStatus(200);
     } catch (Exception $err) {
         $respuesta = json_encode(array('msg' => "error", "std" => 0, "err" => $err->getMessage()));
         $response = $response->withStatus(404);
     }
     $response->getBody()->write($respuesta);
     return $response;
 }
Exemplo n.º 28
0
  *
  * @apiSuccess {Date} date Date, année plus mois des commandes.
  * @apiSuccess {Number} nb_command Nombre de commande sur une journée.
  *
  * @apiSuccessExample Success-Response:
  *     HTTP/1.1 200 OK
  *
  * @apiErrorExample Error-Response:
  *     HTTP/1.1 404 Not Found
  *     {
  *       "error": code error
  *     }
  */
 $app->get('/stats/', function ($request, $response) {
     try {
         $response = $response->withJson(Capsule::table('COMMAND')->select(Capsule::raw("COUNT(*) as nb_command, DATE_FORMAT(time,'%Y-%m-%d') AS time_new"))->groupBy('time_new')->get());
     } catch (Illuminate\Database\QueryException $e) {
         $response = $response->withJson(array("status" => array("error" => $e->getMessage())), 400);
     }
     return $response;
 });
 /**
  * @api {get} /command/id_commande/:id_commande Récupération d'un commande par son ID.
  * @apiName GetCommandsByIdCommand
  * @apiGroup Command
  *
  * @apiParam {Number} id Commande unique ID.
  *
  * @apiSuccess {Number} id_commande ID du commande.
  * @apiSuccess {String} login Login de la commande de l'utilisateur.
  * @apiSuccess {Number} state Etat de la commande.
Exemplo n.º 29
0
 /**
  * Scope for teachers with april-born students
  *
  * @param $query
  * @return mixed
  */
 public function scopeAprilBornStudents($query)
 {
     $query->select('teachers.*')->join('teacher_student', 'teachers.id', '=', 'teacher_student.teacher_id')->join('students', 'teacher_student.student_id', '=', 'students.id')->where(DB::raw('MONTH(students.birth_date)'), '=', '4');
     return $query;
 }
Exemplo n.º 30
0
 /**
  * It creates an access token, a session, and links
  * scopes mentionned in $scopes to the session and
  * access token, it finally returns the new access token
  *
  * It associates the 'webapp' app
  */
 public static function createAccessTokenFromUserId($user_id, $scopes, $ttl = 3600)
 {
     $user = User::where('id', '=', $user_id)->first();
     if (!$user) {
         return false;
     }
     $session = new Session();
     $session->owner_type = 'user';
     $session->owner_id = $user->id;
     $session->app_id = 'webapp';
     $session->save();
     $accessToken = new AccessToken();
     $accessToken->session_id = $session->id;
     $accessToken->token = SecureKey::generate();
     $accessToken->expire_time = DB::raw('FROM_UNIXTIME(' . ($ttl + time()) . ')');
     $accessToken->save();
     foreach ($scopes as $_scope) {
         $scope = Scope::where('identifier', '=', $_scope)->first();
         if ($scope) {
             $session->scopes()->attach($scope);
             $accessToken->scopes()->attach($scope);
         }
     }
     $refreshToken = new RefreshToken();
     $refreshToken->access_token_id = $accessToken->id;
     $refreshToken->token = SecureKey::generate();
     $refreshToken->expire_time = DB::raw('FROM_UNIXTIME(' . (604800 + time()) . ')');
     $refreshToken->save();
     return ["token" => $accessToken->token, "refresh_token" => $refreshToken->token, "ttl" => $ttl];
 }