Created by ticup on 04/11/13.
174060
function View(attrs) {
  var view = this;
  if (typeof attrs !== 'undefined') {
    Object.keys(attrs).forEach(function (attr) {
      view[attr] = attrs[attr];
    });
  }
  if (typeof this.initialize === 'function')
    this.initialize();
}
34184
function f_tahta_ihale_takip_idler(_tahta_id) {
        return result.dbQ.smembers(result.kp.tahta.ssetTakiptekiIhaleleri(_tahta_id));
    }
662186
function f_rol_bolgeleri_tumu(_rol_id, _tahta_id) {

        return result.dbQ.smembers(result.kp.rol.ssetBolgeleri(_rol_id))
            .then(function (_bolge_idler) {
                if (_bolge_idler && _bolge_idler.length > 0) {
                    var db_bolge = require("./db_bolge");
                    return db_bolge.f_db_bolge_id(_bolge_idler)
                } else {
                    return null;
                }
            });
    }
557353
def toc(message='Elapsed time : {} s'):
    
    t = time.time()
    print(message.format(t - __time_tic_toc))
    return t - __time_tic_toc
1036453
function f_tahta_ihale_gizlenen_toplami(_tahta_id) {
        var db_ihale = require("./db_ihale");
        return result.dbQ.exists(result.kp.temp.ssetTahtaIhaleTumu(_tahta_id))
            .then(function (_iExist) {
                return (_iExist
                    ? 1//temp kayıtlı
                    : db_ihale.f_db_tahta_ihale_idler_aktif(_tahta_id))//temp oluşturmak için ihale idlerini çek
            })
            .then(function () {
                return result.dbQ.Q.all([
                    f_tahta_ihale_gizlenen_idler(_tahta_id),
                    result.dbQ.scard(result.kp.temp.ssetTahtaIhaleTumu(_tahta_id))

                ]).then(function (_ress) {
                    /** @type {GrafikDonut} */
                    var sonuc = schema.f_create_default_object(schema.SCHEMA.GRAFIK_DONUT);
                    var gecerli = parseInt(_ress[0].length || 0),
                        toplam = parseInt(_ress[1] || 0);

                    sonuc.Toplam = toplam;
                    sonuc.Gecerli = gecerli;
                    sonuc.Gecersiz = toplam - gecerli;
                    return sonuc;
                });
            });

    }
1108598
public void createDir(String key, int ttl, Boolean prevExist) throws EtcdClientException {
        Preconditions.checkNotNull(key);

        List<BasicNameValuePair> data = Lists.newArrayList();
        data.add(new BasicNameValuePair("dir", String.valueOf(true)));
        if (ttl > 0) {
            data.add(new BasicNameValuePair("ttl", String.valueOf(ttl)));
        }
        if (prevExist != null) {
            data.add(new BasicNameValuePair("prevExist", String.valueOf(prevExist)));
        }

        put(key, data, null, new int[]{200, 201});
    }
987829
public void union(Viewport v) {
        union(v.left, v.top, v.right, v.bottom);
    }
607498
function f_kurum_tumu(tahta_id, ihale_id) {
        return result.dbQ.sinter(result.kp.tahta.ssetTeklifleri(tahta_id, true), result.kp.ihale.ssetTeklifleri(ihale_id))
            .then(function (_teklif_idler) {
                if (_teklif_idler && _teklif_idler.length > 0) {
                    return result.dbQ.hmget(result.kp.teklif.hsetKurumlari, _teklif_idler)
                        .then(function (_kurum_idler) {
                            if (_kurum_idler && _kurum_idler.length > 0) {
                                var db_kurum = require("./db_kurum");
                                return db_kurum.f_db_kurum_id(_kurum_idler);
                            } else {
                                return [];
                            }
                        });
                } else {
                    return null;
                }
            })
            .fail(function () {
                l.e("ihale kurumları çekilemedi");
            });
    }
641134
function tumblr(hostname, key, secret, access_key, access_secret) {
  if (!(this instanceof tumblr)) return new tumblr(hostname, key, secret, access_key, access_secret);

  var obj = (typeof hostname !== 'object') ? {
    hostname : hostname,
    secret : secret,
    key : key,
    access_secret : access_secret,
    access_key : access_key
  } : hostname;

  // reference
  if (obj && obj.hostname) this.hostname = !/\./.test(obj.hostname) ? obj.hostname + '.tumblr.com' : obj.hostname;
  this.key = obj.key;
  this.secret = obj.secret;
  this.access_key = obj.access_key;
  this.access_secret = obj.access_secret;

  // output the log to console
  this.debug = false;

  // keeping the logs even if debug is false
  this.log = [];

  // caching requests
  this.caches = false;
  this._cache = {};

  // oauth access
  this._oauth_access = this.access_key && this.access_secret;

  // if response should omit "meta"
  this.onlyResponse = true;

  if (this.key && this.secret && this._oauth_access) {
    this._oa = oa = new OAuth('http://www.tumblr.com/oauth/request_token',
                              'http://www.tumblr.com/oauth/access_token',
                              this.key, this.secret, '1.0A',
                              null, 'HMAC-SHA1');

    var self = this;
    oa.getOAuthRequestToken(function(err, req_key, req_secret, res) {
      if (!err) {
        var url = ['http://www.tumblr.com/oauth/authorize/?oauth_token=', req_key].join('');
        self.OAuthAuthorizationURL = url;
        self._oa.session = self._oa.session || {};
        self._oa.session.key = req_key;
        self._oa.session.secret = req_secret;
      }
      else {
        debug(err);
      }
    });
  }
  return this;
}
1354331
function create() {
  var name = [ 'tobi', 'loki', 'jane', 'manny' ][ Math.random() * 4 | 0 ];
  var job  = jobs.create( 'video conversion', {
    title: 'converting ' + name + '\'s to avi', user: 1, frames: 200
  } );

  job.on( 'complete', function () {
    console.log( " Job complete" );
  } ).on( 'failed', function () {
    console.log( " Job failed" );
  } ).on( 'progress', function ( progress ) {
    process.stdout.write( '\r  job #' + job.id + ' ' + progress + '% complete' );
  } );

  job.save();

  setTimeout( create, Math.random() * 2000 | 0 );
}
208131
function DevAdapter (controller) {
    
    // Define or LEX/Bison grammar to handle device packet
    var grammar = {
    "lex": {
        "rules" : [ ["\\s+" , "/* skip whitespace */"]
            // Lex rules==> smallest token after big/generic ones ex: 'b,'/'b', [A,C]/[a-Z], etc ...
            ,['help\\b'             , "return 'HELP';"]
            ,['quit\\b'             , "return 'QUIT';"]
            ,['ctrl\\b'             , "return 'CTRL';"]
            ,['back\\b'             , "return 'BACK';"]
            
            ,['evt\\b'              , "return 'EVTS';"]
            ,['start\\b'            , "return 'STAR';"]
            ,['on\\b'               , "return 'STAR';"]
            ,['stop\\b'             , "return 'STOP';"]
            ,['off\\b'              , "return 'STOP';"]
            
            ,['dev\\b'              , "return 'DEV';"]
            ,['list\\b'             , "return 'LIS';"]
            ,['login\\b'            , "return 'LOG';" ]
            ,['logout\\b'           , "return 'OUT';" ]
            ,['track\\b'            , "return 'TRK';" ]
            ,['info\\b'             , "return 'INF';" ]
            ,['track\\b'            , "return 'TRK';" ]
            
            ,['snd\\b'              , "return 'SEND';"]
            ,['all\\b'              , "return 'ALL';" ]

            ,['db\\b'               , "return 'BASE';"]
            ,['create\\b'           , "return 'CREA';"]
            ,['remove\\b'           , "return 'DROP';"]
            ,['search\\b'           , "return 'SEAR';"]
            ,['show\\b'             , "return 'SEAR';"]
            ,['init\\b'             , "return 'INIT';"]

            ,['[\',\"]'             , "/* ignored */" ]
            ,['[^ ]+\\b'            , "return 'TXT';" ]
            ,['\\n'                 , "return 'EOL';" ]
            ,[';'                   , "return 'EOL';" ]
            ,['$'                   , "return 'EOL';" ]
        ]
    },  // end Lex rules
    
    "bnf": { // WARNING: only one space in between TOKEN ex: "STOP EOF"
        'data': [["EOL"        ,"this.cmd='EMPTY'; return (this);"]
            ,["QUIT EOL"   ,"this.cmd='QUIT'   ; return (this);"]
            ,["HELP EOL"   ,"this.cmd='HELP'   ; return (this);"]
            ,["CTRL EOL"   ,"this.cmd='CONTROL'; return (this);"]
            ,["BACK EOL"   ,"this.cmd='BACKEND'; return (this);"]
            ,["COMMD EOL"  ,"return (this);"]

            ,["DEV LIS EOL"  ,"this.cmd='DEVLIST' ; return (this);"]
            ,["DEV ALL EOL"  ,"this.cmd='DEVALL' ; return (this);"]
            ,["DEV LOG TXT EOL"   ,"this.cmd='DEVIN'  ; this.devid=$3; return (this);"]
            ,["DEV OUT TXT EOL"   ,"this.cmd='DEVOUT' ; this.devid=$3; return (this);"]
            ,["DEV OUT ALL EOL"   ,"this.cmd='DEVOUT' ; this.devid=0;  return (this);"]
            ,["DEV TRK TXT EOL"   ,"this.cmd='DEVTRCK'; this.devid=$3; return (this);"]
            ,["DEV TRK ALL EOL"   ,"this.cmd='DEVTRCK'; this.devid=0;  return (this);"]
            ,["DEV INF TXT EOL"   ,"this.cmd='DEVINFO'; this.devid=$3; return (this);"]

            ,["BASE INIT EOL"     ,"this.cmd='DBINIT' ;return (this);"]
            ,["BASE DROP TXT EOL" ,"this.cmd='DBDROP' ; this.devid=$3;return (this);"]
            ,["BASE SEAR TXT EOL" ,"this.cmd='DBSEAR' ; this.devid=$3; this.args=5; return (this);"]
            ,["BASE SEAR TXT TXT EOL" ,"this.cmd='DBSEAR' ; this.devid=$3; this.limit=parseInt($4); return (this);"]
            ,["BASE CREA TXT TXT TXT TXT TXT TXT TXT ARGS EOL","this.cmd='DBCREA' ; this.devid=$3; this.mmsi=$4; this.callsign=$5; this.cargo=$6; this.length=$7; this.width=$8; this.model=$9; return (this);"]

            ,["EVTS STAR EOL" ,"this.cmd='EVTSTART' ; return (this);"]
            ,["EVTS STOP EOL" ,"this.cmd='EVTSTOP'  ; return (this);"]
           ] 
        ,'COMMD':[
            ,["SEND TXT ALL ARGS"     , "this.cmd='SEND'; this.action=$2; this.devid=0;"]
            ,["SEND TXT TXT ARGS"     , "this.cmd='SEND'; this.action=$2; this.devid=$3;"]
            ,["SEND TXT ALL"          , "this.cmd='SEND'; this.action=$2; this.devid=0;"]
            ,["SEND TXT TXT"          , "this.cmd='SEND'; this.action=$2; this.devid=$3;"]
            ,["SEND HELP TXT"         , "this.cmd='SEND'; this.devid=$3; this.action='help';"]
        ]
        ,'ARGS':[
             ["TXT"                   , "this.args=[$1];"]
            ,["ARGS TXT"              , "this.args.push ($2);"]
        ]
    }};

    this.id        = controller.svc;
    this.uid       = "//" + controller.svcopts.adapter + "/" + controller.svc + ":" +  controller.svcopts.port;;
    this.control   = "tcpsock";
    this.info      = "Telnet";
    this.debug     = controller.svcopts.debug;  // inherit debug from controller
    this.Debug     (1,"uid=%s", this.uid);
    this.controller= controller;  // keep a link to device controller and TCP socket
    this.parser    = new Jison(grammar);
    this.request   = 0; // job request number for gateway queue
    try {
        this.prompt= controller.gateway.opts.name +"> ";
    } catch (err) {
        this.prompt= "GatewayTracker> ";
    }
}
1026876
def tblPeople
      @headers = %w{PersonID FamilyName GivenNames GivenInitials Suffix Role LastUpdate ModifiedBy}
      sql = []   
      @name_collection.ref_collection.all_authors.each do |a|
        cols = {
          PersonID: a.id,
          FamilyName: (a.last_name.length > 0 ? a.last_name : "Unknown"),
          GivenNames: a.first_name || @empty_quotes,
          GivenInitials: a.initials_string || @empty_quotes,
          Suffix: a.suffix || @empty_quotes,
          Role: 1,                          # authors 
          LastUpdate: @time,
          ModifiedBy: @authorized_user_id
        }
        sql << sql_insert_statement('tblPeople', cols) 
      end
      sql.join("\n")
    end
608872
private function createBrandsTbl()
    {
        Schema::create('tbl_brands', function (Blueprint $table) {
            $table->increments('id')->unsigned();
            $table->text('name');
            $table->tinyInteger('status')->default(1);
            $table->tinyInteger('default')->default(0);
            $table->timestamps();
            $table->softDeletes();
        });
        $datetime = Carbon::now();

        DB::table('tbl_brands')->insert([
            'name'       => 'Antares',
            'status'     => 1,
            'default'    => 1,
            'created_at' => $datetime
        ]);
    }
1077789
function(){
            // Compute team Wins, Losts, Draws and Goal-Sum
            /*
                // Uses the key as the teamId
                {
                         1: {P: x, S: y, [...]},
                    teamId: {P: x, S: y, [...]}
                 }
            */
            var rawTable = {};
            var _default = {rank: 0, teamId: 0, P: 0, goalsMade: 0, goalsTaken: 0, S: 0, W: 0, D: 0, L: 0, score: 0};

            for(var k in this.matches){
                var match = this.matches[k];

                // Compute game points for both teams
                computeGame(match, match.teamAId, match.teamAScore, match.teamBScore);
                computeGame(match, match.teamBId, match.teamBScore, match.teamAScore);
            }

            // Adds game to the teamId. Should be runned twice for each
            // side of match (teamA and teamB).
            function computeGame(match, teamId, goalsMade, goalsTaken){
                // Skip empty id's
                if(!teamId)
                    return;

                // Generate default template if NOT in array yet
                if(!rawTable[teamId]){
                    var teamRow = _.clone(_default);
                    // Keeps team id under team
                    teamRow.teamId = teamId;
                    // Inserts team in rawTable
                    rawTable[teamId] = teamRow;
                }

                // Get teamRow (it is supposed to exist)
                var teamRow = rawTable[teamId];

                // Compute points ONLY if match is not 'scheduled'
                // logycaly, it's 'ended' or 'playing', so we compute it
                if(match.state == 'scheduled')
                    return;

                // Increment Plays
                teamRow.P++;

                // Compute goals made/taken
                teamRow.goalsMade += goalsMade*1;
                teamRow.goalsTaken += goalsTaken*1;

                // Win
                if(goalsMade > goalsTaken)
                    teamRow.W ++;
                // Loose
                else if(goalsMade < goalsTaken)
                    teamRow.L ++;
                // Drew
                else
                    teamRow.D ++;
            }

            // Compute 'final score' and add column S (goalsMade:goalsTaken)
            // Transfer data to final table array
            var finalTable = [];
            _.forEach(rawTable, function(row){
                row.score = row.W*3 + row.D*1;
                row.S = row.goalsMade*1 + ':' + row.goalsTaken*1;
                row.GD = row.goalsMade*1 - row.goalsTaken*1;

                finalTable.push(row);
            });

            // Sort by 'score' field
            finalTable = _.sortBy(finalTable, 'score').reverse();

            // Rank Table
            var pos = 0;
            var lastScore = -1;

            _.forEach(finalTable, function(row){
                // Keeps the same ranking if scores is the same
                if(lastScore != row.score){
                    pos++;
                    lastScore = row.score;
                }

                row.rank = pos;
            });


            return finalTable;


        }
290239
public function ajouter()
    {
        $html = '';
        $erreur = array();
        $tabForm = array();
        $ajoutOk = false;
        $aAuthentification = new archiAuthentification();
        $formulaire = new formGenerator();
        if ($aAuthentification->estConnecte() == 0) {
            echo 'utilisateur non connecté';
            $this->erreurs->ajouter('Vous n\'êtes pas connecté !');
        } elseif (isset($this->variablesPost['ajoutSousEvenement'])) {
            $tabForm=$this->getEvenementFields('nouveauDossier');

            $erreur = $formulaire->getArrayFromPost($tabForm);

            if (count($erreur) == 0) {
                $this->connexionBdd->getLock(array('evenements'));

                //***************
                //**  GESTION DES VARIABLES
                //**

                $titre              = mysql_escape_string($tabForm['titre']['value']);
                $description        = mysql_escape_string($tabForm['description']['value']);
                $dateDebut          = $this->date->toBdd($this->date->convertYears($tabForm['dateDebut']['value']));
                $isDateDebutEnviron = $tabForm['isDateDebutEnviron']['value'];
                $dateFin            = $this->date->toBdd($this->date->convertYears($tabForm['dateFin']['value']));
                $idSource=0;
                if ($tabForm['source']['value']!='') {
                    $idSource    = $tabForm['source']['value'];
                }
                $idUtilisateur   = $aAuthentification->getIdUtilisateur();
                $idTypeStructure = $tabForm['typeStructure']['value'];
                $idTypeEvenement = $tabForm['typeEvenement']['value'];
                $nbEtages = $tabForm['nbEtages']['value'];


                $ISMH           = $tabForm['ISMH']['value'];
                $MH             = $tabForm['MH']['value'];


                //**************
                //**  VERIFICATION DOUBLON
                //**

                $sqlVerificationDoublon = "
						SELECT he1.idEvenement
						FROM evenements he2, evenements he1
						RIGHT JOIN _evenementEvenement ee ON ee.idEvenement = '".$this->variablesPost['evenementGroupeAdresse']."'
						WHERE he2.idEvenement = he1.idEvenement
						AND he1.titre='".$titre."'
						AND he1.idEvenement = ee.idEvenementAssocie
						AND he1.description = \"".$description."\"
						AND he1.dateDebut = \"".$dateDebut."\"
						AND he1.isDateDebutEnviron = '".$isDateDebutEnviron."'
						AND he1.dateFin = \"".$dateFin."\"
						AND he1.idSource = '".$idSource."'
						AND he1.idTypeStructure='".$idTypeStructure."'
						AND he1.idTypeEvenement='".$idTypeEvenement."'
						GROUP BY he1.idEvenement, he1.idEvenement
						";

                $res = $this->connexionBdd->requete($sqlVerificationDoublon);

                if (mysql_num_rows($res) != 0) {
                    $this->erreurs->ajouter(_("Exactement le même enregistrement existe déjà !"));

                    // on défini les informations pour pouvoir tout de même afficher l'événement
                    $rep         = mysql_fetch_object($res);
                    $idEvenement = $rep->idEvenement;
                    $ajoutOk     = true;
                } else {
                    //***************
                    //**  ENREGISTREMENT
                    //**
                    //$idEvenement = $this->getNewIdEvenement();
                    // si c'est un événement sans événements parents
                    // c'est qu'il faut créer un evenement vide
                    // ayant pour type d'événement un groupe d'adresses
                    // sur lequel on va donc lier les adresses

                    if (!isset($this->variablesPost['evenementGroupeAdresse']) || $this->variablesPost['evenementGroupeAdresse']=='') {//(empty($tabForm['evenements']['value']))
                    // creation de l'evenement parent groupe d'adresse
                        $sql = "INSERT INTO evenements (titre, description, dateDebut, dateFin, idSource, idUtilisateur, idTypeStructure, idTypeEvenement,dateCreationEvenement)
								VALUES ('', '', '', '', ".$idSource.", ".$idUtilisateur.", 0, '".$this->getIdTypeEvenementGroupeAdresse()."', now())";

                        $this->connexionBdd->requete($sql);
                        $tabForm['evenements']['value'][] = $idEvenement;

                        $idEvenement = $this->connexionBdd->getLastId();
                        $idSousEvenement =$idEvenement+ 1; // id du sous evenements lié à l'evenement groupe d'adresses


                        // on lie les adresses a l'evenement groupe d'adresse
                        if (!empty($tabForm['adresses']['value'])) {
                            $sqlEvenementAdresse = "INSERT INTO _adresseEvenement (idAdresse,idEvenement) VALUES ";
                            foreach (array_unique($tabForm['adresses']['value']) as $idAdresse) {
                                $sqlEvenementAdresse .= '('.$idAdresse.', '.$idEvenement.'),';
                            }
                            $sqlEvenementAdresse = pia_substr($sqlEvenementAdresse, 0, -1);
                            $this->connexionBdd->requete($sqlEvenementAdresse);
                        }
                    } else {
                        $idSousEvenement = $idEvenement; // si on est dans le cas d'un ajout de sous evenement simple , sans creation de groupe d'adresse, on recupere l'id d'un nouvel element virtuel (getNewIdEVenement)
                    }



                    // debug
                    if ($nbEtages=='') {
                        $nbEtages=0;
                    }

                    // ajout de l'evenement fils
                    $sqlHistoriqueEvenement =
                    "INSERT INTO evenements (
								titre,
								description,
								dateDebut,
								dateFin,
								idSource,
								idUtilisateur,
								idTypeStructure,
								idTypeEvenement,
								dateCreationEvenement ,
								nbEtages,
								ISMH,
								MH,
								isDateDebutEnviron
							)

							VALUES (
								\"".$titre."\",
								\"".$description."\",
								'".$dateDebut."',
								'".$dateFin."',
								 ".$idSource.",
								 ".$idUtilisateur.",
						 		'".$idTypeStructure."',
				 				'".$idTypeEvenement."',
		 						now(),
		 						".$nbEtages.",
	 							'".$ISMH."',
	 							'".$MH."',
	 							'".$isDateDebutEnviron."'
 														)";
                    $this->connexionBdd->requete($sqlHistoriqueEvenement);


                    $idSousEvenement=$this->connexionBdd->getLastId();


                    if (!empty($tabForm['courant']['value'])) {
                        $sqlEvenementCourantArchitectural = "INSERT INTO _evenementCourantArchitectural (idCourantArchitectural, idEvenement) VALUES ";
                        foreach (array_unique($tabForm['courant']['value']) as $idCourant) {
                            $sqlEvenementCourantArchitectural .= '('.$idCourant.', '.$idSousEvenement.'),';
                        }
                        $sqlEvenementCourantArchitectural = pia_substr($sqlEvenementCourantArchitectural, 0, -1);

                        $this->connexionBdd->requete($sqlEvenementCourantArchitectural);
                    }

                    if (!empty($tabForm['personnes']['value'])) {
                        $sqlEvenementPersonne = "INSERT INTO _evenementPersonne (idPersonne, idEvenement) VALUES ";
                        foreach (array_unique($tabForm['personnes']['value']) as $idPersonne) {
                            $sqlEvenementPersonne .= '('.$idPersonne.', '.$idSousEvenement.'),';
                        }
                        $sqlEvenementPersonne = pia_substr($sqlEvenementPersonne, 0, -1);
                        $this->connexionBdd->requete($sqlEvenementPersonne);
                    }


                    //TODO : Gestion du tableau de source
                    /*
					 if(!empty($tabForm['source']['value'])){
					$sqlEvenementSource = "INSERT INTO _evenementSource (idSource, idEvenement) VALUES ";
					foreach ( array_unique($tabForm['source']['value']) AS $idSource)
					{
					$sqlEvenementSource .= '('.$idSource.', '.$idSousEvenement.'),';
					}
					$sqlEvenementSource = pia_substr( $sqlEvenementSource, 0, -1);

					$this->connexionBdd->requete($sqlEvenementSource);
					}
					*/




                    // ajout de l'evenement enfant à l'evenement groupe d'adresse

                    if (!isset($this->variablesPost['evenementGroupeAdresse']) || $this->variablesPost['evenementGroupeAdresse']=='') {//(empty($tabForm['evenements']['value']))
                    // cas liaison entre le nouvel evenement groupe d'adresse et le nouvel evenement fils // ajout d'un evenement
                        $sqlEvenementEvenement = "
								insert into _evenementEvenement (idEvenement,idEvenementAssocie)
								values ('".$idEvenement."','".$idSousEvenement."');
										";
                        //debug($sqlEvenementEvenement);
                        $this->connexionBdd->requete($sqlEvenementEvenement);
                    } else {
                        // cas liaison entre l'element groupe d'adresse precisé dans $tabForm['evenementGroupeAdresse'] et le nouvel evenement fils // ajout d'un sous evenement
                        $sqlEvenementEvenement = "
								insert into _evenementEvenement (idEvenement,idEvenementAssocie)
								values ('".$this->variablesPost['evenementGroupeAdresse']."','".$idSousEvenement."')
										";
                        //debug($sqlEvenementEvenement);
                        $this->connexionBdd->requete($sqlEvenementEvenement);
                    }

                    $ajoutOk = true;
                }

                // libération de la table
                $this->connexionBdd->freeLock(array('evenements'));
            }
        }

        if ($ajoutOk === true) {
            if (isset($idSousEvenement)) {
                $idEvenementGroupeAdresse = $this->getIdEvenementGroupeAdresseFromIdEvenement($idSousEvenement);

                // d'abord on classe les evenements (les positions précédentes sont conservees)
                $this->majPositionsEvenements(array('idEvenementGroupeAdresse'=>$idEvenementGroupeAdresse,'idNouvelEvenement'=>$idSousEvenement));

                $mail = new mailObject();
                $adresse = new archiAdresse();
                $reqAdresses = $adresse->getIdAdressesFromIdEvenement(array('idEvenement'=>$idSousEvenement));

                $resAdresses = $this->connexionBdd->requete($reqAdresses);
                $arrayVilles=array();
                $arrayAdresses = array();
                while ($fetchAdresses = mysql_fetch_assoc($resAdresses)) {
                    $arrayVilles[] = $adresse->getIdVilleFrom($fetchAdresses['idAdresse'], 'idAdresse');
                    $arrayAdresses[] = $fetchAdresses['idAdresse'];
                }

                $arrayVilles = array_unique($arrayVilles);
                $arrayAdresses = array_unique($arrayAdresses);

                if ($idPerson=archiPersonne::isPerson($idEvenementGroupeAdresse)) {
                    header("Location: ".$this->creerUrl('', '', array('archiAffichage'=>'evenementListe', 'selection'=>"personne", 'id'=>$idPerson), false, false));
                }

                // ************************************************************************************************************************************************
                // envoi d'un mail a l'auteur de l'adresse
                // ************************************************************************************************************************************************
                $utilisateur = new archiUtilisateur();
                $arrayUtilisateurs = $utilisateur->getCreatorsFromAdresseFrom($idSousEvenement, 'idEvenement');

                $intituleAdresse = $adresse->getIntituleAdresseFrom($idSousEvenement, 'idEvenement');
                foreach ($arrayUtilisateurs as $indice => $idUtilisateurAdresse) {
                    if ($idUtilisateurAdresse != $aAuthentification->getIdUtilisateur()) {
                        $infosUtilisateur = $utilisateur->getArrayInfosFromUtilisateur($idUtilisateurAdresse);
                        if ($infosUtilisateur['alerteAdresses']=='1' && $infosUtilisateur['compteActif']=='1' && $infosUtilisateur['idProfil']!='4') {
                            $messageDebut = "Un utilisateur a ajouté un événement sur une adresse dont vous êtes l'auteur.";
                            $messageDebut.= "Pour vous rendre sur l'événement : <br>";
                            $messageDebut.="<a href='".$this->creerUrl('', '', array('archiAffichage'=>'adresseDetail','archiIdAdresse'=>$arrayAdresses[0],'archiIdEvenementGroupeAdresse'=>$idEvenementGroupeAdresse))."'>".$intituleAdresse."</a><br>";
                            $messageFin= $this->getMessageDesabonnerAlerteMail();

                            if ($utilisateur->isMailEnvoiImmediat($idUtilisateurAdresse)) {
                                $mail->sendMail($mail->getSiteMail(), $infosUtilisateur['mail'], 'Mise a jour d\'un événement d\'une adresse dont vous êtes l\'auteur.', $messageDebut.$messageFin, true);
                            } else {
                                $utilisateur->ajouteMailEnvoiRegroupes(array('contenu'=>$messageDebut,'idDestinataire'=>$idUtilisateurAdresse,'idTypeMailRegroupement'=>10));
                            }
                        }
                    }
                }
                // ************************************************************************************************************************************************

                // ************************************************************************************************************************************************
                // envoi au administrateurs qui sont en mode alerteAdresse
                // ************************************************************************************************************************************************

                $message = "";
                $message .= "Un nouvel événement a été ajouté sur l'adresse suivante : <br>";
                $message.="<a href='".$this->creerUrl('', '', array('archiAffichage'=>'adresseDetail','archiIdAdresse'=>$arrayAdresses[0],'archiIdEvenementGroupeAdresse'=>$idEvenementGroupeAdresse))."'>".$adresse->getIntituleAdresseFrom($idSousEvenement, 'idEvenement')."</a>";

                $mail->sendMailToAdministrators($mail->getSiteMail(), "Un nouvel événement a été ajouté - ".$intituleAdresse, $message, " AND alerteAdresses='1' ", true);
                $utilisateur->ajouteMailEnvoiRegroupesAdministrateurs(array('contenu'=>$message,'idTypeMailRegroupement'=>10,'criteres'=>" and alerteAdresses='1' "));
                // ************************************************************************************************************************************************

                // *************************************************************************************************************************************************************
                // envoi mail aussi au moderateur si ajout sur adresse de ville que celui ci modere
                $u = new archiUtilisateur();


                $arrayListeModerateurs = $u->getArrayIdModerateursActifsFromVille($arrayVilles[0], array("sqlWhere"=>" AND alerteAdresses='1' "));
                if (count($arrayListeModerateurs)>0) {
                    foreach ($arrayListeModerateurs as $indice => $idModerateur) {
                        if ($aAuthentification->getIdUtilisateur()!=$idModerateur) {
                            if ($u->isMailEnvoiImmediat($idModerateur)) {
                                $mailModerateur = $u->getMailUtilisateur($idModerateur);
                                $mail->sendMail($mail->getSiteMail(), $mailModerateur, "Un nouvel événement a été ajouté - ".$intituleAdresse, $message, true);
                            } else {
                                $u->ajouteMailEnvoiRegroupes(array('contenu'=>$message,'idDestinataire'=>$idModerateur,'idTypeMailRegroupement'=>10));
                            }
                        }
                    }
                }

                // *************************************************************************************************************************************************************

                if ($idPerson=archiPersonne::isPerson($idEvenementGroupeAdresse)) {
                    header("Location: ".$this->creerUrl('', '', array('archiAffichage'=>'evenementListe', 'selection'=>"personne", 'id'=>$idPerson), false, false));
                } else {
                    $adresse = new archiAdresse();
                    $idGroupeAdresse = $this->getParent($idSousEvenement);
                    $idAdresse = $this->getIdAdresseFromIdEvenementGroupeAdresse($idGroupeAdresse);

                    $url= $this->creerUrl(
                        '',
                        '',
                        array(
                                'archiAffichage'=>'adresseDetail',
                                "archiIdAdresse"=>$idAdresse,
                                "archiIdEvenementGroupeAdresse"=>$idGroupeAdresse
                        )
                    );
                        header("Location: ".htmlspecialchars_decode($url));
                }
            }
        } else {
            $html .= $this->afficheFormulaire($tabForm);
        }

        return $html;
    }
607062
public function sendNotificationsReply($tid, $cur_posting, $new_pid, $post)
    {
        Container::get('hooks')->fire('model.post.send_notifications_reply_start', $tid, $cur_posting, $new_pid, $post);

        // Get the post time for the previous post in this topic
        $previous_post_time = DB::forTable('posts')
            ->select('posted')
            ->where('topic_id', $tid)
            ->order_by_desc('id');
        $previous_post_time = Container::get('hooks')->fireDB(
            'model.post.send_notifications_reply_previous',
            $previous_post_time
        );
        $previous_post_time = $previous_post_time->find_one();

        // Get any subscribed users that should be notified (banned users are excluded)
//        $result['where'] = array(
//            array('fp.read_forum' => 'IS NULL'),
//            array('fp.read_forum' => '1')
//        );
        $result['select'] = ['u.id', 'u.email', 'u.notify_with_post', 'u.language'];

        $result = DB::forTable('users')
                    ->table_alias('u')
                    ->select_many($result['select'])
                    ->inner_join(DB::prefix().'topic_subscriptions', ['u.id', '=', 's.user_id'], 's')
//                    ->left_outer_join('forum_perms', array('fp.forum_id', '=', $cur_posting['id']), 'fp', true)
//                    ->left_outer_join('forum_perms', array('fp.group_id', '=', 'u.group_id'))
            ->left_outer_join(
                DB::prefix().'forum_perms',
                '(fp.group_id=u.group_id AND fp.forum_id='. $cur_posting['id'].')',
                'fp'
            )
                    ->left_outer_join(DB::prefix().'online', ['u.id', '=', 'o.user_id'], 'o')
                    ->left_outer_join(DB::prefix().'bans', ['u.username', '=', 'b.username'], 'b')
                    ->where_raw('COALESCE(o.logged, u.last_visit)>'.$previous_post_time->posted)
                    ->where_null('b.username')
                    ->where_raw('(fp.read_forum IS NULL OR fp.read_forum=1)')
                    ->where('s.topic_id', $tid)
                    ->where_not_equal('u.id', User::get()->id);
        $result = Container::get('hooks')->fireDB('model.post.send_notifications_reply_query', $result);
        $result = $result->find_many();

        if ($result) {
            $notification_emails = [];

            $censored_message = Utils::trim(Utils::censor($post['message']));

            if (ForumSettings::get('o_censoring') == '1') {
                $cleaned_message = Container::get('email')->bbcode2email($censored_message, -1);
            } else {
                $cleaned_message = Container::get('email')->bbcode2email($post['message'], -1);
            }

            // Loop through subscribed users and send emails
            foreach ($result as $cur_subscriber) {
                // Is the subscription email for $cur_subscriber['language'] cached or not?
                if (!isset($notification_emails[$cur_subscriber['language']])) {
//                    if (file_exists(ForumEnv::get('FORUM_ROOT').'lang/'.$cur_subscriber['language'].
//                        '/mail_templates/new_reply.tpl')) {
                        $mail_tpl = Lang::getMailTemplate('new_reply')->text;
                    if ($mail_tpl) {
                        // Load the "new reply" template
//                        $mail_tpl = trim(file_get_contents(ForumEnv::get('FORUM_ROOT').'lang/'.
//                            $cur_subscriber['language'].'/mail_templates/new_reply.tpl'));
                        $mail_tpl = Container::get('hooks')->fire(
                            'model.post.send_notifications_reply_mail_tpl',
                            $mail_tpl
                        );

                        // Load the "new reply full" template (with post included)
//                        $mail_tpl_full = trim(file_get_contents(ForumEnv::get('FORUM_ROOT').'lang/'.
//                            $cur_subscriber['language'].'/mail_templates/new_reply_full.tpl'));
                        $mail_tpl_full = Lang::getMailTemplate('new_reply_full')->text;

                        $mail_tpl_full = Container::get('hooks')->fire(
                            'model.post.send_notifications_reply_mail_tpl_full',
                            $mail_tpl_full
                        );

                        // The first row contains the subject (it also starts with "Subject:")
                        $first_crlf = strpos($mail_tpl, "\n");
                        $mail_subject = trim(substr($mail_tpl, 8, $first_crlf-8));
                        $mail_subject = Container::get('hooks')->fire(
                            'model.post.send_notifications_reply_mail_subject',
                            $mail_subject
                        );
                        $mail_message = trim(substr($mail_tpl, $first_crlf));

                        $first_crlf = strpos($mail_tpl_full, "\n");
                        $mail_subject_full = trim(substr($mail_tpl_full, 8, $first_crlf-8));
                        $mail_message_full = trim(substr($mail_tpl_full, $first_crlf));

                        $mail_subject = str_replace('<topic_subject>', $cur_posting['subject'], $mail_subject);
                        $mail_message = str_replace('<topic_subject>', $cur_posting['subject'], $mail_message);
                        $mail_message = str_replace('<replier>', $post['username'], $mail_message);
                        $mail_message = str_replace(
                            '<post_url>',
                            Router::pathFor('viewPost', ['pid' => $new_pid]).'#p'.$new_pid,
                            $mail_message
                        );
                        $mail_message = str_replace(
                            '<unsubscribe_url>',
                            Router::pathFor('unsubscribeTopic', ['id' => $tid]),
                            $mail_message
                        );
                        $mail_message = str_replace(
                            '<board_mailer>',
                            ForumSettings::get('o_board_title'),
                            $mail_message
                        );
                        $mail_message = Container::get('hooks')->fire(
                            'model.post.send_notifications_reply_mail_message',
                            $mail_message
                        );

                        $mail_subject_full = str_replace(
                            '<topic_subject>',
                            $cur_posting['subject'],
                            $mail_subject_full
                        );
                        $mail_message_full = str_replace(
                            '<topic_subject>',
                            $cur_posting['subject'],
                            $mail_message_full
                        );
                        $mail_message_full = str_replace('<replier>', $post['username'], $mail_message_full);
                        $mail_message_full = str_replace('<message>', $cleaned_message, $mail_message_full);
                        $mail_message_full = str_replace(
                            '<post_url>',
                            Router::pathFor('viewPost', ['pid' => $new_pid]).'#p'.$new_pid,
                            $mail_message_full
                        );
                        $mail_message_full = str_replace(
                            '<unsubscribe_url>',
                            Router::pathFor('unsubscribeTopic', ['id' => $tid]),
                            $mail_message_full
                        );
                        $mail_message_full = str_replace(
                            '<board_mailer>',
                            ForumSettings::get('o_board_title'),
                            $mail_message_full
                        );
                        $mail_message_full = Container::get('hooks')->fire(
                            'model.post.send_notifications_reply_mail_message_full',
                            $mail_message_full
                        );

                        $notification_emails[$cur_subscriber['language']][0] = $mail_subject;
                        $notification_emails[$cur_subscriber['language']][1] = $mail_message;
                        $notification_emails[$cur_subscriber['language']][2] = $mail_subject_full;
                        $notification_emails[$cur_subscriber['language']][3] = $mail_message_full;

                        $mail_subject = $mail_message = $mail_subject_full = $mail_message_full = null;
                    }
                }

                // We have to double check here because the templates could be missing
                if (isset($notification_emails[$cur_subscriber['language']])) {
                    if ($cur_subscriber['notify_with_post'] == '0') {
                        Container::get('email')->dispatchMail(
                            $cur_subscriber['email'],
                            $notification_emails[$cur_subscriber['language']][0],
                            $notification_emails[$cur_subscriber['language']][1]
                        );
                    } else {
                        Container::get('email')->dispatchMail(
                            $cur_subscriber['email'],
                            $notification_emails[$cur_subscriber['language']][2],
                            $notification_emails[$cur_subscriber['language']][3]
                        );
                    }
                }
            }

            Container::get('hooks')->fire('model.post.send_notifications_reply');

            unset($cleaned_message);
        }
    }
1015021
static <T1, T2, T3, T4> Flowable<Notification<Tuple4<T1, T2, T3, T4>>> createWithFourOutParameters(
            Single<Connection> connection, String sql, Flowable<List<Object>> parameterGroups,
            List<ParameterPlaceholder> parameterPlaceholders, Class<T1> cls1, Class<T2> cls2, Class<T3> cls3,
            Class<T4> cls4) {
        return connection.toFlowable()
                .flatMap(con -> createWithParameters(con, sql, parameterGroups, parameterPlaceholders,
                        (stmt, parameters) -> createWithFourParameters(stmt, parameters, parameterPlaceholders, cls1,
                                cls2, cls3, cls4)));
    }